text
stringlengths
54
60.6k
<commit_before>#include "vast/configuration.h" #include "config.h" #include <iostream> #include <string> #include <boost/exception/diagnostic_information.hpp> #include "vast/exception.h" #include "vast/fs/path.h" #include "vast/fs/fstream.h" #include "vast/fs/operations.h" #include "vast/logger.h" namespace vast { configuration::configuration() : visible_("") , all_("") { po::options_description general("general options"); general.add_options() ("config,c", po::value<fs::path>(), "configuration file") ("directory,d", po::value<fs::path>()->default_value("vast"), "VAST directory") ("help,h", "display this help") ("advanced,z", "show advanced options") ; po::options_description logger("logger options"); logger.add_options() ("log.console-verbosity,v", po::value<int>()->default_value(logger::info), "console verbosity") ("log.file-verbosity,V", po::value<int>()->default_value(logger::verbose), "log file verbosity") ("log.directory", po::value<fs::path>()->default_value(fs::path("vast") / "log"), "log direcotory") ; po::options_description advanced("advanced options"); advanced.add_options() ("profile,P", po::value<unsigned>(), "enable getrusage profiling at a given interval (seconds)") #ifdef USE_PERFTOOLS_CPU_PROFILER ("profile-cpu", "also enable Google perftools CPU profiling") #endif #ifdef USE_PERFTOOLS_HEAP_PROFILER ("profile-heap", "also enable Google perftools heap profiling") #endif ("broccoli-messages", "enable broccoli debug messages") ("broccoli-calltrace", "enable broccoli function call tracing") ; po::options_description actor("actor options"); actor.add_options() ("all-server,a", "spawn all server components") ("ingestor-actor,I", "spawn the ingestor locally") ("archive-actor,A", "spawn the archive locally") ("index-actor,X", "spawn the index locally") ("search-actor,S", "spawn the search locally") ("tracker-actor,T", "spawn the ID tracker locally") ; po::options_description schema("schema options"); schema.add_options() ("schema.file,s", po::value<std::string>(), "schema file") ("schema.print", "print the parsed event schema") ; po::options_description tracker("ID tracker options"); tracker.add_options() ("tracker.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the ID tracker") ("tracker.port", po::value<unsigned>()->default_value(42004), "TCP port of the ID tracker") ; po::options_description ingest("ingest options"); ingest.add_options() ("ingest.max-events-per-chunk", po::value<size_t>()->default_value(1000), "maximum number of events per chunk") ("ingest.max-segment-size", po::value<size_t>()->default_value(1), "maximum segment size in MB") ("ingest.batch-size", po::value<size_t>()->default_value(1000), "number of events to ingest before yielding") ("ingest.broccoli-host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the broccoli source") ("ingest.broccoli-port", po::value<unsigned>()->default_value(42000), "port of the broccoli source") ("ingest.broccoli-events", po::value<std::vector<std::string>>()->multitoken(), "explicit list of events for broccoli to ingest") ("ingest.file-names", po::value<std::vector<std::string>>()->multitoken(), "file(s) to ingest") ("ingest.file-type", po::value<std::string>()->default_value("bro2"), "file type of the file(s) to ingest") ; po::options_description archive("archive options"); archive.add_options() ("archive.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the archive") ("archive.port", po::value<unsigned>()->default_value(42002), "port of the archive") ("archive.max-segments", po::value<size_t>()->default_value(500), "maximum number of segments to keep in memory") ; po::options_description index("index options"); index.add_options() ("index.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the index") ("index.port", po::value<unsigned>()->default_value(42003), "port of the index") ; po::options_description search("search options"); search.add_options() ("search.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the search") ("search.port", po::value<unsigned>()->default_value(42001), "port of the search") ; po::options_description client("client options"); client.add_options() ("client.expression,e", po::value<std::string>(), "query expression") ("client.paginate,p", po::value<unsigned>()->default_value(10), "number of query results per page") ; all_.add(general).add(logger).add(advanced).add(actor).add(schema) .add(tracker).add(ingest).add(archive).add(index).add(search).add(client); visible_.add(general).add(actor); } bool configuration::load(std::string const& filename) { try { if (! fs::exists(filename)) return false; fs::ifstream ifs(filename); po::store(po::parse_config_file(ifs, all_), config_); init(); return true; } catch (error::config const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } bool configuration::load(int argc, char *argv[]) { try { po::store(parse_command_line(argc, argv, all_), config_); if (check("config")) { fs::path const& cfg = get<fs::path>("config"); std::ifstream ifs(cfg.string().data()); po::store(po::parse_config_file(ifs, all_), config_); } init(); return true; } catch (error::config const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } catch (boost::program_options::invalid_command_line_syntax const& e) { std::cerr << "invalid command line: " << e.what() << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } bool configuration::check(char const* option) const { return config_.count(option); } void configuration::print(std::ostream& out, bool advanced) const { out << " _ _____ __________\n" "| | / / _ | / __/_ __/\n" "| |/ / __ |_\\ \\ / /\n" "|___/_/ |_/___/ /_/ " << VAST_VERSION << '\n' << (advanced ? all_ : visible_) << std::endl; } void configuration::init() { po::notify(config_); depends("schema.print", "schema.file"); auto cv = get<int>("log.console-verbosity"); if (cv < 0 || cv > 6) throw error::config("verbosity not in [0,6]", "log.console-verbosity"); auto fv = get<int>("log.file-verbosity"); if (fv < 0 || fv > 6) throw error::config("verbosity not in [0,6]", "log.file-verbosity"); if (check("profile") && get<unsigned>("profile") == 0) throw error::config("profiling interval must be non-zero", "profile"); depends("client.paginate", "client.expression"); conflicts("client.expression", "tracker-actor"); conflicts("client.expression", "archive-actor"); conflicts("client.expression", "index-actor"); conflicts("client.expression", "search-actor"); if (get<unsigned>("client.paginate") == 0) throw error::config("pagination must be non-zero", "client.paginate"); auto log_dir = get<fs::path>("log.directory"); auto log_file = log_dir / "vast.log"; if (! fs::exists(log_dir)) fs::mkdir(log_dir); logger::init( static_cast<logger::level>(cv), static_cast<logger::level>(fv), log_file); } void configuration::conflicts(const char* opt1, const char* opt2) const { if (check(opt1) && ! config_[opt1].defaulted() && check(opt2) && ! config_[opt2].defaulted()) throw error::config("conflicting options", opt1, opt2); } void configuration::depends(const char* for_what, const char* required) const { if (check(for_what) && ! config_[for_what].defaulted() && (! check(required) || config_[required].defaulted())) throw error::config("missing option dependency", for_what, required); } } // namespace vast <commit_msg>Create log directory inside main directory.<commit_after>#include "vast/configuration.h" #include "config.h" #include <iostream> #include <string> #include <boost/exception/diagnostic_information.hpp> #include "vast/exception.h" #include "vast/fs/path.h" #include "vast/fs/fstream.h" #include "vast/fs/operations.h" #include "vast/logger.h" namespace vast { configuration::configuration() : visible_("") , all_("") { po::options_description general("general options"); general.add_options() ("config,c", po::value<fs::path>(), "configuration file") ("directory,d", po::value<fs::path>()->default_value("vast"), "VAST directory") ("help,h", "display this help") ("advanced,z", "show advanced options") ; po::options_description logger("logger options"); logger.add_options() ("log.console-verbosity,v", po::value<int>()->default_value(logger::info), "console verbosity") ("log.file-verbosity,V", po::value<int>()->default_value(logger::verbose), "log file verbosity") ("log.directory", po::value<fs::path>()->default_value("log"), "log direcotory") ; po::options_description advanced("advanced options"); advanced.add_options() ("profile,P", po::value<unsigned>(), "enable getrusage profiling at a given interval (seconds)") #ifdef USE_PERFTOOLS_CPU_PROFILER ("profile-cpu", "also enable Google perftools CPU profiling") #endif #ifdef USE_PERFTOOLS_HEAP_PROFILER ("profile-heap", "also enable Google perftools heap profiling") #endif ("broccoli-messages", "enable broccoli debug messages") ("broccoli-calltrace", "enable broccoli function call tracing") ; po::options_description actor("actor options"); actor.add_options() ("all-server,a", "spawn all server components") ("ingestor-actor,I", "spawn the ingestor locally") ("archive-actor,A", "spawn the archive locally") ("index-actor,X", "spawn the index locally") ("search-actor,S", "spawn the search locally") ("tracker-actor,T", "spawn the ID tracker locally") ; po::options_description schema("schema options"); schema.add_options() ("schema.file,s", po::value<std::string>(), "schema file") ("schema.print", "print the parsed event schema") ; po::options_description tracker("ID tracker options"); tracker.add_options() ("tracker.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the ID tracker") ("tracker.port", po::value<unsigned>()->default_value(42004), "TCP port of the ID tracker") ; po::options_description ingest("ingest options"); ingest.add_options() ("ingest.max-events-per-chunk", po::value<size_t>()->default_value(1000), "maximum number of events per chunk") ("ingest.max-segment-size", po::value<size_t>()->default_value(1), "maximum segment size in MB") ("ingest.batch-size", po::value<size_t>()->default_value(1000), "number of events to ingest before yielding") ("ingest.broccoli-host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the broccoli source") ("ingest.broccoli-port", po::value<unsigned>()->default_value(42000), "port of the broccoli source") ("ingest.broccoli-events", po::value<std::vector<std::string>>()->multitoken(), "explicit list of events for broccoli to ingest") ("ingest.file-names", po::value<std::vector<std::string>>()->multitoken(), "file(s) to ingest") ("ingest.file-type", po::value<std::string>()->default_value("bro2"), "file type of the file(s) to ingest") ; po::options_description archive("archive options"); archive.add_options() ("archive.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the archive") ("archive.port", po::value<unsigned>()->default_value(42002), "port of the archive") ("archive.max-segments", po::value<size_t>()->default_value(500), "maximum number of segments to keep in memory") ; po::options_description index("index options"); index.add_options() ("index.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the index") ("index.port", po::value<unsigned>()->default_value(42003), "port of the index") ; po::options_description search("search options"); search.add_options() ("search.host", po::value<std::string>()->default_value("127.0.0.1"), "hostname or IP address of the search") ("search.port", po::value<unsigned>()->default_value(42001), "port of the search") ; po::options_description client("client options"); client.add_options() ("client.expression,e", po::value<std::string>(), "query expression") ("client.paginate,p", po::value<unsigned>()->default_value(10), "number of query results per page") ; all_.add(general).add(logger).add(advanced).add(actor).add(schema) .add(tracker).add(ingest).add(archive).add(index).add(search).add(client); visible_.add(general).add(actor); } bool configuration::load(std::string const& filename) { try { if (! fs::exists(filename)) return false; fs::ifstream ifs(filename); po::store(po::parse_config_file(ifs, all_), config_); init(); return true; } catch (error::config const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } bool configuration::load(int argc, char *argv[]) { try { po::store(parse_command_line(argc, argv, all_), config_); if (check("config")) { fs::path const& cfg = get<fs::path>("config"); std::ifstream ifs(cfg.string().data()); po::store(po::parse_config_file(ifs, all_), config_); } init(); return true; } catch (error::config const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } catch (boost::program_options::invalid_command_line_syntax const& e) { std::cerr << "invalid command line: " << e.what() << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } bool configuration::check(char const* option) const { return config_.count(option); } void configuration::print(std::ostream& out, bool advanced) const { out << " _ _____ __________\n" "| | / / _ | / __/_ __/\n" "| |/ / __ |_\\ \\ / /\n" "|___/_/ |_/___/ /_/ " << VAST_VERSION << '\n' << (advanced ? all_ : visible_) << std::endl; } void configuration::init() { po::notify(config_); depends("schema.print", "schema.file"); auto cv = get<int>("log.console-verbosity"); if (cv < 0 || cv > 6) throw error::config("verbosity not in [0,6]", "log.console-verbosity"); auto fv = get<int>("log.file-verbosity"); if (fv < 0 || fv > 6) throw error::config("verbosity not in [0,6]", "log.file-verbosity"); if (check("profile") && get<unsigned>("profile") == 0) throw error::config("profiling interval must be non-zero", "profile"); depends("client.paginate", "client.expression"); conflicts("client.expression", "tracker-actor"); conflicts("client.expression", "archive-actor"); conflicts("client.expression", "index-actor"); conflicts("client.expression", "search-actor"); if (get<unsigned>("client.paginate") == 0) throw error::config("pagination must be non-zero", "client.paginate"); auto log_dir = get<fs::path>("directory") / get<fs::path>("log.directory"); auto log_file = log_dir / "vast.log"; if (! fs::exists(log_dir)) fs::mkdir(log_dir); logger::init( static_cast<logger::level>(cv), static_cast<logger::level>(fv), log_file); } void configuration::conflicts(const char* opt1, const char* opt2) const { if (check(opt1) && ! config_[opt1].defaulted() && check(opt2) && ! config_[opt2].defaulted()) throw error::config("conflicting options", opt1, opt2); } void configuration::depends(const char* for_what, const char* required) const { if (check(for_what) && ! config_[for_what].defaulted() && (! check(required) || config_[required].defaulted())) throw error::config("missing option dependency", for_what, required); } } // namespace vast <|endoftext|>
<commit_before>#pragma once #include <cstdlib> // std::aligned_alloc (C++17) & std::free #include <stdint.h> // uintptr_t #include <cstring> // std::memset #include <stdexcept> // std::runtime_error #if ANYODE_NO_LAPACK == 1 #include "anyode/anyode_blasless.hpp" #else #include "anyode/anyode_blas_lapack.hpp" #endif namespace AnyODE { template<typename T> constexpr std::size_t n_padded(std::size_t n, int alignment_bytes){ return ((n*sizeof(T) + alignment_bytes - 1) & ~(alignment_bytes - 1)) / sizeof(T); } static constexpr int alignment_bytes_ = 64; // L1 cache line template<typename Real_t> class MatrixBase { void * m_own_array_ = nullptr; Real_t * alloc_array_(int n){ m_own_array_ = std::malloc(sizeof(Real_t)*n + alignment_bytes_ - 1); const uintptr_t mask = ~uintptr_t(alignment_bytes_ - 1); const uintptr_t addr = reinterpret_cast<uintptr_t>(m_own_array_); const uintptr_t candidate = addr + alignment_bytes_ - 1; return static_cast<Real_t *>(reinterpret_cast<void *>(candidate & mask)); } public: Real_t * m_data; int m_nr, m_nc, m_ld, m_ndata; bool m_own_data; MatrixBase(Real_t * const data, int nr, int nc, int ld, int ndata, bool own_data=false) : m_data(data ? data : alloc_array_(ndata)), m_nr(nr), m_nc(nc), m_ld(ld), m_ndata(ndata), m_own_data(own_data) { if (data == nullptr && own_data) throw std::runtime_error("own_data not needed for nullptr"); } MatrixBase(const MatrixBase<Real_t>& ori) : MatrixBase(nullptr, ori.m_nr, ori.m_nc, ori.m_ld, ori.m_ndata) { std::copy(ori.m_data, ori.m_data + m_ndata, m_data); } virtual ~MatrixBase(){ if (m_own_array_) std::free(m_own_array_); if (m_own_data && m_data) std::free(m_data); } virtual Real_t& operator()(int /* ri */, int /* ci */) { throw std::runtime_error("Not implemented: operator() in MatrixBase"); } const Real_t& operator()(int ri, int ci) const { return (*const_cast<MatrixBase<Real_t>* >(this))(ri, ci); } virtual bool valid_index(const int ri, const int ci) const { return (0 <= ri) && (ri < this->m_nr) && (0 <= ci) && (ci < this->m_nc); } virtual bool guaranteed_zero_index(int /* ri */, int /* ci */) const { throw std::runtime_error("Not implemented: guaranteed_zero_index"); }; virtual void dot_vec(const Real_t * const, Real_t * const) { throw std::runtime_error("Not implemented: dot_vec"); }; virtual void set_to_eye_plus_scaled_mtx(Real_t, const MatrixBase&) { throw std::runtime_error("Not implemented: set_to_eye_plus_scaled_mtx"); }; void set_to(Real_t value) noexcept { std::memset(m_data, value, m_ndata*sizeof(Real_t)); } }; template<typename Real_t = double> struct DenseMatrix : public MatrixBase<Real_t> { bool m_colmaj; DenseMatrix(Real_t * const data, int nr, int nc, int ld, bool colmaj=true, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*(colmaj ? nc : nr), own_data), m_colmaj(colmaj) {} DenseMatrix(const DenseMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_colmaj(ori.m_colmaj) {} DenseMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, source.m_nr, source.m_nr*source.m_nc), m_colmaj(true) { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = source(ri, ci); } } } Real_t& operator()(int ri, int ci) noexcept override final { const int imaj = m_colmaj ? ci : ri; const int imin = m_colmaj ? ri : ci; return this->m_data[imaj*this->m_ld + imin]; } virtual bool guaranteed_zero_index(const int /* ri */, const int /* ci */) const override { return false; } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; char trans= m_colmaj ? 'N' : 'T'; constexpr gemv_callback<Real_t> gemv{}; gemv(&trans, &(this->m_nr), &(this->m_nc), &alpha, this->m_data, &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = scale*source(ri, ci) + ((imaj == imin) ? 1 : 0); } } } }; template<typename Real_t=double> struct DiagonalMatrix : public MatrixBase<Real_t> { // single diagonal static constexpr bool m_colmaj = true; DiagonalMatrix(Real_t * const data, int nr, int nc, int ld, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*nc, own_data) { } Real_t& operator()(int /* ri */, int ci) noexcept override final { return this->m_data[ci*this->m_ld]; } void read(const MatrixBase<Real_t>& source){ for (int i = 0; i < this->m_nc; ++i){ (*this)(i, i) = (source.guaranteed_zero_index(i, i)) ? 0 : source(i, i); } } DiagonalMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, std::min(source.m_nr, source.m_nc), std::min(source.m_nr, source.m_nc), 1, std::min(source.m_nr, source.m_nc)) { read(source); } DiagonalMatrix(const DiagonalMatrix<Real_t> &ori) : MatrixBase<Real_t>(ori) { } bool guaranteed_zero_index(const int ri, const int ci) const final { return ri - ci; } void dot_vec(const Real_t * const vec, Real_t * const out) final { for (int i=0; i < this->m_nc; ++i){ out[i] = this->m_data[i]*vec[i]; } } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override { for (int i = 0; i < this->m_nc; ++i) this->m_data[i] = 1 + scale*source(i, i); } void set_to_eye_plus_scaled_mtx(Real_t scale, const DiagonalMatrix<Real_t>& source) { for (int i = 0; i < this->m_nc; ++i) this->m_data[i] = 1 + scale*source.m_data[i]; } }; #if ANYODE_NO_LAPACK != 1 constexpr int banded_padded_ld(int kl, int ku) { return 2*kl+ku+1; } template<typename Real_t = double> struct BandedMatrix : public MatrixBase<Real_t> { int m_kl, m_ku; static constexpr bool m_colmaj = true; // dgbmv takes a trans arg, but not used at the moment. #define LD (ld ? ld : banded_padded_ld(kl, ku)) BandedMatrix(Real_t * const data, int nr, int nc, int kl, int ku, int ld=0, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, LD, LD*nc, own_data), m_kl(kl), m_ku(ku) {} void read(const MatrixBase<Real_t>& source){ for (int ci = 0; ci < this->m_nc; ++ci){ for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri){ (*this)(ri, ci) = (source.guaranteed_zero_index(ri, ci)) ? 0 : source(ri, ci); } } } BandedMatrix(const MatrixBase<Real_t>& source, int kl, int ku, int ld=0) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, LD, LD*source.m_nc), m_kl(kl), m_ku(ku) { read(source); } #undef LD BandedMatrix(const BandedMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_kl(ori.m_kl), m_ku(ori.m_ku) {} Real_t& operator()(int ri, int ci) noexcept override final { return this->m_data[m_kl + m_ku + ri - ci + ci*this->m_ld]; // m_kl paddding } virtual bool guaranteed_zero_index(const int ri, const int ci) const override { const int delta = ri - ci; return (this->m_ku < delta) || (delta < -(this->m_kl)); } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; const char trans='N'; constexpr gbmv_callback<Real_t> gbmv{}; gbmv(&trans, &(this->m_nr), &(this->m_nc), &(m_kl), &(m_ku), &alpha, this->m_data+m_kl, // m_kl padding &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int ci = 0; ci < this->m_nc; ++ci) for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri) (*this)(ri, ci) = scale*source(ri, ci) + ((ri == ci) ? 1 : 0); } }; #endif } <commit_msg>always define macro ANYODE_NO_LAPACK<commit_after>#pragma once #include <cstdlib> // std::aligned_alloc (C++17) & std::free #include <stdint.h> // uintptr_t #include <cstring> // std::memset #include <stdexcept> // std::runtime_error #if !defined(ANYODE_NO_LAPACK) #define ANYODE_NO_LAPACK 0 #endif #if ANYODE_NO_LAPACK == 1 #include "anyode/anyode_blasless.hpp" #else #include "anyode/anyode_blas_lapack.hpp" #endif namespace AnyODE { template<typename T> constexpr std::size_t n_padded(std::size_t n, int alignment_bytes){ return ((n*sizeof(T) + alignment_bytes - 1) & ~(alignment_bytes - 1)) / sizeof(T); } static constexpr int alignment_bytes_ = 64; // L1 cache line template<typename Real_t> class MatrixBase { void * m_own_array_ = nullptr; Real_t * alloc_array_(int n){ m_own_array_ = std::malloc(sizeof(Real_t)*n + alignment_bytes_ - 1); const uintptr_t mask = ~uintptr_t(alignment_bytes_ - 1); const uintptr_t addr = reinterpret_cast<uintptr_t>(m_own_array_); const uintptr_t candidate = addr + alignment_bytes_ - 1; return static_cast<Real_t *>(reinterpret_cast<void *>(candidate & mask)); } public: Real_t * m_data; int m_nr, m_nc, m_ld, m_ndata; bool m_own_data; MatrixBase(Real_t * const data, int nr, int nc, int ld, int ndata, bool own_data=false) : m_data(data ? data : alloc_array_(ndata)), m_nr(nr), m_nc(nc), m_ld(ld), m_ndata(ndata), m_own_data(own_data) { if (data == nullptr && own_data) throw std::runtime_error("own_data not needed for nullptr"); } MatrixBase(const MatrixBase<Real_t>& ori) : MatrixBase(nullptr, ori.m_nr, ori.m_nc, ori.m_ld, ori.m_ndata) { std::copy(ori.m_data, ori.m_data + m_ndata, m_data); } virtual ~MatrixBase(){ if (m_own_array_) std::free(m_own_array_); if (m_own_data && m_data) std::free(m_data); } virtual Real_t& operator()(int /* ri */, int /* ci */) { throw std::runtime_error("Not implemented: operator() in MatrixBase"); } const Real_t& operator()(int ri, int ci) const { return (*const_cast<MatrixBase<Real_t>* >(this))(ri, ci); } virtual bool valid_index(const int ri, const int ci) const { return (0 <= ri) && (ri < this->m_nr) && (0 <= ci) && (ci < this->m_nc); } virtual bool guaranteed_zero_index(int /* ri */, int /* ci */) const { throw std::runtime_error("Not implemented: guaranteed_zero_index"); }; virtual void dot_vec(const Real_t * const, Real_t * const) { throw std::runtime_error("Not implemented: dot_vec"); }; virtual void set_to_eye_plus_scaled_mtx(Real_t, const MatrixBase&) { throw std::runtime_error("Not implemented: set_to_eye_plus_scaled_mtx"); }; void set_to(Real_t value) noexcept { std::memset(m_data, value, m_ndata*sizeof(Real_t)); } }; template<typename Real_t = double> struct DenseMatrix : public MatrixBase<Real_t> { bool m_colmaj; DenseMatrix(Real_t * const data, int nr, int nc, int ld, bool colmaj=true, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*(colmaj ? nc : nr), own_data), m_colmaj(colmaj) {} DenseMatrix(const DenseMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_colmaj(ori.m_colmaj) {} DenseMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, source.m_nr, source.m_nr*source.m_nc), m_colmaj(true) { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = source(ri, ci); } } } Real_t& operator()(int ri, int ci) noexcept override final { const int imaj = m_colmaj ? ci : ri; const int imin = m_colmaj ? ri : ci; return this->m_data[imaj*this->m_ld + imin]; } virtual bool guaranteed_zero_index(const int /* ri */, const int /* ci */) const override { return false; } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; char trans= m_colmaj ? 'N' : 'T'; constexpr gemv_callback<Real_t> gemv{}; gemv(&trans, &(this->m_nr), &(this->m_nc), &alpha, this->m_data, &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = scale*source(ri, ci) + ((imaj == imin) ? 1 : 0); } } } }; template<typename Real_t=double> struct DiagonalMatrix : public MatrixBase<Real_t> { // single diagonal static constexpr bool m_colmaj = true; DiagonalMatrix(Real_t * const data, int nr, int nc, int ld, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*nc, own_data) { } Real_t& operator()(int /* ri */, int ci) noexcept override final { return this->m_data[ci*this->m_ld]; } void read(const MatrixBase<Real_t>& source){ for (int i = 0; i < this->m_nc; ++i){ (*this)(i, i) = (source.guaranteed_zero_index(i, i)) ? 0 : source(i, i); } } DiagonalMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, std::min(source.m_nr, source.m_nc), std::min(source.m_nr, source.m_nc), 1, std::min(source.m_nr, source.m_nc)) { read(source); } DiagonalMatrix(const DiagonalMatrix<Real_t> &ori) : MatrixBase<Real_t>(ori) { } bool guaranteed_zero_index(const int ri, const int ci) const final { return ri - ci; } void dot_vec(const Real_t * const vec, Real_t * const out) final { for (int i=0; i < this->m_nc; ++i){ out[i] = this->m_data[i]*vec[i]; } } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override { for (int i = 0; i < this->m_nc; ++i) this->m_data[i] = 1 + scale*source(i, i); } void set_to_eye_plus_scaled_mtx(Real_t scale, const DiagonalMatrix<Real_t>& source) { for (int i = 0; i < this->m_nc; ++i) this->m_data[i] = 1 + scale*source.m_data[i]; } }; #if ANYODE_NO_LAPACK != 1 constexpr int banded_padded_ld(int kl, int ku) { return 2*kl+ku+1; } template<typename Real_t = double> struct BandedMatrix : public MatrixBase<Real_t> { int m_kl, m_ku; static constexpr bool m_colmaj = true; // dgbmv takes a trans arg, but not used at the moment. #define LD (ld ? ld : banded_padded_ld(kl, ku)) BandedMatrix(Real_t * const data, int nr, int nc, int kl, int ku, int ld=0, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, LD, LD*nc, own_data), m_kl(kl), m_ku(ku) {} void read(const MatrixBase<Real_t>& source){ for (int ci = 0; ci < this->m_nc; ++ci){ for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri){ (*this)(ri, ci) = (source.guaranteed_zero_index(ri, ci)) ? 0 : source(ri, ci); } } } BandedMatrix(const MatrixBase<Real_t>& source, int kl, int ku, int ld=0) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, LD, LD*source.m_nc), m_kl(kl), m_ku(ku) { read(source); } #undef LD BandedMatrix(const BandedMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_kl(ori.m_kl), m_ku(ori.m_ku) {} Real_t& operator()(int ri, int ci) noexcept override final { return this->m_data[m_kl + m_ku + ri - ci + ci*this->m_ld]; // m_kl paddding } virtual bool guaranteed_zero_index(const int ri, const int ci) const override { const int delta = ri - ci; return (this->m_ku < delta) || (delta < -(this->m_kl)); } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; const char trans='N'; constexpr gbmv_callback<Real_t> gbmv{}; gbmv(&trans, &(this->m_nr), &(this->m_nc), &(m_kl), &(m_ku), &alpha, this->m_data+m_kl, // m_kl padding &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int ci = 0; ci < this->m_nc; ++ci) for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri) (*this)(ri, ci) = scale*source(ri, ci) + ((ri == ci) ? 1 : 0); } }; #endif } <|endoftext|>
<commit_before>#ifndef _BLISPP_MEMORY_HPP_ #define _BLISPP_MEMORY_HPP_ #include "blis++.hpp" namespace blis { template <typename T, typename Allocator=std::allocator<T> > class Memory { public: typedef T type; private: struct _mem_s : Allocator { type* _base = NULL; _mem_s(Allocator alloc) : Allocator(alloc), _base(NULL) {} } _mem; type* _ptr = NULL; siz_t _size = 0; public: Memory(const Memory&) = delete; Memory(Memory&&) = default; Memory& operator=(const Memory&) = delete; Memory& operator=(Memory&&) = default; explicit Memory(siz_t size, Allocator alloc = Allocator()) : _mem(alloc) { reset(size); } explicit Memory(Allocator alloc = Allocator()) : _mem(alloc) {} explicit Memory(type* ptr) : _mem(Allocator()) { reset(ptr); } ~Memory() { free(); } void reset(siz_t size = 0) { free(); if (size > 0) { _mem._base = _mem.allocate(size); _size = size; _ptr = _mem._base; } } void reset(type* ptr) { free(); _ptr = ptr; } void free() { if (_mem._base) _mem.deallocate(_mem._base, _size); _mem._base = NULL; _size = 0; _ptr = NULL; } Memory& operator+=(inc_t x) { _ptr += x; return *this; } Memory& operator-=(inc_t x) { _ptr -= x; return *this; } type& operator[](dim_t i) { return _ptr[i]; } const type& operator[](dim_t i) const { return _ptr[i]; } operator type*() { return _ptr; } operator const type*() const { return _ptr; } }; template <typename T> class PooledMemory : private mem_t { public: typedef T type; private: packbuf_t _packbuf; void init() { memset(static_cast<mem_t*>(this), 0, sizeof(mem_t)); } public: PooledMemory(const PooledMemory&) = delete; PooledMemory(PooledMemory&& other) { *this = std::move(other); } PooledMemory& operator=(const PooledMemory&) = delete; PooledMemory& operator=(PooledMemory&& other) { if (this != &other) { memcpy(static_cast<mem_t*>(this), static_cast<mem_t*>(other), sizeof(mem_t)); _packbuf = other._packbuf; other.init(); } return *this; } explicit PooledMemory(packbuf_t packbuf) : _packbuf(packbuf) { init(); } explicit PooledMemory(siz_t size, packbuf_t packbuf) : _packbuf(packbuf) { init(); reset(size); } ~PooledMemory() { free(); } void reset() {} void reset(siz_t size) { if (bli_mem_is_unalloc(this)) { bli_mem_acquire_m(size, _packbuf, this); } else if (size > bli_mem_size(this)) { bli_mem_release(this); bli_mem_acquire_m(size, _packbuf, this); } } void free() { if (bli_mem_is_alloc(this)) bli_mem_release(this); } operator type*() { return (type*)bli_mem_buffer(this); } operator const type*() const { return (type*)bli_mem_buffer(this); } }; } #endif <commit_msg>Default move operators for Memory were invalid.<commit_after>#ifndef _BLISPP_MEMORY_HPP_ #define _BLISPP_MEMORY_HPP_ #include "blis++.hpp" namespace blis { template <typename T, typename Allocator=std::allocator<T> > class Memory { public: typedef T type; private: struct _mem_s : Allocator { type* _base = NULL; _mem_s(Allocator alloc) : Allocator(alloc), _base(NULL) {} } _mem; type* _ptr = NULL; siz_t _size = 0; public: Memory(const Memory&) = delete; Memory(Memory&& other) : _ptr(other._ptr), _size(other._size) { std::swap(_mem._base, other._mem._base); } Memory& operator=(const Memory&) = delete; Memory& operator=(Memory&& other) { std::swap(_ptr, other._ptr); std::swap(_size, other._size); std::swap(_mem._base, other._mem._base); return *this; } explicit Memory(siz_t size, Allocator alloc = Allocator()) : _mem(alloc) { reset(size); } explicit Memory(Allocator alloc = Allocator()) : _mem(alloc) {} explicit Memory(type* ptr) : _mem(Allocator()) { reset(ptr); } ~Memory() { free(); } void reset(siz_t size = 0) { free(); if (size > 0) { _mem._base = _mem.allocate(size); _size = size; _ptr = _mem._base; } } void reset(type* ptr) { free(); _ptr = ptr; } void free() { if (_mem._base) _mem.deallocate(_mem._base, _size); _mem._base = NULL; _size = 0; _ptr = NULL; } Memory& operator+=(inc_t x) { _ptr += x; return *this; } Memory& operator-=(inc_t x) { _ptr -= x; return *this; } type& operator[](dim_t i) { return _ptr[i]; } const type& operator[](dim_t i) const { return _ptr[i]; } operator type*() { return _ptr; } operator const type*() const { return _ptr; } }; template <typename T> class PooledMemory : private mem_t { public: typedef T type; private: packbuf_t _packbuf; void init() { memset(static_cast<mem_t*>(this), 0, sizeof(mem_t)); } public: PooledMemory(const PooledMemory&) = delete; PooledMemory(PooledMemory&& other) { *this = std::move(other); } PooledMemory& operator=(const PooledMemory&) = delete; PooledMemory& operator=(PooledMemory&& other) { if (this != &other) { memcpy(static_cast<mem_t*>(this), static_cast<mem_t*>(other), sizeof(mem_t)); _packbuf = other._packbuf; other.init(); } return *this; } explicit PooledMemory(packbuf_t packbuf) : _packbuf(packbuf) { init(); } explicit PooledMemory(siz_t size, packbuf_t packbuf) : _packbuf(packbuf) { init(); reset(size); } ~PooledMemory() { free(); } void reset() {} void reset(siz_t size) { if (bli_mem_is_unalloc(this)) { bli_mem_acquire_m(size, _packbuf, this); } else if (size > bli_mem_size(this)) { bli_mem_release(this); bli_mem_acquire_m(size, _packbuf, this); } } void free() { if (bli_mem_is_alloc(this)) bli_mem_release(this); } operator type*() { return (type*)bli_mem_buffer(this); } operator const type*() const { return (type*)bli_mem_buffer(this); } }; } #endif <|endoftext|>
<commit_before>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2016 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/. */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <array> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \tparam T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (& array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using const std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the const array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \brief ContiguousRange's copy constructor * * \param [in] other is a reference to source of copy */ constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<T>::type>& other) noexcept : begin_{other.begin()}, end_{other.end()} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return const_iterator to first element in the range */ constexpr const_iterator cbegin() const noexcept { return begin(); } /** * \return const_iterator to "one past the last" element in the range */ constexpr const_iterator cend() const noexcept { return end(); } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range iterator begin_; /// iterator to "one past the last" element in the range iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <commit_msg>Add ContiguousRange::rend()<commit_after>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2016 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/. */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <array> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \tparam T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (& array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using const std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the const array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \brief ContiguousRange's copy constructor * * \param [in] other is a reference to source of copy */ constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<T>::type>& other) noexcept : begin_{other.begin()}, end_{other.end()} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return const_iterator to first element in the range */ constexpr const_iterator cbegin() const noexcept { return begin(); } /** * \return const_iterator to "one past the last" element in the range */ constexpr const_iterator cend() const noexcept { return end(); } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } /** * \return reverse_iterator to "one past the last" element in the reversed range ("one before the first" element of * the non-reversed range) */ constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range iterator begin_; /// iterator to "one past the last" element in the range iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <|endoftext|>
<commit_before>#include "search_engine.hpp" #include "result.hpp" #include "search_query.hpp" #include "../storage/country_info.hpp" #include "../indexer/categories_holder.hpp" #include "../indexer/search_string_utils.hpp" #include "../indexer/mercator.hpp" #include "../indexer/scales.hpp" #include "../platform/platform.hpp" #include "../geometry/distance_on_sphere.hpp" #include "../base/logging.hpp" #include "../base/stl_add.hpp" #include "../std/map.hpp" #include "../std/vector.hpp" #include "../std/bind.hpp" namespace search { typedef vector<Query::SuggestT> SuggestsContainerT; class EngineData { public: EngineData(Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR) : m_categories(pCategoriesR), m_infoGetter(polyR, countryR) { } CategoriesHolder m_categories; SuggestsContainerT m_stringsToSuggest; storage::CountryInfoGetter m_infoGetter; }; namespace { class InitSuggestions { // Key - is a string with language. typedef map<pair<strings::UniString, int8_t>, uint8_t> SuggestMapT; SuggestMapT m_suggests; public: void operator() (CategoriesHolder::Category::Name const & name) { if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH) { strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name); uint8_t & score = m_suggests[make_pair(uniName, name.m_lang)]; if (score == 0 || score > name.m_prefixLengthToSuggest) score = name.m_prefixLengthToSuggest; } } void GetSuggests(SuggestsContainerT & cont) const { cont.reserve(m_suggests.size()); for (SuggestMapT::const_iterator i = m_suggests.begin(); i != m_suggests.end(); ++i) cont.push_back(Query::SuggestT(i->first.first, i->second, i->first.second)); } }; } Engine::Engine(IndexType const * pIndex, Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR, string const & lang) : m_readyThread(false), m_pIndex(pIndex), m_pData(new EngineData(pCategoriesR, polyR, countryR)) { InitSuggestions doInit; m_pData->m_categories.ForEachName(bind<void>(ref(doInit), _1)); doInit.GetSuggests(m_pData->m_stringsToSuggest); m_pQuery.reset(new Query(pIndex, &m_pData->m_categories, &m_pData->m_stringsToSuggest, &m_pData->m_infoGetter, RESULTS_COUNT)); m_pQuery->SetPreferredLanguage(lang); } Engine::~Engine() { } namespace { m2::PointD GetViewportXY(double lat, double lon) { return m2::PointD(MercatorBounds::LonToX(lon), MercatorBounds::LatToY(lat)); } m2::RectD GetViewportRect(double lat, double lon, double radius = 20000) { return MercatorBounds::MetresToXY(lon, lat, radius); } enum { VIEWPORT_RECT = 0, NEARME_RECT = 1 }; // X metres in mercator (lon, lat) units. double const epsEqualRects = 100.0 * MercatorBounds::degreeInMetres; double const epsEqualPoints = 500.0 * MercatorBounds::degreeInMetres; /// Check rects for optimal search (avoid duplicating). void AnalyzeRects(m2::RectD arrRects[2]) { if (arrRects[NEARME_RECT].IsRectInside(arrRects[VIEWPORT_RECT]) && arrRects[NEARME_RECT].Center().EqualDxDy(arrRects[VIEWPORT_RECT].Center(), epsEqualRects)) { arrRects[VIEWPORT_RECT].MakeEmpty(); } else { if (arrRects[VIEWPORT_RECT].IsRectInside(arrRects[NEARME_RECT]) && (scales::GetScaleLevel(arrRects[VIEWPORT_RECT]) + Query::SCALE_SEARCH_DEPTH >= scales::GetUpperScale())) { arrRects[NEARME_RECT].MakeEmpty(); } } } } void Engine::PrepareSearch(m2::RectD const & viewport, bool hasPt, double lat, double lon) { m2::RectD const nearby = (hasPt ? GetViewportRect(lat, lon) : m2::RectD()); // bind does copy of all rects GetPlatform().RunAsync(bind(&Engine::SetViewportAsync, this, viewport, nearby)); } bool Engine::Search(SearchParams const & params, m2::RectD const & viewport) { // Check for equal query. // There is no need to put synch here for reading m_params, // because this function is always called from main thread (one-by-one for queries). if (!params.IsForceSearch() && m_params.IsEqualCommon(params) && m2::IsEqual(m_viewport, viewport, epsEqualRects, epsEqualRects)) { if (!m_params.IsValidPosition()) return false; m2::PointD const p1 = GetViewportXY(m_params.m_lat, m_params.m_lon); m2::PointD const p2 = GetViewportXY(params.m_lat, params.m_lon); if (p1.EqualDxDy(p2, epsEqualPoints)) return false; } { // Assign new search params. // Put the synch here, because this params are reading in search threads. threads::MutexGuard guard(m_updateMutex); m_params = params; m_viewport = viewport; } // Run task. GetPlatform().RunAsync(bind(&Engine::SearchAsync, this)); return true; } void Engine::SetViewportAsync(m2::RectD const & viewport, m2::RectD const & nearby) { // First of all - cancel previous query. m_pQuery->DoCancel(); // Enter to run new search. threads::MutexGuard searchGuard(m_searchMutex); m2::RectD arrRects[] = { viewport, nearby }; AnalyzeRects(arrRects); m_pQuery->SetViewport(arrRects, ARRAY_SIZE(arrRects)); } void Engine::SearchAsync() { { // Avoid many threads waiting in search mutex. One is enough. threads::MutexGuard readyGuard(m_readyMutex); if (m_readyThread) return; m_readyThread = true; } // First of all - cancel previous query. m_pQuery->DoCancel(); // Enter to run new search. threads::MutexGuard searchGuard(m_searchMutex); { threads::MutexGuard readyGuard(m_readyMutex); m_readyThread = false; } // Get current search params. SearchParams params; m2::RectD arrRects[2]; { threads::MutexGuard updateGuard(m_updateMutex); params = m_params; arrRects[VIEWPORT_RECT] = m_viewport; } // Initialize query. m_pQuery->Init(); // Set search viewports according to search params. if (params.IsValidPosition()) { if (params.NeedSearch(SearchParams::AROUND_POSITION)) { m_pQuery->SetPosition(GetViewportXY(params.m_lat, params.m_lon)); arrRects[NEARME_RECT] = GetViewportRect(params.m_lat, params.m_lon); } } else m_pQuery->NullPosition(); if (!params.NeedSearch(SearchParams::IN_VIEWPORT)) arrRects[VIEWPORT_RECT].MakeEmpty(); if (arrRects[NEARME_RECT].IsValid() && arrRects[VIEWPORT_RECT].IsValid()) AnalyzeRects(arrRects); m_pQuery->SetViewport(arrRects, 2); m_pQuery->SetSearchInWorld(params.NeedSearch(SearchParams::SEARCH_WORLD)); if (params.IsLanguageValid()) m_pQuery->SetInputLanguage(params.m_inputLanguageCode); m_pQuery->SetQuery(params.m_query); bool const emptyQuery = m_pQuery->IsEmptyQuery(); Results res; // Call m_pQuery->IsCanceled() everywhere it needed without storing return value. // This flag can be changed from another thread. m_pQuery->SearchCoordinates(params.m_query, res); try { if (emptyQuery) { // Search for empty query only around viewport. if (params.IsValidPosition()) { double arrR[] = { 500, 1000, 2000 }; for (size_t i = 0; i < ARRAY_SIZE(arrR); ++i) { res.Clear(); m_pQuery->SearchAllInViewport(GetViewportRect(params.m_lat, params.m_lon, arrR[i]), res, 3*RESULTS_COUNT); if (m_pQuery->IsCanceled() || res.GetCount() >= 2*RESULTS_COUNT) break; } } } else { // Do search for address in all modes. // params.NeedSearch(SearchParams::SEARCH_ADDRESS) m_pQuery->Search(res, true); } } catch (Query::CancelException const &) { } // Emit results even if search was canceled and we have something. size_t const count = res.GetCount(); if (!m_pQuery->IsCanceled() || count > 0) params.m_callback(res); // Make additional search in whole mwm when not enough results (only for non-empty query). if (!emptyQuery && !m_pQuery->IsCanceled() && count < RESULTS_COUNT) { try { m_pQuery->SearchAdditional(res, params.NeedSearch(SearchParams::AROUND_POSITION), params.NeedSearch(SearchParams::IN_VIEWPORT)); } catch (Query::CancelException const &) { } // Emit if we have more results. if (res.GetCount() > count) params.m_callback(res); } // Emit finish marker to client. params.m_callback(Results::GetEndMarker(m_pQuery->IsCanceled())); } string Engine::GetCountryFile(m2::PointD const & pt) { threads::MutexGuard searchGuard(m_searchMutex); return m_pData->m_infoGetter.GetRegionFile(pt); } string Engine::GetCountryCode(m2::PointD const & pt) { threads::MutexGuard searchGuard(m_searchMutex); storage::CountryInfo info; m_pData->m_infoGetter.GetRegionInfo(pt, info); return info.m_flag; } template <class T> string Engine::GetCountryNameT(T const & t) { threads::MutexGuard searchGuard(m_searchMutex); storage::CountryInfo info; m_pData->m_infoGetter.GetRegionInfo(t, info); return info.m_name; } string Engine::GetCountryName(m2::PointD const & pt) { return GetCountryNameT(pt); } string Engine::GetCountryName(string const & id) { return GetCountryNameT(id); } bool Engine::GetNameByType(uint32_t type, int8_t lang, string & name) const { return m_pData->m_categories.GetNameByType(type, lang, name); } m2::RectD Engine::GetCountryBounds(string const & file) const { return m_pData->m_infoGetter.CalcLimitRect(file); } int8_t Engine::GetCurrentLanguage() const { return m_pQuery->GetPrefferedLanguage(); } void Engine::ClearViewportsCache() { threads::MutexGuard guard(m_searchMutex); m_pQuery->ClearCaches(); } void Engine::ClearAllCaches() { threads::MutexGuard guard(m_searchMutex); m_pQuery->ClearCaches(); m_pData->m_infoGetter.ClearCaches(); } } // namespace search <commit_msg>Do better check for distance on earth.<commit_after>#include "search_engine.hpp" #include "result.hpp" #include "search_query.hpp" #include "../storage/country_info.hpp" #include "../indexer/categories_holder.hpp" #include "../indexer/search_string_utils.hpp" #include "../indexer/mercator.hpp" #include "../indexer/scales.hpp" #include "../platform/platform.hpp" #include "../geometry/distance_on_sphere.hpp" #include "../base/logging.hpp" #include "../base/stl_add.hpp" #include "../std/map.hpp" #include "../std/vector.hpp" #include "../std/bind.hpp" namespace search { typedef vector<Query::SuggestT> SuggestsContainerT; class EngineData { public: EngineData(Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR) : m_categories(pCategoriesR), m_infoGetter(polyR, countryR) { } CategoriesHolder m_categories; SuggestsContainerT m_stringsToSuggest; storage::CountryInfoGetter m_infoGetter; }; namespace { class InitSuggestions { // Key - is a string with language. typedef map<pair<strings::UniString, int8_t>, uint8_t> SuggestMapT; SuggestMapT m_suggests; public: void operator() (CategoriesHolder::Category::Name const & name) { if (name.m_prefixLengthToSuggest != CategoriesHolder::Category::EMPTY_PREFIX_LENGTH) { strings::UniString const uniName = NormalizeAndSimplifyString(name.m_name); uint8_t & score = m_suggests[make_pair(uniName, name.m_lang)]; if (score == 0 || score > name.m_prefixLengthToSuggest) score = name.m_prefixLengthToSuggest; } } void GetSuggests(SuggestsContainerT & cont) const { cont.reserve(m_suggests.size()); for (SuggestMapT::const_iterator i = m_suggests.begin(); i != m_suggests.end(); ++i) cont.push_back(Query::SuggestT(i->first.first, i->second, i->first.second)); } }; } Engine::Engine(IndexType const * pIndex, Reader * pCategoriesR, ModelReaderPtr polyR, ModelReaderPtr countryR, string const & lang) : m_readyThread(false), m_pIndex(pIndex), m_pData(new EngineData(pCategoriesR, polyR, countryR)) { InitSuggestions doInit; m_pData->m_categories.ForEachName(bind<void>(ref(doInit), _1)); doInit.GetSuggests(m_pData->m_stringsToSuggest); m_pQuery.reset(new Query(pIndex, &m_pData->m_categories, &m_pData->m_stringsToSuggest, &m_pData->m_infoGetter, RESULTS_COUNT)); m_pQuery->SetPreferredLanguage(lang); } Engine::~Engine() { } namespace { m2::PointD GetViewportXY(double lat, double lon) { return m2::PointD(MercatorBounds::LonToX(lon), MercatorBounds::LatToY(lat)); } m2::RectD GetViewportRect(double lat, double lon, double radius = 20000) { return MercatorBounds::MetresToXY(lon, lat, radius); } enum { VIEWPORT_RECT = 0, NEARME_RECT = 1 }; // X metres in mercator (lon, lat) units. double const epsEqualRects = 100.0 * MercatorBounds::degreeInMetres; /// Check rects for optimal search (avoid duplicating). void AnalyzeRects(m2::RectD arrRects[2]) { if (arrRects[NEARME_RECT].IsRectInside(arrRects[VIEWPORT_RECT]) && arrRects[NEARME_RECT].Center().EqualDxDy(arrRects[VIEWPORT_RECT].Center(), epsEqualRects)) { arrRects[VIEWPORT_RECT].MakeEmpty(); } else { if (arrRects[VIEWPORT_RECT].IsRectInside(arrRects[NEARME_RECT]) && (scales::GetScaleLevel(arrRects[VIEWPORT_RECT]) + Query::SCALE_SEARCH_DEPTH >= scales::GetUpperScale())) { arrRects[NEARME_RECT].MakeEmpty(); } } } } void Engine::PrepareSearch(m2::RectD const & viewport, bool hasPt, double lat, double lon) { m2::RectD const nearby = (hasPt ? GetViewportRect(lat, lon) : m2::RectD()); // bind does copy of all rects GetPlatform().RunAsync(bind(&Engine::SetViewportAsync, this, viewport, nearby)); } bool Engine::Search(SearchParams const & params, m2::RectD const & viewport) { // Check for equal query. // There is no need to put synch here for reading m_params, // because this function is always called from main thread (one-by-one for queries). if (!params.IsForceSearch() && m_params.IsEqualCommon(params) && m2::IsEqual(m_viewport, viewport, epsEqualRects, epsEqualRects)) { if (!m_params.IsValidPosition()) return false; // Check distance between previous and current user's position. if (ms::DistanceOnEarth(m_params.m_lat, m_params.m_lon, params.m_lat, params.m_lon) < 500.0) return false; } { // Assign new search params. // Put the synch here, because this params are reading in search threads. threads::MutexGuard guard(m_updateMutex); m_params = params; m_viewport = viewport; } // Run task. GetPlatform().RunAsync(bind(&Engine::SearchAsync, this)); return true; } void Engine::SetViewportAsync(m2::RectD const & viewport, m2::RectD const & nearby) { // First of all - cancel previous query. m_pQuery->DoCancel(); // Enter to run new search. threads::MutexGuard searchGuard(m_searchMutex); m2::RectD arrRects[] = { viewport, nearby }; AnalyzeRects(arrRects); m_pQuery->SetViewport(arrRects, ARRAY_SIZE(arrRects)); } void Engine::SearchAsync() { { // Avoid many threads waiting in search mutex. One is enough. threads::MutexGuard readyGuard(m_readyMutex); if (m_readyThread) return; m_readyThread = true; } // First of all - cancel previous query. m_pQuery->DoCancel(); // Enter to run new search. threads::MutexGuard searchGuard(m_searchMutex); { threads::MutexGuard readyGuard(m_readyMutex); m_readyThread = false; } // Get current search params. SearchParams params; m2::RectD arrRects[2]; { threads::MutexGuard updateGuard(m_updateMutex); params = m_params; arrRects[VIEWPORT_RECT] = m_viewport; } // Initialize query. m_pQuery->Init(); // Set search viewports according to search params. if (params.IsValidPosition()) { if (params.NeedSearch(SearchParams::AROUND_POSITION)) { m_pQuery->SetPosition(GetViewportXY(params.m_lat, params.m_lon)); arrRects[NEARME_RECT] = GetViewportRect(params.m_lat, params.m_lon); } } else m_pQuery->NullPosition(); if (!params.NeedSearch(SearchParams::IN_VIEWPORT)) arrRects[VIEWPORT_RECT].MakeEmpty(); if (arrRects[NEARME_RECT].IsValid() && arrRects[VIEWPORT_RECT].IsValid()) AnalyzeRects(arrRects); m_pQuery->SetViewport(arrRects, 2); m_pQuery->SetSearchInWorld(params.NeedSearch(SearchParams::SEARCH_WORLD)); if (params.IsLanguageValid()) m_pQuery->SetInputLanguage(params.m_inputLanguageCode); m_pQuery->SetQuery(params.m_query); bool const emptyQuery = m_pQuery->IsEmptyQuery(); Results res; // Call m_pQuery->IsCanceled() everywhere it needed without storing return value. // This flag can be changed from another thread. m_pQuery->SearchCoordinates(params.m_query, res); try { if (emptyQuery) { // Search for empty query only around viewport. if (params.IsValidPosition()) { double arrR[] = { 500, 1000, 2000 }; for (size_t i = 0; i < ARRAY_SIZE(arrR); ++i) { res.Clear(); m_pQuery->SearchAllInViewport(GetViewportRect(params.m_lat, params.m_lon, arrR[i]), res, 3*RESULTS_COUNT); if (m_pQuery->IsCanceled() || res.GetCount() >= 2*RESULTS_COUNT) break; } } } else { // Do search for address in all modes. // params.NeedSearch(SearchParams::SEARCH_ADDRESS) m_pQuery->Search(res, true); } } catch (Query::CancelException const &) { } // Emit results even if search was canceled and we have something. size_t const count = res.GetCount(); if (!m_pQuery->IsCanceled() || count > 0) params.m_callback(res); // Make additional search in whole mwm when not enough results (only for non-empty query). if (!emptyQuery && !m_pQuery->IsCanceled() && count < RESULTS_COUNT) { try { m_pQuery->SearchAdditional(res, params.NeedSearch(SearchParams::AROUND_POSITION), params.NeedSearch(SearchParams::IN_VIEWPORT)); } catch (Query::CancelException const &) { } // Emit if we have more results. if (res.GetCount() > count) params.m_callback(res); } // Emit finish marker to client. params.m_callback(Results::GetEndMarker(m_pQuery->IsCanceled())); } string Engine::GetCountryFile(m2::PointD const & pt) { threads::MutexGuard searchGuard(m_searchMutex); return m_pData->m_infoGetter.GetRegionFile(pt); } string Engine::GetCountryCode(m2::PointD const & pt) { threads::MutexGuard searchGuard(m_searchMutex); storage::CountryInfo info; m_pData->m_infoGetter.GetRegionInfo(pt, info); return info.m_flag; } template <class T> string Engine::GetCountryNameT(T const & t) { threads::MutexGuard searchGuard(m_searchMutex); storage::CountryInfo info; m_pData->m_infoGetter.GetRegionInfo(t, info); return info.m_name; } string Engine::GetCountryName(m2::PointD const & pt) { return GetCountryNameT(pt); } string Engine::GetCountryName(string const & id) { return GetCountryNameT(id); } bool Engine::GetNameByType(uint32_t type, int8_t lang, string & name) const { return m_pData->m_categories.GetNameByType(type, lang, name); } m2::RectD Engine::GetCountryBounds(string const & file) const { return m_pData->m_infoGetter.CalcLimitRect(file); } int8_t Engine::GetCurrentLanguage() const { return m_pQuery->GetPrefferedLanguage(); } void Engine::ClearViewportsCache() { threads::MutexGuard guard(m_searchMutex); m_pQuery->ClearCaches(); } void Engine::ClearAllCaches() { threads::MutexGuard guard(m_searchMutex); m_pQuery->ClearCaches(); m_pData->m_infoGetter.ClearCaches(); } } // namespace search <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifdef ETL_CUDA #include "cuda_runtime.h" #endif namespace etl { namespace impl { namespace cuda { #ifdef ETL_CUDA /*! * \brief Wrapper for CUDA memory */ template <typename T> struct cuda_memory { T* memory; cuda_memory() noexcept : memory(nullptr) {} cuda_memory(T* memory) noexcept : memory(memory) {} //Delete copy operations cuda_memory(const cuda_memory& rhs) noexcept : memory(nullptr) { cpp_unused(rhs); cpp_assert(!rhs.is_set(), "copy of cuda_memory is only possible when not allocated"); } cuda_memory& operator=(const cuda_memory& rhs) noexcept { if (this != &rhs) { cpp_assert(!is_set(), "copy of cuda_memory is only possible when not allocated"); cpp_assert(!rhs.is_set(), "copy of cuda_memory is only possible when not allocated"); } return *this; } cuda_memory(cuda_memory&& rhs) noexcept : memory(rhs.memory) { rhs.memory = nullptr; } cuda_memory& operator=(cuda_memory&& rhs) noexcept { if (this != &rhs) { free_memory(); memory = rhs.memory; rhs.memory = nullptr; } return *this; } cuda_memory& operator=(T* new_memory) { free_memory(); memory = new_memory; return *this; } T* get() const { return memory; } bool is_set() const { return memory; } void reset() { free_memory(); memory = nullptr; } ~cuda_memory() { free_memory(); } private: void free_memory() { if (memory) { //Note: the const_cast is only here to allow compilation cudaFree((reinterpret_cast<void*>(const_cast<std::remove_const_t<T>*>(memory)))); } } }; template <typename E> auto cuda_allocate(const E& expr, bool copy = false) -> cuda_memory<value_t<E>> { value_t<E>* memory; auto cuda_status = cudaMalloc(&memory, etl::size(expr) * sizeof(value_t<E>)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << etl::size(expr) * sizeof(value_t<E>) << "B" << std::endl; exit(EXIT_FAILURE); } if (copy) { cudaMemcpy(memory, expr.memory_start(), etl::size(expr) * sizeof(value_t<E>), cudaMemcpyHostToDevice); } return {memory}; } template <typename E> auto cuda_allocate_copy(const E& expr) -> cuda_memory<value_t<E>> { return cuda_allocate(expr, true); } template <typename E> auto cuda_allocate(E* ptr, std::size_t n, bool copy = false) -> cuda_memory<E> { E* memory; auto cuda_status = cudaMalloc(&memory, n * sizeof(E)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << n * sizeof(E) << "B" << std::endl; exit(EXIT_FAILURE); } if (copy) { cudaMemcpy(memory, ptr, n * sizeof(E), cudaMemcpyHostToDevice); } return {memory}; } template <typename E> auto cuda_allocate_copy(E* ptr, std::size_t n) -> cuda_memory<E> { return cuda_allocate(ptr, n, true); } #else /*! * \brief Wrapper for CUDA memory (when disabled CUDA support) */ template <typename T> struct cuda_memory { //Nothing is enought }; #endif } //end of namespace cuda } //end of namespace impl } //end of namespace etl <commit_msg>New allocation features<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifdef ETL_CUDA #include "cuda_runtime.h" #endif namespace etl { namespace impl { namespace cuda { #ifdef ETL_CUDA /*! * \brief Wrapper for CUDA memory */ template <typename T> struct cuda_memory { T* memory; cuda_memory() noexcept : memory(nullptr) {} cuda_memory(T* memory) noexcept : memory(memory) {} //Delete copy operations cuda_memory(const cuda_memory& rhs) noexcept : memory(nullptr) { cpp_unused(rhs); cpp_assert(!rhs.is_set(), "copy of cuda_memory is only possible when not allocated"); } cuda_memory& operator=(const cuda_memory& rhs) noexcept { if (this != &rhs) { cpp_assert(!is_set(), "copy of cuda_memory is only possible when not allocated"); cpp_assert(!rhs.is_set(), "copy of cuda_memory is only possible when not allocated"); } return *this; } cuda_memory(cuda_memory&& rhs) noexcept : memory(rhs.memory) { rhs.memory = nullptr; } cuda_memory& operator=(cuda_memory&& rhs) noexcept { if (this != &rhs) { free_memory(); memory = rhs.memory; rhs.memory = nullptr; } return *this; } cuda_memory& operator=(T* new_memory) { free_memory(); memory = new_memory; return *this; } T* get() const { return memory; } bool is_set() const { return memory; } void reset() { free_memory(); memory = nullptr; } ~cuda_memory() { free_memory(); } private: void free_memory() { if (memory) { //Note: the const_cast is only here to allow compilation cudaFree((reinterpret_cast<void*>(const_cast<std::remove_const_t<T>*>(memory)))); } } }; template <typename E> auto cuda_allocate_only(std::size_t size) -> cuda_memory<E> { E* memory; auto cuda_status = cudaMalloc(&memory, size * sizeof(E)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << size * sizeof(E) << "B" << std::endl; exit(EXIT_FAILURE); } return {memory}; } template <typename E> auto cuda_allocate(const E& expr, bool copy = false) -> cuda_memory<value_t<E>> { value_t<E>* memory; auto cuda_status = cudaMalloc(&memory, etl::size(expr) * sizeof(value_t<E>)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << etl::size(expr) * sizeof(value_t<E>) << "B" << std::endl; exit(EXIT_FAILURE); } if (copy) { cudaMemcpy(memory, expr.memory_start(), etl::size(expr) * sizeof(value_t<E>), cudaMemcpyHostToDevice); } return {memory}; } template <typename E> auto cuda_allocate_copy(const E& expr) -> cuda_memory<value_t<E>> { return cuda_allocate(expr, true); } template <typename E> auto cuda_allocate(E* ptr, std::size_t n, bool copy = false) -> cuda_memory<E> { E* memory; auto cuda_status = cudaMalloc(&memory, n * sizeof(E)); if (cuda_status != cudaSuccess) { std::cout << "cuda: Failed to allocate GPU memory: " << cudaGetErrorString(cuda_status) << std::endl; std::cout << " Tried to allocate " << n * sizeof(E) << "B" << std::endl; exit(EXIT_FAILURE); } if (copy) { cudaMemcpy(memory, ptr, n * sizeof(E), cudaMemcpyHostToDevice); } return {memory}; } template <typename E> auto cuda_allocate_copy(E* ptr, std::size_t n) -> cuda_memory<E> { return cuda_allocate(ptr, n, true); } #else /*! * \brief Wrapper for CUDA memory (when disabled CUDA support) */ template <typename T> struct cuda_memory { //Nothing is enought }; #endif } //end of namespace cuda } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "LoggerFeature.h" #include "Basics/StringUtils.h" #include "Logger/LogAppender.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" using namespace arangodb; using namespace arangodb::basics; using namespace arangodb::options; LoggerFeature::LoggerFeature(application_features::ApplicationServer* server, bool threaded) : ApplicationFeature(server, "Logger"), _threaded(threaded) { setOptional(false); requiresElevatedPrivileges(false); startsAfter("Version"); if (threaded) { startsAfter("WorkMonitor"); } _levels.push_back("info"); // if stdout is not a tty, then the default for _foregroundTty becomes false _foregroundTty = (isatty(STDOUT_FILENO) != 0); } LoggerFeature::~LoggerFeature() { Logger::shutdown(); } void LoggerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addOldOption("log.tty", "log.foreground-tty"); options->addOldOption("log.content-filter", ""); options->addOldOption("log.source-filter", ""); options->addOldOption("log.application", ""); options->addOldOption("log.facility", ""); options->addHiddenOption("--log", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addSection("log", "Configure the logging"); options->addOption("--log.output,-o", "log destination(s)", new VectorParameter<StringParameter>(&_output)); options->addOption("--log.level,-l", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addOption("--log.use-local-time", "use local timezone instead of UTC", new BooleanParameter(&_useLocalTime)); options->addOption("--log.use-microtime", "use microtime instead", new BooleanParameter(&_useMicrotime)); options->addHiddenOption("--log.prefix", "prefix log message with this string", new StringParameter(&_prefix)); options->addHiddenOption("--log.file", "shortcut for '--log.output file://<filename>'", new StringParameter(&_file)); options->addHiddenOption("--log.line-number", "append line number and file name", new BooleanParameter(&_lineNumber)); options->addHiddenOption("--log.shorten-filenames", "shorten filenames in log output (use with --log.line-number)", new BooleanParameter(&_shortenFilenames)); options->addHiddenOption("--log.thread", "show thread identifier in log message", new BooleanParameter(&_thread)); options->addHiddenOption("--log.performance", "shortcut for '--log.level performance=trace'", new BooleanParameter(&_performance)); options->addHiddenOption("--log.keep-logrotate", "keep the old log file after receiving a sighup", new BooleanParameter(&_keepLogRotate)); options->addHiddenOption("--log.foreground-tty", "also log to tty if not backgrounded", new BooleanParameter(&_foregroundTty)); options->addHiddenOption("--log.force-direct", "do not start a seperate thread for logging", new BooleanParameter(&_forceDirect)); } void LoggerFeature::loadOptions( std::shared_ptr<options::ProgramOptions> options, const char *binaryPath) { // for debugging purpose, we set the log levels NOW // this might be overwritten latter Logger::setLogLevel(_levels); } void LoggerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { if (options->processingResult().touched("log.file")) { std::string definition; if (_file == "+" || _file == "-") { definition = _file; } else { definition = "file://" + _file; } _output.push_back(definition); } if (_performance) { _levels.push_back("performance=trace"); } } void LoggerFeature::prepare() { #if _WIN32 if (!TRI_InitWindowsEventLog()) { std::cerr << "failed to init event log" << std::endl; FATAL_ERROR_EXIT(); } #endif Logger::setLogLevel(_levels); Logger::setUseLocalTime(_useLocalTime); Logger::setUseMicrotime(_useMicrotime); Logger::setShowLineNumber(_lineNumber); Logger::setShortenFilenames(_shortenFilenames); Logger::setShowThreadIdentifier(_thread); Logger::setOutputPrefix(_prefix); Logger::setKeepLogrotate(_keepLogRotate); for (auto definition : _output) { if (_supervisor && StringUtils::isPrefix(definition, "file://")) { definition += ".supervisor"; } LogAppender::addAppender(definition); } if (!_backgrounded && _foregroundTty) { LogAppender::addTtyAppender(); } if (_forceDirect || _supervisor) { Logger::initialize(false); } else { Logger::initialize(_threaded); } } void LoggerFeature::unprepare() { Logger::flush(); } <commit_msg>fix for win32<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "LoggerFeature.h" #include "Basics/StringUtils.h" #include "Logger/LogAppender.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #if _WIN32 #include <iostream> #endif using namespace arangodb; using namespace arangodb::basics; using namespace arangodb::options; LoggerFeature::LoggerFeature(application_features::ApplicationServer* server, bool threaded) : ApplicationFeature(server, "Logger"), _threaded(threaded) { setOptional(false); requiresElevatedPrivileges(false); startsAfter("Version"); if (threaded) { startsAfter("WorkMonitor"); } _levels.push_back("info"); // if stdout is not a tty, then the default for _foregroundTty becomes false _foregroundTty = (isatty(STDOUT_FILENO) != 0); } LoggerFeature::~LoggerFeature() { Logger::shutdown(); } void LoggerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addOldOption("log.tty", "log.foreground-tty"); options->addOldOption("log.content-filter", ""); options->addOldOption("log.source-filter", ""); options->addOldOption("log.application", ""); options->addOldOption("log.facility", ""); options->addHiddenOption("--log", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addSection("log", "Configure the logging"); options->addOption("--log.output,-o", "log destination(s)", new VectorParameter<StringParameter>(&_output)); options->addOption("--log.level,-l", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addOption("--log.use-local-time", "use local timezone instead of UTC", new BooleanParameter(&_useLocalTime)); options->addOption("--log.use-microtime", "use microtime instead", new BooleanParameter(&_useMicrotime)); options->addHiddenOption("--log.prefix", "prefix log message with this string", new StringParameter(&_prefix)); options->addHiddenOption("--log.file", "shortcut for '--log.output file://<filename>'", new StringParameter(&_file)); options->addHiddenOption("--log.line-number", "append line number and file name", new BooleanParameter(&_lineNumber)); options->addHiddenOption("--log.shorten-filenames", "shorten filenames in log output (use with --log.line-number)", new BooleanParameter(&_shortenFilenames)); options->addHiddenOption("--log.thread", "show thread identifier in log message", new BooleanParameter(&_thread)); options->addHiddenOption("--log.performance", "shortcut for '--log.level performance=trace'", new BooleanParameter(&_performance)); options->addHiddenOption("--log.keep-logrotate", "keep the old log file after receiving a sighup", new BooleanParameter(&_keepLogRotate)); options->addHiddenOption("--log.foreground-tty", "also log to tty if not backgrounded", new BooleanParameter(&_foregroundTty)); options->addHiddenOption("--log.force-direct", "do not start a seperate thread for logging", new BooleanParameter(&_forceDirect)); } void LoggerFeature::loadOptions( std::shared_ptr<options::ProgramOptions> options, const char *binaryPath) { // for debugging purpose, we set the log levels NOW // this might be overwritten latter Logger::setLogLevel(_levels); } void LoggerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { if (options->processingResult().touched("log.file")) { std::string definition; if (_file == "+" || _file == "-") { definition = _file; } else { definition = "file://" + _file; } _output.push_back(definition); } if (_performance) { _levels.push_back("performance=trace"); } } void LoggerFeature::prepare() { #if _WIN32 if (!TRI_InitWindowsEventLog()) { std::cerr << "failed to init event log" << std::endl; FATAL_ERROR_EXIT(); } #endif Logger::setLogLevel(_levels); Logger::setUseLocalTime(_useLocalTime); Logger::setUseMicrotime(_useMicrotime); Logger::setShowLineNumber(_lineNumber); Logger::setShortenFilenames(_shortenFilenames); Logger::setShowThreadIdentifier(_thread); Logger::setOutputPrefix(_prefix); Logger::setKeepLogrotate(_keepLogRotate); for (auto definition : _output) { if (_supervisor && StringUtils::isPrefix(definition, "file://")) { definition += ".supervisor"; } LogAppender::addAppender(definition); } if (!_backgrounded && _foregroundTty) { LogAppender::addTtyAppender(); } if (_forceDirect || _supervisor) { Logger::initialize(false); } else { Logger::initialize(_threaded); } } void LoggerFeature::unprepare() { Logger::flush(); } <|endoftext|>
<commit_before>// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "MexStream.h" #include "mex.h" inline std::streamsize igl::MexStream::xsputn( const char *s, std::streamsize n) { mexPrintf("%.*s",n,s); mexEvalString("drawnow;"); // to dump string. return n; } inline int igl::MexStream::overflow(int c) { if (c != EOF) { mexPrintf("%.1s",&c); mexEvalString("drawnow;"); // to dump string. } return 1; } <commit_msg>rm cpp class impl<commit_after><|endoftext|>
<commit_before> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkColorPriv.h" #include "SkShader.h" namespace skiagm { class BigMatrixGM : public GM { public: BigMatrixGM() { this->setBGColor(0xFF66AA99); } protected: virtual SkString onShortName() { return SkString("bigmatrix"); } virtual SkISize onISize() { return make_isize(50, 50); } virtual void onDraw(SkCanvas* canvas) { SkMatrix m; m.reset(); m.setRotate(33 * SK_Scalar1); m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1); m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1); canvas->concat(m); SkPaint paint; paint.setColor(SK_ColorRED); paint.setAntiAlias(true); m.invert(&m); SkPath path; SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1}; SkScalar small = 1 / (500 * SK_Scalar1); m.mapPoints(&pt, 1); path.addCircle(pt.fX, pt.fY, small); canvas->drawPath(path, paint); pt.set(30 * SK_Scalar1, 10 * SK_Scalar1); m.mapPoints(&pt, 1); SkRect rect = {pt.fX - small, pt.fY - small, pt.fX + small, pt.fY + small}; canvas->drawRect(rect, paint); SkBitmap bmp; bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); bmp.allocPixels(); bmp.lockPixels(); uint32_t* pixels = reinterpret_cast<uint32_t*>(bmp.getPixels()); pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00); pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00); pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00); pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF); bmp.unlockPixels(); pt.set(30 * SK_Scalar1, 30 * SK_Scalar1); m.mapPoints(&pt, 1); SkShader* shader = SkShader::CreateBitmapShader( bmp, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix s; s.reset(); s.setScale(SK_Scalar1 / 1000, SK_Scalar1 / 1000); shader->setLocalMatrix(s); paint.setShader(shader)->unref(); paint.setAntiAlias(false); paint.setFilterBitmap(true); rect.setLTRB(pt.fX - small, pt.fY - small, pt.fX + small, pt.fY + small); canvas->drawRect(rect, paint); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BigMatrixGM; } static GMRegistry reg(MyFactory); } <commit_msg>silence warning<commit_after> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkColorPriv.h" #include "SkShader.h" namespace skiagm { class BigMatrixGM : public GM { public: BigMatrixGM() { this->setBGColor(0xFF66AA99); } protected: virtual SkString onShortName() { return SkString("bigmatrix"); } virtual SkISize onISize() { return make_isize(50, 50); } virtual void onDraw(SkCanvas* canvas) { SkMatrix m; m.reset(); m.setRotate(33 * SK_Scalar1); m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1); m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1); canvas->concat(m); SkPaint paint; paint.setColor(SK_ColorRED); paint.setAntiAlias(true); bool success = m.invert(&m); SkPath path; SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1}; SkScalar small = 1 / (500 * SK_Scalar1); m.mapPoints(&pt, 1); path.addCircle(pt.fX, pt.fY, small); canvas->drawPath(path, paint); pt.set(30 * SK_Scalar1, 10 * SK_Scalar1); m.mapPoints(&pt, 1); SkRect rect = {pt.fX - small, pt.fY - small, pt.fX + small, pt.fY + small}; canvas->drawRect(rect, paint); SkBitmap bmp; bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); bmp.allocPixels(); bmp.lockPixels(); uint32_t* pixels = reinterpret_cast<uint32_t*>(bmp.getPixels()); pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00); pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00); pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00); pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF); bmp.unlockPixels(); pt.set(30 * SK_Scalar1, 30 * SK_Scalar1); m.mapPoints(&pt, 1); SkShader* shader = SkShader::CreateBitmapShader( bmp, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix s; s.reset(); s.setScale(SK_Scalar1 / 1000, SK_Scalar1 / 1000); shader->setLocalMatrix(s); paint.setShader(shader)->unref(); paint.setAntiAlias(false); paint.setFilterBitmap(true); rect.setLTRB(pt.fX - small, pt.fY - small, pt.fX + small, pt.fY + small); canvas->drawRect(rect, paint); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BigMatrixGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to 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) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/disk_buffer_holder.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; namespace { struct peer_plugin_wrap : peer_plugin, wrapper<peer_plugin> { void add_handshake(entry& e) { if (override f = this->get_override("add_handshake")) e = call<entry>(f.ptr(), e); else peer_plugin::add_handshake(e); } void default_add_handshake(entry& e) { this->peer_plugin::add_handshake(e); } bool on_handshake() { if (override f = this->get_override("on_handshake")) return f(); else return peer_plugin::on_handshake(); } bool default_on_handshake() { return this->peer_plugin::on_handshake(); } bool on_extension_handshake(entry const& e) { if (override f = this->get_override("on_extension_handshake")) return f(e); else return peer_plugin::on_extension_handshake(e); } bool default_on_extension_handshake(entry const& e) { return this->peer_plugin::on_extension_handshake(e); } bool on_choke() { if (override f = this->get_override("on_choke")) return f(); else return peer_plugin::on_choke(); } bool default_on_choke() { return this->peer_plugin::on_choke(); } bool on_unchoke() { if (override f = this->get_override("on_unchoke")) return f(); else return peer_plugin::on_unchoke(); } bool default_on_unchoke() { return this->peer_plugin::on_unchoke(); } bool on_interested() { if (override f = this->get_override("on_interested")) return f(); else return peer_plugin::on_interested(); } bool default_on_interested() { return this->peer_plugin::on_interested(); } bool on_not_interested() { if (override f = this->get_override("on_not_interested")) return f(); else return peer_plugin::on_not_interested(); } bool default_on_not_interested() { return this->peer_plugin::on_not_interested(); } bool on_have(int index) { if (override f = this->get_override("on_have")) return f(index); else return peer_plugin::on_have(index); } bool default_on_have(int index) { return this->peer_plugin::on_have(index); } bool on_bitfield(std::vector<bool> const& bitfield) { if (override f = this->get_override("on_bitfield")) return f(bitfield); else return peer_plugin::on_bitfield(bitfield); } bool default_on_bitfield(std::vector<bool> const& bitfield) { return this->peer_plugin::on_bitfield(bitfield); } bool on_request(peer_request const& req) { if (override f = this->get_override("on_request")) return f(req); else return peer_plugin::on_request(req); } bool default_on_request(peer_request const& req) { return this->peer_plugin::on_request(req); } bool on_piece(peer_request const& piece, disk_buffer_holder& data) { if (override f = this->get_override("on_piece")) return f(piece, data); else return peer_plugin::on_piece(piece, data); } bool default_on_piece(peer_request const& piece, disk_buffer_holder& data) { return this->peer_plugin::on_piece(piece, data); } bool on_cancel(peer_request const& req) { if (override f = this->get_override("on_cancel")) return f(req); else return peer_plugin::on_cancel(req); } bool default_on_cancel(peer_request const& req) { return this->peer_plugin::on_cancel(req); } bool on_extended(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_extended")) return f(length, msg, body); else return peer_plugin::on_extended(length, msg, body); } bool default_on_extended(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_extended(length, msg, body); } bool on_unknown_message(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_unknown_message")) return f(length, msg, body); else return peer_plugin::on_unknown_message(length, msg, body); } bool default_on_unknown_message(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_unknown_message(length, msg, body); } void on_piece_pass(int index) { if (override f = this->get_override("on_piece_pass")) f(index); else peer_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->peer_plugin::on_piece_pass(index); } void on_piece_failed(int index) { if (override f = this->get_override("on_piece_failed")) f(index); else peer_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { this->peer_plugin::on_piece_failed(index); } void tick() { if (override f = this->get_override("tick")) f(); else peer_plugin::tick(); } void default_tick() { this->peer_plugin::tick(); } bool write_request(peer_request const& req) { if (override f = this->get_override("write_request")) return f(req); else return peer_plugin::write_request(req); } bool default_write_request(peer_request const& req) { return this->peer_plugin::write_request(req); } }; object get_buffer() { static char const data[] = "foobar"; return object(handle<>(PyBuffer_FromMemory((void*)data, 6))); } } // namespace unnamed void bind_peer_plugin() { class_< peer_plugin_wrap, boost::shared_ptr<peer_plugin_wrap>, boost::noncopyable >("peer_plugin") .def( "add_handshake" , &peer_plugin::add_handshake, &peer_plugin_wrap::default_add_handshake ) .def( "on_handshake" , &peer_plugin::on_handshake, &peer_plugin_wrap::default_on_handshake ) .def( "on_extension_handshake" , &peer_plugin::on_extension_handshake , &peer_plugin_wrap::default_on_extension_handshake ) .def( "on_choke" , &peer_plugin::on_choke, &peer_plugin_wrap::default_on_choke ) .def( "on_unchoke" , &peer_plugin::on_unchoke, &peer_plugin_wrap::default_on_unchoke ) .def( "on_interested" , &peer_plugin::on_interested, &peer_plugin_wrap::default_on_interested ) .def( "on_not_interested" , &peer_plugin::on_not_interested, &peer_plugin_wrap::default_on_not_interested ) .def( "on_have" , &peer_plugin::on_have, &peer_plugin_wrap::default_on_have ) .def( "on_bitfield" , &peer_plugin::on_bitfield, &peer_plugin_wrap::default_on_bitfield ) .def( "on_request" , &peer_plugin::on_request, &peer_plugin_wrap::default_on_request ) .def( "on_piece" , &peer_plugin::on_piece, &peer_plugin_wrap::default_on_piece ) .def( "on_cancel" , &peer_plugin::on_cancel, &peer_plugin_wrap::default_on_cancel ) .def( "on_piece_pass" , &peer_plugin::on_piece_pass, &peer_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &peer_plugin::on_piece_failed, &peer_plugin_wrap::default_on_piece_failed ) .def( "tick" , &peer_plugin::tick, &peer_plugin_wrap::default_tick ) .def( "write_request" , &peer_plugin::write_request, &peer_plugin_wrap::default_write_request ) // These seem to make VC7.1 freeze. Needs special handling. /*.def( "on_extended" , &peer_plugin::on_extended, &peer_plugin_wrap::default_on_extended ) .def( "on_unknown_message" , &peer_plugin::on_unknown_message, &peer_plugin_wrap::default_on_unknown_message )*/ ; def("get_buffer", &get_buffer); } <commit_msg>python binding fixes<commit_after>// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to 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) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/disk_buffer_holder.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; namespace { struct peer_plugin_wrap : peer_plugin, wrapper<peer_plugin> { void add_handshake(entry& e) { if (override f = this->get_override("add_handshake")) e = call<entry>(f.ptr(), e); else peer_plugin::add_handshake(e); } void default_add_handshake(entry& e) { this->peer_plugin::add_handshake(e); } bool on_handshake(char const* reserved_bits) { if (override f = this->get_override("on_handshake")) return f(); else return peer_plugin::on_handshake(reserved_bits); } bool default_on_handshake(char const* reserved_bits) { return this->peer_plugin::on_handshake(reserved_bits); } bool on_extension_handshake(entry const& e) { if (override f = this->get_override("on_extension_handshake")) return f(e); else return peer_plugin::on_extension_handshake(e); } bool default_on_extension_handshake(entry const& e) { return this->peer_plugin::on_extension_handshake(e); } bool on_choke() { if (override f = this->get_override("on_choke")) return f(); else return peer_plugin::on_choke(); } bool default_on_choke() { return this->peer_plugin::on_choke(); } bool on_unchoke() { if (override f = this->get_override("on_unchoke")) return f(); else return peer_plugin::on_unchoke(); } bool default_on_unchoke() { return this->peer_plugin::on_unchoke(); } bool on_interested() { if (override f = this->get_override("on_interested")) return f(); else return peer_plugin::on_interested(); } bool default_on_interested() { return this->peer_plugin::on_interested(); } bool on_not_interested() { if (override f = this->get_override("on_not_interested")) return f(); else return peer_plugin::on_not_interested(); } bool default_on_not_interested() { return this->peer_plugin::on_not_interested(); } bool on_have(int index) { if (override f = this->get_override("on_have")) return f(index); else return peer_plugin::on_have(index); } bool default_on_have(int index) { return this->peer_plugin::on_have(index); } bool on_bitfield(std::vector<bool> const& bitfield) { if (override f = this->get_override("on_bitfield")) return f(bitfield); else return peer_plugin::on_bitfield(bitfield); } bool default_on_bitfield(std::vector<bool> const& bitfield) { return this->peer_plugin::on_bitfield(bitfield); } bool on_request(peer_request const& req) { if (override f = this->get_override("on_request")) return f(req); else return peer_plugin::on_request(req); } bool default_on_request(peer_request const& req) { return this->peer_plugin::on_request(req); } bool on_piece(peer_request const& piece, disk_buffer_holder& data) { if (override f = this->get_override("on_piece")) return f(piece, data); else return peer_plugin::on_piece(piece, data); } bool default_on_piece(peer_request const& piece, disk_buffer_holder& data) { return this->peer_plugin::on_piece(piece, data); } bool on_cancel(peer_request const& req) { if (override f = this->get_override("on_cancel")) return f(req); else return peer_plugin::on_cancel(req); } bool default_on_cancel(peer_request const& req) { return this->peer_plugin::on_cancel(req); } bool on_extended(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_extended")) return f(length, msg, body); else return peer_plugin::on_extended(length, msg, body); } bool default_on_extended(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_extended(length, msg, body); } bool on_unknown_message(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_unknown_message")) return f(length, msg, body); else return peer_plugin::on_unknown_message(length, msg, body); } bool default_on_unknown_message(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_unknown_message(length, msg, body); } void on_piece_pass(int index) { if (override f = this->get_override("on_piece_pass")) f(index); else peer_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->peer_plugin::on_piece_pass(index); } void on_piece_failed(int index) { if (override f = this->get_override("on_piece_failed")) f(index); else peer_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { this->peer_plugin::on_piece_failed(index); } void tick() { if (override f = this->get_override("tick")) f(); else peer_plugin::tick(); } void default_tick() { this->peer_plugin::tick(); } bool write_request(peer_request const& req) { if (override f = this->get_override("write_request")) return f(req); else return peer_plugin::write_request(req); } bool default_write_request(peer_request const& req) { return this->peer_plugin::write_request(req); } }; object get_buffer() { static char const data[] = "foobar"; return object(handle<>(PyBuffer_FromMemory((void*)data, 6))); } } // namespace unnamed void bind_peer_plugin() { class_< peer_plugin_wrap, boost::shared_ptr<peer_plugin_wrap>, boost::noncopyable >("peer_plugin") .def( "add_handshake" , &peer_plugin::add_handshake, &peer_plugin_wrap::default_add_handshake ) .def( "on_handshake" , &peer_plugin::on_handshake, &peer_plugin_wrap::default_on_handshake ) .def( "on_extension_handshake" , &peer_plugin::on_extension_handshake , &peer_plugin_wrap::default_on_extension_handshake ) .def( "on_choke" , &peer_plugin::on_choke, &peer_plugin_wrap::default_on_choke ) .def( "on_unchoke" , &peer_plugin::on_unchoke, &peer_plugin_wrap::default_on_unchoke ) .def( "on_interested" , &peer_plugin::on_interested, &peer_plugin_wrap::default_on_interested ) .def( "on_not_interested" , &peer_plugin::on_not_interested, &peer_plugin_wrap::default_on_not_interested ) .def( "on_have" , &peer_plugin::on_have, &peer_plugin_wrap::default_on_have ) .def( "on_bitfield" , &peer_plugin::on_bitfield, &peer_plugin_wrap::default_on_bitfield ) .def( "on_request" , &peer_plugin::on_request, &peer_plugin_wrap::default_on_request ) .def( "on_piece" , &peer_plugin::on_piece, &peer_plugin_wrap::default_on_piece ) .def( "on_cancel" , &peer_plugin::on_cancel, &peer_plugin_wrap::default_on_cancel ) .def( "on_piece_pass" , &peer_plugin::on_piece_pass, &peer_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &peer_plugin::on_piece_failed, &peer_plugin_wrap::default_on_piece_failed ) .def( "tick" , &peer_plugin::tick, &peer_plugin_wrap::default_tick ) .def( "write_request" , &peer_plugin::write_request, &peer_plugin_wrap::default_write_request ) // These seem to make VC7.1 freeze. Needs special handling. /*.def( "on_extended" , &peer_plugin::on_extended, &peer_plugin_wrap::default_on_extended ) .def( "on_unknown_message" , &peer_plugin::on_unknown_message, &peer_plugin_wrap::default_on_unknown_message )*/ ; def("get_buffer", &get_buffer); } <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP #include <type_traits> namespace kgr { namespace detail { /* * Type trait that extract the return type of the forward function. */ template<typename, typename = void> struct ServiceTypeHelper {}; /* * Specialization of ServiceTypeHelper when T has a forward function callable without parameter. */ template<typename T> struct ServiceTypeHelper<T, typename std::enable_if<!std::is_same<decltype(std::declval<T>().forward()), void>::value>::type> { using type = decltype(std::declval<T>().forward()); }; /* * Variable sent as parameter for in_place_t. * * Used by the container to desambiguate between contructor that construct the service, and those that doesnt. * * We defined the variable before the type because the variable is private, but the type is public. */ struct {} constexpr in_place; } // namespace detail /** * This type is the return type of the forward function of the service T. */ template<typename T> using ServiceType = typename detail::ServiceTypeHelper<T>::type; /* * This is a tag type to mark a constructor as the one the container should use to construct a definition. */ using in_place_t = decltype(detail::in_place); } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP <commit_msg>Fixed build with clang constructing a constexpr unnamed struct<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP #include <type_traits> namespace kgr { namespace detail { /* * Type trait that extract the return type of the forward function. */ template<typename, typename = void> struct ServiceTypeHelper {}; /* * Specialization of ServiceTypeHelper when T has a forward function callable without parameter. */ template<typename T> struct ServiceTypeHelper<T, typename std::enable_if<!std::is_same<decltype(std::declval<T>().forward()), void>::value>::type> { using type = decltype(std::declval<T>().forward()); }; /* * Variable sent as parameter for in_place_t. * * Used by the container to desambiguate between contructor that construct the service, and those that doesnt. * * We defined the variable before the type because the variable is private, but the type is public. */ struct {} constexpr in_place{}; } // namespace detail /** * This type is the return type of the forward function of the service T. */ template<typename T> using ServiceType = typename detail::ServiceTypeHelper<T>::type; /* * This is a tag type to mark a constructor as the one the container should use to construct a definition. */ using in_place_t = decltype(detail::in_place); } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_UTILS_HPP <|endoftext|>
<commit_before>// utils/grm_tester.cc // Copyright 2016 Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // \file // Used to run thrax grammer tests. #include <fstream> #include <string> #include <fst/compat.h> #include <fst/string.h> #include <fst/vector-fst.h> #include <thrax/compat/utils.h> #include <thrax/grm-manager.h> DEFINE_string(far, "", "Path to the far file."); DEFINE_string(test_file, "", "Path to a tsv file which " " contains test entries. TSV format column 1 - thrax rule," " column 2 - thrax input and column 3 expected thrax rewrite. "); int main(int argc, char *argv[]) { using fst::StdArc; typedef fst::StringCompiler<StdArc> Compiler; typedef fst::VectorFst<StdArc> Transducer; SET_FLAGS(argv[0], &argc, &argv, true); thrax::GrmManagerSpec<StdArc> grm_manager; if (!grm_manager.LoadArchive(FLAGS_far)) { LOG(ERROR) << "Cannot load far file: " << FLAGS_far; return 2; } std::ifstream file(FLAGS_test_file); if (!file) { LOG(ERROR) << "Failed to open test file: " << FLAGS_test_file; return 2; } Compiler compiler_(fst::StringTokenType::BYTE); string output; Transducer input_fst; int error = 0; int line_no = 0; for (string line; std::getline(file, line); ) { line_no++; // Line is a comment. if (line.empty() || line[0] == '#') { continue; } const auto segments = thrax::Split(line, "\t"); if (segments.size() != 3) { continue; } if (!compiler_(segments[1], &input_fst)) { LOG(ERROR) << "Unable to parse input: " << segments[1]; error = 1; continue; } if (!grm_manager.RewriteBytes(segments[0], input_fst, &output, "", "")) { LOG(ERROR) << "REWRITE_FAILED in line - " << line_no << "\n line text: " + line << "\n segment 0: " + segments[0] << "\n segment 1: " + segments[1] << "\n segment 2: " + segments[2]; error = 1; continue; } if (output != segments[2]) { error = 1; LOG(WARNING) << "Error in line " << line_no << " expected - " << segments[2] << " but actually - " << output; } } return error; } <commit_msg>Log error when lines are malformed<commit_after>// utils/grm_tester.cc // Copyright 2016 Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // \file // Used to run thrax grammer tests. #include <fstream> #include <string> #include <fst/compat.h> #include <fst/string.h> #include <fst/vector-fst.h> #include <thrax/compat/utils.h> #include <thrax/grm-manager.h> DEFINE_string(far, "", "Path to the far file."); DEFINE_string(test_file, "", "Path to a tsv file which " " contains test entries. TSV format column 1 - thrax rule," " column 2 - thrax input and column 3 expected thrax rewrite. "); int main(int argc, char *argv[]) { using fst::StdArc; typedef fst::StringCompiler<StdArc> Compiler; typedef fst::VectorFst<StdArc> Transducer; SET_FLAGS(argv[0], &argc, &argv, true); thrax::GrmManagerSpec<StdArc> grm_manager; if (!grm_manager.LoadArchive(FLAGS_far)) { LOG(ERROR) << "Cannot load far file: " << FLAGS_far; return 2; } std::ifstream file(FLAGS_test_file); if (!file) { LOG(ERROR) << "Failed to open test file: " << FLAGS_test_file; return 2; } Compiler compiler_(fst::StringTokenType::BYTE); string output; Transducer input_fst; int error = 0; int line_no = 0; for (string line; std::getline(file, line); ) { line_no++; // Line is a comment. if (line.empty() || line[0] == '#') { continue; } const auto segments = thrax::Split(line, "\t"); if (segments.size() != 3) { LOG(ERROR) << "Line no: " << line << " malformed"; error = 1; continue; } if (!compiler_(segments[1], &input_fst)) { LOG(ERROR) << "Unable to parse input: " << segments[1]; error = 1; continue; } if (!grm_manager.RewriteBytes(segments[0], input_fst, &output, "", "")) { LOG(ERROR) << "REWRITE_FAILED in line - " << line_no << "\n line text: " + line << "\n segment 0: " + segments[0] << "\n segment 1: " + segments[1] << "\n segment 2: " + segments[2]; error = 1; continue; } if (output != segments[2]) { error = 1; LOG(WARNING) << "Error in line " << line_no << " expected - " << segments[2] << " but actually - " << output; } } return error; } <|endoftext|>
<commit_before>/* Copyright (c) 2009, 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. */ #include <cstddef> #ifndef TORRENT_ALLOCATOR_HPP_INCLUDED #define TORRENT_ALLOCATOR_HPP_INCLUDED namespace libtorrent { struct page_aligned_allocator { typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static char* malloc(const size_type bytes); static void free(char* const block); }; } #endif <commit_msg>add dllexport interface to page_aligned_allocator<commit_after>/* Copyright (c) 2009, 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_ALLOCATOR_HPP_INCLUDED #define TORRENT_ALLOCATOR_HPP_INCLUDED #include <cstddef> #include "libtorrent/config.hpp" namespace libtorrent { struct TORRENT_EXPORT page_aligned_allocator { typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static char* malloc(const size_type bytes); static void free(char* const block); }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2016-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <fs.h> #include <util/system.h> #include <util/translation.h> #include <wallet/salvage.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> namespace WalletTool { // The standard wallet deleter function blocks on the validation interface // queue, which doesn't exist for the bitcoin-wallet. Define our own // deleter here. static void WalletToolReleaseWallet(CWallet* wallet) { wallet->WalletLogPrintf("Releasing wallet\n"); wallet->Close(); delete wallet; } static void WalletCreate(CWallet* wallet_instance) { LOCK(wallet_instance->cs_wallet); wallet_instance->SetMinVersion(FEATURE_HD_SPLIT); // generate a new HD seed auto spk_man = wallet_instance->GetOrCreateLegacyScriptPubKeyMan(); CPubKey seed = spk_man->GenerateNewSeed(); spk_man->SetHDSeed(seed); tfm::format(std::cout, "Topping up keypool...\n"); wallet_instance->TopUpKeyPool(); } static std::shared_ptr<CWallet> MakeWallet(const std::string& name, const fs::path& path, bool create) { DatabaseOptions options; DatabaseStatus status; if (create) { options.require_create = true; } else { options.require_existing = true; } bilingual_str error; std::unique_ptr<WalletDatabase> database = MakeDatabase(path, options, status, error); if (!database) { tfm::format(std::cerr, "%s\n", error.original); return nullptr; } // dummy chain interface std::shared_ptr<CWallet> wallet_instance{new CWallet(nullptr /* chain */, name, std::move(database)), WalletToolReleaseWallet}; DBErrors load_wallet_ret; try { bool first_run; load_wallet_ret = wallet_instance->LoadWallet(first_run); } catch (const std::runtime_error&) { tfm::format(std::cerr, "Error loading %s. Is wallet being used by another process?\n", name); return nullptr; } if (load_wallet_ret != DBErrors::LOAD_OK) { wallet_instance = nullptr; if (load_wallet_ret == DBErrors::CORRUPT) { tfm::format(std::cerr, "Error loading %s: Wallet corrupted", name); return nullptr; } else if (load_wallet_ret == DBErrors::NONCRITICAL_ERROR) { tfm::format(std::cerr, "Error reading %s! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.", name); } else if (load_wallet_ret == DBErrors::TOO_NEW) { tfm::format(std::cerr, "Error loading %s: Wallet requires newer version of %s", name, PACKAGE_NAME); return nullptr; } else if (load_wallet_ret == DBErrors::NEED_REWRITE) { tfm::format(std::cerr, "Wallet needed to be rewritten: restart %s to complete", PACKAGE_NAME); return nullptr; } else { tfm::format(std::cerr, "Error loading %s", name); return nullptr; } } if (create) WalletCreate(wallet_instance.get()); return wallet_instance; } static void WalletShowInfo(CWallet* wallet_instance) { LOCK(wallet_instance->cs_wallet); tfm::format(std::cout, "Wallet info\n===========\n"); tfm::format(std::cout, "Name: %s\n", wallet_instance->GetName()); tfm::format(std::cout, "Format: %s\n", wallet_instance->GetDatabase().Format()); tfm::format(std::cout, "Descriptors: %s\n", wallet_instance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) ? "yes" : "no"); tfm::format(std::cout, "Encrypted: %s\n", wallet_instance->IsCrypted() ? "yes" : "no"); tfm::format(std::cout, "HD (hd seed available): %s\n", wallet_instance->IsHDEnabled() ? "yes" : "no"); tfm::format(std::cout, "Keypool Size: %u\n", wallet_instance->GetKeyPoolSize()); tfm::format(std::cout, "Transactions: %zu\n", wallet_instance->mapWallet.size()); tfm::format(std::cout, "Address Book: %zu\n", wallet_instance->m_address_book.size()); } bool ExecuteWalletToolFunc(const std::string& command, const std::string& name) { fs::path path = fs::absolute(name, GetWalletDir()); if (command == "create") { std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, /* create= */ true); if (wallet_instance) { WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); } } else if (command == "info" || command == "salvage") { if (command == "info") { std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, /* create= */ false); if (!wallet_instance) return false; WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); } else if (command == "salvage") { bilingual_str error; std::vector<bilingual_str> warnings; bool ret = RecoverDatabaseFile(path, error, warnings); if (!ret) { for (const auto& warning : warnings) { tfm::format(std::cerr, "%s\n", warning.original); } if (!error.empty()) { tfm::format(std::cerr, "%s\n", error.original); } } return ret; } } else { tfm::format(std::cerr, "Invalid command: %s\n", command); return false; } return true; } } // namespace WalletTool <commit_msg>wallettool: pass in DatabaseOptions into MakeWallet<commit_after>// Copyright (c) 2016-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <fs.h> #include <util/system.h> #include <util/translation.h> #include <wallet/salvage.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> namespace WalletTool { // The standard wallet deleter function blocks on the validation interface // queue, which doesn't exist for the bitcoin-wallet. Define our own // deleter here. static void WalletToolReleaseWallet(CWallet* wallet) { wallet->WalletLogPrintf("Releasing wallet\n"); wallet->Close(); delete wallet; } static void WalletCreate(CWallet* wallet_instance) { LOCK(wallet_instance->cs_wallet); wallet_instance->SetMinVersion(FEATURE_HD_SPLIT); // generate a new HD seed auto spk_man = wallet_instance->GetOrCreateLegacyScriptPubKeyMan(); CPubKey seed = spk_man->GenerateNewSeed(); spk_man->SetHDSeed(seed); tfm::format(std::cout, "Topping up keypool...\n"); wallet_instance->TopUpKeyPool(); } static std::shared_ptr<CWallet> MakeWallet(const std::string& name, const fs::path& path, DatabaseOptions options) { DatabaseStatus status; bilingual_str error; std::unique_ptr<WalletDatabase> database = MakeDatabase(path, options, status, error); if (!database) { tfm::format(std::cerr, "%s\n", error.original); return nullptr; } // dummy chain interface std::shared_ptr<CWallet> wallet_instance{new CWallet(nullptr /* chain */, name, std::move(database)), WalletToolReleaseWallet}; DBErrors load_wallet_ret; try { bool first_run; load_wallet_ret = wallet_instance->LoadWallet(first_run); } catch (const std::runtime_error&) { tfm::format(std::cerr, "Error loading %s. Is wallet being used by another process?\n", name); return nullptr; } if (load_wallet_ret != DBErrors::LOAD_OK) { wallet_instance = nullptr; if (load_wallet_ret == DBErrors::CORRUPT) { tfm::format(std::cerr, "Error loading %s: Wallet corrupted", name); return nullptr; } else if (load_wallet_ret == DBErrors::NONCRITICAL_ERROR) { tfm::format(std::cerr, "Error reading %s! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.", name); } else if (load_wallet_ret == DBErrors::TOO_NEW) { tfm::format(std::cerr, "Error loading %s: Wallet requires newer version of %s", name, PACKAGE_NAME); return nullptr; } else if (load_wallet_ret == DBErrors::NEED_REWRITE) { tfm::format(std::cerr, "Wallet needed to be rewritten: restart %s to complete", PACKAGE_NAME); return nullptr; } else { tfm::format(std::cerr, "Error loading %s", name); return nullptr; } } if (options.require_create) WalletCreate(wallet_instance.get()); return wallet_instance; } static void WalletShowInfo(CWallet* wallet_instance) { LOCK(wallet_instance->cs_wallet); tfm::format(std::cout, "Wallet info\n===========\n"); tfm::format(std::cout, "Name: %s\n", wallet_instance->GetName()); tfm::format(std::cout, "Format: %s\n", wallet_instance->GetDatabase().Format()); tfm::format(std::cout, "Descriptors: %s\n", wallet_instance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) ? "yes" : "no"); tfm::format(std::cout, "Encrypted: %s\n", wallet_instance->IsCrypted() ? "yes" : "no"); tfm::format(std::cout, "HD (hd seed available): %s\n", wallet_instance->IsHDEnabled() ? "yes" : "no"); tfm::format(std::cout, "Keypool Size: %u\n", wallet_instance->GetKeyPoolSize()); tfm::format(std::cout, "Transactions: %zu\n", wallet_instance->mapWallet.size()); tfm::format(std::cout, "Address Book: %zu\n", wallet_instance->m_address_book.size()); } bool ExecuteWalletToolFunc(const std::string& command, const std::string& name) { fs::path path = fs::absolute(name, GetWalletDir()); if (command == "create") { DatabaseOptions options; options.require_create = true; std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, options); if (wallet_instance) { WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); } } else if (command == "info" || command == "salvage") { if (command == "info") { DatabaseOptions options; options.require_existing = true; std::shared_ptr<CWallet> wallet_instance = MakeWallet(name, path, options); if (!wallet_instance) return false; WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); } else if (command == "salvage") { bilingual_str error; std::vector<bilingual_str> warnings; bool ret = RecoverDatabaseFile(path, error, warnings); if (!ret) { for (const auto& warning : warnings) { tfm::format(std::cerr, "%s\n", warning.original); } if (!error.empty()) { tfm::format(std::cerr, "%s\n", error.original); } } return ret; } } else { tfm::format(std::cerr, "Invalid command: %s\n", command); return false; } return true; } } // namespace WalletTool <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_CONFIG_HELPERS_INCLUDED #define MAPNIK_CONFIG_HELPERS_INCLUDED #include <mapnik/enumeration.hpp> #include <mapnik/config_error.hpp> #include <mapnik/color_factory.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <iostream> #include <sstream> namespace mapnik { template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value); template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name); template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, true); } template <typename T> boost::optional<T> get_opt_child( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, false); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name, const T & default_value ) { return get<T>( node, name, true, default_value); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name ) { return get<T>( node, name, true ); } template <typename T> T get_css( const boost::property_tree::ptree & node, const std::string & name ) { return get_own<T>( node, std::string("CSS parameter '") + name + "'"); } // specialization for color type template <> inline color get_css (boost::property_tree::ptree const& node, std::string const& name) { std::string str = get_own<std::string>( node, std::string("CSS parameter '") + name + "'"); ; try { return mapnik::color_factory::from_string(str.c_str()); } catch (...) { throw config_error(string("Failed to parse ") + name + "'. Expected CSS color" + " but got '" + str + "'"); } } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c ) { std::string hex_string( c.to_hex_string() ); s << hex_string; return s; } /** Helper for class bool */ class boolean { public: boolean() {} boolean(bool b) : b_(b) {} boolean(const boolean & b) : b_(b.b_) {} operator bool() const { return b_; } boolean & operator = (const boolean & other) { b_ = other.b_; return * this; } boolean & operator = (bool other) { b_ = other; return * this; } private: bool b_; }; /** Special stream input operator for boolean values */ template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean & b ) { std::string word; s >> word; if ( s ) { if ( word == "true" || word == "yes" || word == "on" || word == "1") { b = true; } else if ( word == "false" || word == "no" || word == "off" || word == "0") { b = false; } else { s.setstate( std::ios::failbit ); } } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const boolean & b ) { s << ( b ? "true" : "false" ); return s; } template <typename T> void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v) { pt.put("<xmlattr>." + name, v); } /* template <> void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v) { pt.put("<xmlattr>." + name, boolean(v)); } */ class boolean; template <typename T> void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v) { boost::property_tree::ptree & css_node = pt.push_back( boost::property_tree::ptree::value_type("CssParameter", boost::property_tree::ptree()))->second; css_node.put("<xmlattr>.name", name ); css_node.put_own( v ); } template <typename T> struct name_trait { static std::string name() { return "<unknown>"; } // missing name_trait for type ... // if you get here you are probably using a new type // in the XML file. Just add a name trait for the new // type below. BOOST_STATIC_ASSERT( sizeof(T) == 0 ); }; #define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \ template <> \ struct name_trait<type> \ { \ static std::string name() { return std::string("type ") + type_name; } \ }; #define DEFINE_NAME_TRAIT( type ) \ DEFINE_NAME_TRAIT_WITH_NAME( type, #type ); DEFINE_NAME_TRAIT( double ); DEFINE_NAME_TRAIT( float ); DEFINE_NAME_TRAIT( unsigned ); DEFINE_NAME_TRAIT( boolean ); DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" ); DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" ); DEFINE_NAME_TRAIT_WITH_NAME( color, "color" ); template <typename ENUM, int MAX> struct name_trait< mapnik::enumeration<ENUM, MAX> > { typedef enumeration<ENUM, MAX> Enum; static std::string name() { std::string value_list("one of ["); for (unsigned i = 0; i < Enum::MAX; ++i) { value_list += Enum::get_string( i ); if ( i + 1 < Enum::MAX ) value_list += ", "; } value_list += "]"; return value_list; } }; template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return boost::lexical_cast<T>( * str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <> inline color get(boost::property_tree::ptree const& node, std::string const& name, bool is_attribute, color const& default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } if ( ! str ) { throw config_error(string("Required ") + (is_attribute ? "attribute " : "child node ") + "'" + name + "' is missing"); } try { return boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name) { try { return node.get_own<T>(); } catch (...) { throw config_error(string("Failed to parse ") + name + ". Expected " + name_trait<T>::name() + " but got '" + node.data() + "'"); } } template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<T> result; if ( str ) { try { result = boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast &) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } return result; } // template <> inline boost::optional<color> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<color> result; if ( str ) { try { //result = boost::lexical_cast<T>( *str ); result = mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } return result; } } // end of namespace mapnik #endif // MAPNIK_CONFIG_HELPERS_INCLUDED <commit_msg>+ mapnik-write-colors-using-rgba-not-hex.patch (jonb) When you use save_xml() the colors are written out in #RGB format which can not represent alpha information. The patch makes it save using the rgb()/rgba() strings.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_CONFIG_HELPERS_INCLUDED #define MAPNIK_CONFIG_HELPERS_INCLUDED #include <mapnik/enumeration.hpp> #include <mapnik/config_error.hpp> #include <mapnik/color_factory.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <iostream> #include <sstream> namespace mapnik { template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value); template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name); template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, true); } template <typename T> boost::optional<T> get_opt_child( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, false); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name, const T & default_value ) { return get<T>( node, name, true, default_value); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name ) { return get<T>( node, name, true ); } template <typename T> T get_css( const boost::property_tree::ptree & node, const std::string & name ) { return get_own<T>( node, std::string("CSS parameter '") + name + "'"); } // specialization for color type template <> inline color get_css (boost::property_tree::ptree const& node, std::string const& name) { std::string str = get_own<std::string>( node, std::string("CSS parameter '") + name + "'"); ; try { return mapnik::color_factory::from_string(str.c_str()); } catch (...) { throw config_error(string("Failed to parse ") + name + "'. Expected CSS color" + " but got '" + str + "'"); } } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c ) { std::string hex_string( c.to_string() ); s << hex_string; return s; } /** Helper for class bool */ class boolean { public: boolean() {} boolean(bool b) : b_(b) {} boolean(const boolean & b) : b_(b.b_) {} operator bool() const { return b_; } boolean & operator = (const boolean & other) { b_ = other.b_; return * this; } boolean & operator = (bool other) { b_ = other; return * this; } private: bool b_; }; /** Special stream input operator for boolean values */ template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean & b ) { std::string word; s >> word; if ( s ) { if ( word == "true" || word == "yes" || word == "on" || word == "1") { b = true; } else if ( word == "false" || word == "no" || word == "off" || word == "0") { b = false; } else { s.setstate( std::ios::failbit ); } } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const boolean & b ) { s << ( b ? "true" : "false" ); return s; } template <typename T> void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v) { pt.put("<xmlattr>." + name, v); } /* template <> void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v) { pt.put("<xmlattr>." + name, boolean(v)); } */ class boolean; template <typename T> void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v) { boost::property_tree::ptree & css_node = pt.push_back( boost::property_tree::ptree::value_type("CssParameter", boost::property_tree::ptree()))->second; css_node.put("<xmlattr>.name", name ); css_node.put_own( v ); } template <typename T> struct name_trait { static std::string name() { return "<unknown>"; } // missing name_trait for type ... // if you get here you are probably using a new type // in the XML file. Just add a name trait for the new // type below. BOOST_STATIC_ASSERT( sizeof(T) == 0 ); }; #define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \ template <> \ struct name_trait<type> \ { \ static std::string name() { return std::string("type ") + type_name; } \ }; #define DEFINE_NAME_TRAIT( type ) \ DEFINE_NAME_TRAIT_WITH_NAME( type, #type ); DEFINE_NAME_TRAIT( double ); DEFINE_NAME_TRAIT( float ); DEFINE_NAME_TRAIT( unsigned ); DEFINE_NAME_TRAIT( boolean ); DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" ); DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" ); DEFINE_NAME_TRAIT_WITH_NAME( color, "color" ); template <typename ENUM, int MAX> struct name_trait< mapnik::enumeration<ENUM, MAX> > { typedef enumeration<ENUM, MAX> Enum; static std::string name() { std::string value_list("one of ["); for (unsigned i = 0; i < Enum::MAX; ++i) { value_list += Enum::get_string( i ); if ( i + 1 < Enum::MAX ) value_list += ", "; } value_list += "]"; return value_list; } }; template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return boost::lexical_cast<T>( * str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <> inline color get(boost::property_tree::ptree const& node, std::string const& name, bool is_attribute, color const& default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } if ( ! str ) { throw config_error(string("Required ") + (is_attribute ? "attribute " : "child node ") + "'" + name + "' is missing"); } try { return boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name) { try { return node.get_own<T>(); } catch (...) { throw config_error(string("Failed to parse ") + name + ". Expected " + name_trait<T>::name() + " but got '" + node.data() + "'"); } } template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<T> result; if ( str ) { try { result = boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast &) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } return result; } // template <> inline boost::optional<color> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<color> result; if ( str ) { try { //result = boost::lexical_cast<T>( *str ); result = mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } return result; } } // end of namespace mapnik #endif // MAPNIK_CONFIG_HELPERS_INCLUDED <|endoftext|>
<commit_before>#include <boost/lexical_cast.hpp> #include <qwt_symbol.h> #include "graphPlot.h" using namespace std; using namespace watcher; INIT_LOGGER(TimeScaleDraw, "TimeScaleDraw"); INIT_LOGGER(GraphCurve, "GraphCurve"); INIT_LOGGER(GraphPlot, "GraphPlot"); TimeScaleDraw::TimeScaleDraw(const QTime &base): baseTime(base) { TRACE_ENTER(); TRACE_EXIT(); } QwtText TimeScaleDraw::label(double v) const { TRACE_ENTER(); QTime upTime = baseTime.addSecs((int)v); return upTime.toString(); TRACE_EXIT(); } GraphCurve::GraphCurve(const QString &title): QwtPlotCurve(title) { TRACE_ENTER(); setRenderHint(QwtPlotItem::RenderAntialiased); TRACE_EXIT(); } void GraphCurve::setColor(const QColor &color) { TRACE_ENTER(); QColor c = color; c.setAlpha(150); setPen(c); // setBrush(c); // Don't fill below curve. TRACE_EXIT(); } GraphPlot::GraphPlot(QWidget *parent, const QString &title_) : QwtPlot(parent), title(title_), timeDataSize(60) { TRACE_ENTER(); timeData.reserve(timeDataSize); // Initialize time data to 1, 2, ... sizeof(timeData)-1 for (int i=timeDataSize; i>0; i--) timeData.push_back(i); setTitle(title); setAutoReplot(false); plotLayout()->setAlignCanvasToScales(true); QwtLegend *legend = new QwtLegend; legend->setItemMode(QwtLegend::CheckableItem); insertLegend(legend, QwtPlot::RightLegend); setAxisTitle(QwtPlot::xBottom, "Time"); setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw(QTime::currentTime())); setAxisScale(QwtPlot::xBottom, 0, timeDataSize); setAxisLabelRotation(QwtPlot::xBottom, -50.0); setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom); // add space for right aligned label QwtScaleWidget *scaleWidget = axisWidget(QwtPlot::xBottom); const int fmh = QFontMetrics(scaleWidget->font()).height(); scaleWidget->setMinBorderDist(0, fmh / 2); setAxisTitle(QwtPlot::yLeft, title); // setAxisScale(QwtPlot::yLeft, 0, 100); LOG_DEBUG("Starting 1 second timer for graph plot " << title.toStdString()); (void)startTimer(1000); // 1 second connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), SLOT(showCurve(QwtPlotItem *, bool))); TRACE_EXIT(); } void GraphPlot::addDataPoint(unsigned int curveId, float dataPoint) { TRACE_ENTER(); GraphData::iterator data=graphData.find(curveId); // Create a new curve, if we've never seen this curveId before. if (data==graphData.end()) addCurve(curveId); LOG_DEBUG("Pushing back data point " << dataPoint << " for curve id " << (0xFF & curveId)); graphData[curveId]->data.push_front(dataPoint); graphData[curveId]->pointSet=true; // we only want timeDataSize data points, so trim front if longer than that. if (graphData[curveId]->data.size()>timeDataSize) graphData[curveId]->data.pop_back(); TRACE_EXIT(); } void GraphPlot::timerEvent(QTimerEvent * /*event*/) { TRACE_ENTER(); for (int i=0;i<timeDataSize;i++) timeData[i]++; setAxisScale(QwtPlot::xBottom, timeData[timeDataSize-1], timeData[0]); for (GraphData::iterator d=graphData.begin(); d!=graphData.end(); d++) { if (!d->second->pointSet) // Didn't hear from the node for last second, set data to zero. { LOG_DEBUG("Didn't hear from node " << (0xFF & d->first) << " setting this second's data to 0"); d->second->data.push_front(0); if (d->second->data.size()>timeDataSize) d->second->data.pop_back(); } else d->second->pointSet=false; // reset for next go around. d->second->curve->setData(timeData, d->second->data); } replot(); TRACE_EXIT(); } void GraphPlot::showCurve(QwtPlotItem *curve, bool on) { TRACE_ENTER(); LOG_DEBUG("Setting curve " << (on?"":"in") << "visible.") curve->setVisible(on); QWidget *w = legend()->find(curve); if ( w && w->inherits("QwtLegendItem") ) ((QwtLegendItem *)w)->setChecked(on); TRACE_EXIT(); } void GraphPlot::showCurve(unsigned int curveId, bool on) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to show curve for a node we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } showCurve(graphData[curveId]->curve.get(), on); replot(); TRACE_EXIT(); } void GraphPlot::toggleCurveAndLegendVisible(unsigned int curveId) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to toggle visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } QWidget *w = legend()->find(graphData[curveId]->curve.get()); if ( w && w->inherits("QwtLegendItem") ) curveAndLegendVisible(curveId, !((QwtLegendItem *)w)->isVisible()); else { LOG_ERROR("Missing legend for curve with id " << (0xff & curveId)); } TRACE_EXIT(); } void GraphPlot::curveAndLegendVisible(unsigned int curveId, bool visible) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to set/unset visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } graphData[curveId]->curve->setVisible(visible); QWidget *w = legend()->find(graphData[curveId]->curve.get()); if ( w && w->inherits("QwtLegendItem") ) { ((QwtLegendItem *)w)->setVisible(visible); ((QwtLegendItem *)w)->setChecked(visible); } emit curveAndLegendToggled(visible); TRACE_EXIT(); } void GraphPlot::addCurve(unsigned int curveId) { TRACE_ENTER(); boost::shared_ptr<CurveData> data(new CurveData); for (int i=0; i<timeDataSize; i++) data->data.push_back(0); graphData[curveId]=data; string curveTitle=boost::lexical_cast<string>((unsigned int)(0xFF & curveId)); data->curve=boost::shared_ptr<GraphCurve>(new GraphCurve(curveTitle.c_str())); data->curve->setColor(QColor::fromHsv(qrand() % 256, 255, 190)); data->curve->setStyle(QwtPlotCurve::Lines); data->curve->attach(this); LOG_DEBUG("Created new curve " << (0xFF & curveId)); TRACE_EXIT(); } <commit_msg>hide all curves until the user double clicks on the node in the watcher main window<commit_after>#include <boost/lexical_cast.hpp> #include <qwt_symbol.h> #include "graphPlot.h" using namespace std; using namespace watcher; INIT_LOGGER(TimeScaleDraw, "TimeScaleDraw"); INIT_LOGGER(GraphCurve, "GraphCurve"); INIT_LOGGER(GraphPlot, "GraphPlot"); TimeScaleDraw::TimeScaleDraw(const QTime &base): baseTime(base) { TRACE_ENTER(); TRACE_EXIT(); } QwtText TimeScaleDraw::label(double v) const { TRACE_ENTER(); QTime upTime = baseTime.addSecs((int)v); return upTime.toString(); TRACE_EXIT(); } GraphCurve::GraphCurve(const QString &title): QwtPlotCurve(title) { TRACE_ENTER(); setRenderHint(QwtPlotItem::RenderAntialiased); TRACE_EXIT(); } void GraphCurve::setColor(const QColor &color) { TRACE_ENTER(); QColor c = color; c.setAlpha(150); setPen(c); // setBrush(c); // Don't fill below curve. TRACE_EXIT(); } GraphPlot::GraphPlot(QWidget *parent, const QString &title_) : QwtPlot(parent), title(title_), timeDataSize(60) { TRACE_ENTER(); timeData.reserve(timeDataSize); // Initialize time data to 1, 2, ... sizeof(timeData)-1 for (int i=timeDataSize; i>0; i--) timeData.push_back(i); setTitle(title); setAutoReplot(false); plotLayout()->setAlignCanvasToScales(true); QwtLegend *legend = new QwtLegend; legend->setItemMode(QwtLegend::CheckableItem); insertLegend(legend, QwtPlot::RightLegend); setAxisTitle(QwtPlot::xBottom, "Time"); setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw(QTime::currentTime())); setAxisScale(QwtPlot::xBottom, 0, timeDataSize); setAxisLabelRotation(QwtPlot::xBottom, -50.0); setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom); // add space for right aligned label QwtScaleWidget *scaleWidget = axisWidget(QwtPlot::xBottom); const int fmh = QFontMetrics(scaleWidget->font()).height(); scaleWidget->setMinBorderDist(0, fmh / 2); setAxisTitle(QwtPlot::yLeft, title); // setAxisScale(QwtPlot::yLeft, 0, 100); LOG_DEBUG("Starting 1 second timer for graph plot " << title.toStdString()); (void)startTimer(1000); // 1 second connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), SLOT(showCurve(QwtPlotItem *, bool))); TRACE_EXIT(); } void GraphPlot::addDataPoint(unsigned int curveId, float dataPoint) { TRACE_ENTER(); GraphData::iterator data=graphData.find(curveId); // Create a new curve, if we've never seen this curveId before. if (data==graphData.end()) addCurve(curveId); LOG_DEBUG("Pushing back data point " << dataPoint << " for curve id " << (0xFF & curveId)); graphData[curveId]->data.push_front(dataPoint); graphData[curveId]->pointSet=true; // we only want timeDataSize data points, so trim front if longer than that. if (graphData[curveId]->data.size()>timeDataSize) graphData[curveId]->data.pop_back(); TRACE_EXIT(); } void GraphPlot::timerEvent(QTimerEvent * /*event*/) { TRACE_ENTER(); for (int i=0;i<timeDataSize;i++) timeData[i]++; setAxisScale(QwtPlot::xBottom, timeData[timeDataSize-1], timeData[0]); for (GraphData::iterator d=graphData.begin(); d!=graphData.end(); d++) { if (!d->second->pointSet) // Didn't hear from the node for last second, set data to zero. { LOG_DEBUG("Didn't hear from node " << (0xFF & d->first) << " setting this second's data to 0"); d->second->data.push_front(0); if (d->second->data.size()>timeDataSize) d->second->data.pop_back(); } else d->second->pointSet=false; // reset for next go around. d->second->curve->setData(timeData, d->second->data); } replot(); TRACE_EXIT(); } void GraphPlot::showCurve(QwtPlotItem *curve, bool on) { TRACE_ENTER(); LOG_DEBUG("Setting curve " << (on?"":"in") << "visible.") curve->setVisible(on); QWidget *w = legend()->find(curve); if ( w && w->inherits("QwtLegendItem") ) ((QwtLegendItem *)w)->setChecked(on); TRACE_EXIT(); } void GraphPlot::showCurve(unsigned int curveId, bool on) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to show curve for a node we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } showCurve(graphData[curveId]->curve.get(), on); replot(); TRACE_EXIT(); } void GraphPlot::toggleCurveAndLegendVisible(unsigned int curveId) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to toggle visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } QWidget *w = legend()->find(graphData[curveId]->curve.get()); if ( w && w->inherits("QwtLegendItem") ) curveAndLegendVisible(curveId, !((QwtLegendItem *)w)->isVisible()); else { LOG_ERROR("Missing legend for curve with id " << (0xff & curveId)); } TRACE_EXIT(); } void GraphPlot::curveAndLegendVisible(unsigned int curveId, bool visible) { TRACE_ENTER(); if (graphData.end()==graphData.find(curveId)) { LOG_DEBUG("User wants to set/unset visibility for a curve we've never seen, adding empty curve with id " << (0xFF & curveId)); addCurve(curveId); } graphData[curveId]->curve->setVisible(visible); QWidget *w = legend()->find(graphData[curveId]->curve.get()); if ( w && w->inherits("QwtLegendItem") ) { ((QwtLegendItem *)w)->setVisible(visible); ((QwtLegendItem *)w)->setChecked(visible); } emit curveAndLegendToggled(visible); TRACE_EXIT(); } void GraphPlot::addCurve(unsigned int curveId) { TRACE_ENTER(); boost::shared_ptr<CurveData> data(new CurveData); for (int i=0; i<timeDataSize; i++) data->data.push_back(0); graphData[curveId]=data; string curveTitle=boost::lexical_cast<string>((unsigned int)(0xFF & curveId)); data->curve=boost::shared_ptr<GraphCurve>(new GraphCurve(curveTitle.c_str())); data->curve->setColor(QColor::fromHsv(qrand() % 256, 255, 190)); data->curve->setStyle(QwtPlotCurve::Lines); data->curve->attach(this); curveAndLegendVisible(curveId, false); LOG_DEBUG("Created new curve " << (0xFF & curveId)); TRACE_EXIT(); } <|endoftext|>
<commit_before>// // Copyright (C) 2016 Greg Landrum // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/MolDraw2D/MolDraw2DUtils.h> #include <GraphMol/RWMol.h> #include <GraphMol/MolOps.h> #include <GraphMol/Depictor/RDDepictor.h> #include <GraphMol/FileParsers/MolFileStereochem.h> namespace RDKit { namespace MolDraw2DUtils { void prepareMolForDrawing(RWMol &mol, bool kekulize, bool addChiralHs, bool wedgeBonds, bool forceCoords) { if (kekulize) { MolOps::Kekulize(mol, false); // kekulize, but keep the aromatic flags! } if (addChiralHs) { std::vector<unsigned int> chiralAts; for (RWMol::AtomIterator atIt = mol.beginAtoms(); atIt != mol.endAtoms(); ++atIt) { if ((*atIt)->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW || (*atIt)->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW) { chiralAts.push_back((*atIt)->getIdx()); } } if (chiralAts.size()) { bool addCoords = false; if (!forceCoords && mol.getNumConformers()) addCoords = true; MolOps::addHs(mol, false, addCoords, &chiralAts); } } if (forceCoords || !mol.getNumConformers()) { RDDepict::compute2DCoords(mol); } if (wedgeBonds) { WedgeMolBonds(mol, &mol.getConformer()); } } } } <commit_msg>standardize the orientation when generating coords<commit_after>// // Copyright (C) 2016 Greg Landrum // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/MolDraw2D/MolDraw2DUtils.h> #include <GraphMol/RWMol.h> #include <GraphMol/MolOps.h> #include <GraphMol/Depictor/RDDepictor.h> #include <GraphMol/FileParsers/MolFileStereochem.h> namespace RDKit { namespace MolDraw2DUtils { void prepareMolForDrawing(RWMol &mol, bool kekulize, bool addChiralHs, bool wedgeBonds, bool forceCoords) { if (kekulize) { MolOps::Kekulize(mol, false); // kekulize, but keep the aromatic flags! } if (addChiralHs) { std::vector<unsigned int> chiralAts; for (RWMol::AtomIterator atIt = mol.beginAtoms(); atIt != mol.endAtoms(); ++atIt) { if ((*atIt)->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW || (*atIt)->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW) { chiralAts.push_back((*atIt)->getIdx()); } } if (chiralAts.size()) { bool addCoords = false; if (!forceCoords && mol.getNumConformers()) addCoords = true; MolOps::addHs(mol, false, addCoords, &chiralAts); } } if (forceCoords || !mol.getNumConformers()) { // compute 2D coordinates in a standard orientation: RDDepict::compute2DCoords(mol, NULL, true); } if (wedgeBonds) { WedgeMolBonds(mol, &mol.getConformer()); } } } } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "basename.h" #include "util_lib_proto.h" // for rotate_file #include "log_rotate.h" #include <sys/types.h> #ifndef WIN32 #include <dirent.h> #endif /** is it a *.old file? */ static int isOldString(const char *str); /** is the argument an ISO timestamp? */ static int isTimestampString(const char *str); /** is the argument a valid log filename? */ static int isLogFilename(const char *filename); /** find the oldest file in the directory matching the *current base name according to iso time ending */ static char *findOldest(char *dirName, int *count); #ifdef WIN32 char * searchLogName = NULL; #endif char * logBaseName = NULL; char * baseDirName = NULL; int isInitialized = 0; int numLogs = 0; // max size of an iso timestamp extenstion 4+2+2+1+2+2+2 #define MAX_ISO_TIMESTAMP 16 /** create an ISO timestamp string */ static void createTimestampString(std::string & timestamp, time_t tt) { struct tm *tm; tm = localtime(&tt); char buf[80]; strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", tm); timestamp = buf; } long long quantizeTimestamp(time_t tt, long long secs) { if ( ! secs) return tt; static int leap_sec = -1; if (leap_sec < 0) { struct tm * ptm = localtime(&tt); ptm->tm_hour = 0; ptm->tm_min = 0; ptm->tm_sec = 0; time_t today = mktime(ptm); leap_sec = today % 3600; } return tt - (tt % secs); } #ifndef WIN32 static int scandirectory(const char *dir, struct dirent ***namelist, int (*select)(const struct dirent *), int (*compar)(const void*, const void*) ) { DIR *d; struct dirent *entry; int i = 0; size_t entrysize; if ((d=opendir(dir)) == NULL) return(-1); *namelist=NULL; while ((entry=readdir(d)) != NULL) { if (select == NULL || (select != NULL && (*select)(entry))) { *namelist=(struct dirent **)realloc((void *)(*namelist), (size_t)((i+1)*sizeof(struct dirent *))); if (*namelist == NULL) { closedir(d); return -1; } entrysize=sizeof(struct dirent)-sizeof(entry->d_name)+strlen(entry->d_name)+1; (*namelist)[i]=(struct dirent *)malloc(entrysize); if ((*namelist)[i] == NULL) { closedir(d); return(-1); } memcpy((*namelist)[i], entry, entrysize); i++; } } if (closedir(d)) return -1; if (i == 0) return -1; if (compar != NULL) qsort((void *)(*namelist), (size_t)i, sizeof(struct dirent *), compar); return i; } static int doalphasort(const void *a, const void *b) { const struct dirent **d1 = (const struct dirent**)const_cast<void*>(a); const struct dirent **d2 = (const struct dirent**)const_cast<void*>(b); return(strcmp(const_cast<char*>((*d1)->d_name), const_cast<char*>((*d2)->d_name))); } #endif void setBaseName(const char *baseName) { // Since one log file can have different ones per debug level, // we need to check whether we want to deal with a different base name if ( (isInitialized == 1) && (strcmp(baseName, logBaseName) != 0) ) { isInitialized = 0; } if (isInitialized == 0) { char *tmpDir; if (logBaseName) free(logBaseName); logBaseName = strdup(baseName); tmpDir = condor_dirname(logBaseName); if (baseDirName) free(baseDirName); baseDirName = strdup(tmpDir); free(tmpDir); #ifdef WIN32 if (searchLogName) free(searchLogName); searchLogName = (char *)malloc(strlen(logBaseName)+3); sprintf(searchLogName, "%s.*", (const char*)logBaseName); #endif isInitialized = 1; } } int rotateSingle() { return rotateTimestamp("old", 1, 0); } const char * createRotateFilename(const char *ending, int maxNum, time_t tt) { static std::string timeStamp; if (maxNum <= 1) timeStamp = "old"; else if (ending == NULL) { createTimestampString(timeStamp, tt); } else { timeStamp = ending; } return timeStamp.c_str(); } // rotate the current file to file.timestamp int rotateTimestamp(const char *timeStamp, int maxNum, time_t tt) { int save_errno; const char *ts = createRotateFilename(timeStamp, maxNum, tt); // First, select a name for the rotated history file char *rotated_log_name = (char*)malloc(strlen(logBaseName) + strlen(ts) + 2) ; ASSERT( rotated_log_name ); (void)sprintf( rotated_log_name, "%s.%s", logBaseName, ts ); save_errno = rotate_file_dprintf(logBaseName, rotated_log_name, 1); free(rotated_log_name); return save_errno; // will be 0 in case of success. } /* tj : change to delete files rather than 'rotating' them when the number exceeds 1 this code currently will take the oldest .timestamp file and rename it to .old which seems wrong. */ int cleanUpOldLogFiles(int maxNum) { int count; char *oldFile = NULL; char empty[BUFSIZ]; /* even if current maxNum is set to 1, clean up in case a config change took place. */ if (maxNum > 0 ) { oldFile = findOldest(baseDirName, &count); while (count > maxNum) { (void)sprintf( empty, "%s.old", logBaseName ); // catch the exception that the file name pattern is disturbed by external influence if (strcmp(oldFile, empty) == 0) break; if ( rotate_file(oldFile,empty) != 0) { dprintf(D_ALWAYS, "Rotation cleanup of old file %s failed.\n", oldFile); } free(oldFile); oldFile = findOldest(baseDirName, &count); } } if (oldFile != NULL) { free(oldFile); oldFile = NULL; } return 0; } static int isOldString(const char *str){ if (strcmp(str, "old") == 0) return 1; return 0; } static int isTimestampString(const char *str) { int len = strlen(str); if (len != 15) { return 0; } int i = 0; while (i < 8) { if (str[i] < '0' || str[i] > '9') return 0; ++i; } if (str[i++] != 'T') return 0; while (i < len) { if (str[i] < '0' || str[i] > '9') return 0; ++i; } return 1; } static int isLogFilename(const char *filename) { int dirLen = strlen(baseDirName); #ifdef WIN32 if (baseDirName[dirLen-1] != DIR_DELIM_CHAR && baseDirName[dirLen-1] != '/') ++dirLen; #else if (baseDirName[dirLen-1] != DIR_DELIM_CHAR) ++dirLen; #endif int fLen = strlen(logBaseName); if (strncmp(filename, (logBaseName+dirLen), fLen - dirLen) == 0 ) { if ( (strlen(filename) > unsigned(fLen-dirLen)) && (filename[fLen-dirLen] == '.') ) { if ( (isTimestampString(filename+(fLen-dirLen+1)) == 1) || (isOldString(filename+(fLen-dirLen+1)) == 1) ) return 1; } } return 0; } #ifndef WIN32 static int file_select(const struct dirent *entry) { return isLogFilename(entry->d_name); } char *findOldest(char *dirName, int *count) { struct dirent **files; int len; *count = scandirectory(dirName, &files, file_select, doalphasort); // no matching files in the directory if (*count <= 0) return NULL; char *oldFile = (char*)files[0]->d_name; len = strlen(oldFile); char *result = (char*)malloc(len+1 + strlen(dirName) + 1); (void)sprintf(result, "%s%c%s", dirName, DIR_DELIM_CHAR, oldFile); for(int i = 0; i < *count; i++) { free(files[i]); } free(files); return result; } #else // return a count of files matching the logfile name pattern, // and the filename of the oldest of these files. char *findOldest(char *dirName, int *count) { char *oldFile = NULL; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; int result; int cchBase = strlen(logBaseName); *count = 0; hFind = FindFirstFile(searchLogName, &ffd); if (hFind == INVALID_HANDLE_VALUE) { return NULL; } // the filenames returned from FindNextFile aren't necessarily sorted // so scan the list, and return the one that sorts the lowest // this should work correctly for .old (because there is only one) // and for .{TIMESTAMP} because the timestamps will sort by date. while ((result = FindNextFile(hFind, &ffd)) != 0) { if ( ! isLogFilename(ffd.cFileName)) continue; ++(*count); if ( ! oldFile) { oldFile = (char*)malloc(strlen(logBaseName) + 2 + MAX_ISO_TIMESTAMP); ASSERT( oldFile ); strcpy(oldFile, ffd.cFileName); } else { int cch = strlen(ffd.cFileName); if (cch > cchBase && strcmp(ffd.cFileName+cchBase, oldFile+cchBase) < 0) { strcpy(oldFile, ffd.cFileName); } } } FindClose(hFind); return oldFile; } #endif <commit_msg>Fix memory leak in log rotation<commit_after>/*************************************************************** * * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "basename.h" #include "util_lib_proto.h" // for rotate_file #include "log_rotate.h" #include <sys/types.h> #ifndef WIN32 #include <dirent.h> #endif /** is it a *.old file? */ static int isOldString(const char *str); /** is the argument an ISO timestamp? */ static int isTimestampString(const char *str); /** is the argument a valid log filename? */ static int isLogFilename(const char *filename); /** find the oldest file in the directory matching the *current base name according to iso time ending */ static char *findOldest(char *dirName, int *count); #ifdef WIN32 char * searchLogName = NULL; #endif char * logBaseName = NULL; char * baseDirName = NULL; int isInitialized = 0; int numLogs = 0; // max size of an iso timestamp extenstion 4+2+2+1+2+2+2 #define MAX_ISO_TIMESTAMP 16 /** create an ISO timestamp string */ static void createTimestampString(std::string & timestamp, time_t tt) { struct tm *tm; tm = localtime(&tt); char buf[80]; strftime(buf, sizeof(buf), "%Y%m%dT%H%M%S", tm); timestamp = buf; } long long quantizeTimestamp(time_t tt, long long secs) { if ( ! secs) return tt; static int leap_sec = -1; if (leap_sec < 0) { struct tm * ptm = localtime(&tt); ptm->tm_hour = 0; ptm->tm_min = 0; ptm->tm_sec = 0; time_t today = mktime(ptm); leap_sec = today % 3600; } return tt - (tt % secs); } #ifndef WIN32 static int scandirectory(const char *dir, struct dirent ***namelist, int (*select)(const struct dirent *), int (*compar)(const void*, const void*) ) { DIR *d; struct dirent *entry; int i = 0; size_t entrysize; if ((d=opendir(dir)) == NULL) return(-1); *namelist=NULL; while ((entry=readdir(d)) != NULL) { if (select == NULL || (select != NULL && (*select)(entry))) { *namelist=(struct dirent **)realloc((void *)(*namelist), (size_t)((i+1)*sizeof(struct dirent *))); if (*namelist == NULL) { closedir(d); return -1; } entrysize=sizeof(struct dirent)-sizeof(entry->d_name)+strlen(entry->d_name)+1; (*namelist)[i]=(struct dirent *)malloc(entrysize); if ((*namelist)[i] == NULL) { closedir(d); return(-1); } memcpy((*namelist)[i], entry, entrysize); i++; } } if (closedir(d)) return -1; if (i == 0) return -1; if (compar != NULL) qsort((void *)(*namelist), (size_t)i, sizeof(struct dirent *), compar); return i; } static int doalphasort(const void *a, const void *b) { const struct dirent **d1 = (const struct dirent**)const_cast<void*>(a); const struct dirent **d2 = (const struct dirent**)const_cast<void*>(b); return(strcmp(const_cast<char*>((*d1)->d_name), const_cast<char*>((*d2)->d_name))); } #endif void setBaseName(const char *baseName) { // Since one log file can have different ones per debug level, // we need to check whether we want to deal with a different base name if ( (isInitialized == 1) && (strcmp(baseName, logBaseName) != 0) ) { isInitialized = 0; } if (isInitialized == 0) { char *tmpDir; if (logBaseName) free(logBaseName); logBaseName = strdup(baseName); tmpDir = condor_dirname(logBaseName); if (baseDirName) free(baseDirName); baseDirName = strdup(tmpDir); free(tmpDir); #ifdef WIN32 if (searchLogName) free(searchLogName); searchLogName = (char *)malloc(strlen(logBaseName)+3); sprintf(searchLogName, "%s.*", (const char*)logBaseName); #endif isInitialized = 1; } } int rotateSingle() { return rotateTimestamp("old", 1, 0); } const char * createRotateFilename(const char *ending, int maxNum, time_t tt) { static std::string timeStamp; if (maxNum <= 1) timeStamp = "old"; else if (ending == NULL) { createTimestampString(timeStamp, tt); } else { timeStamp = ending; } return timeStamp.c_str(); } // rotate the current file to file.timestamp int rotateTimestamp(const char *timeStamp, int maxNum, time_t tt) { int save_errno; const char *ts = createRotateFilename(timeStamp, maxNum, tt); // First, select a name for the rotated history file char *rotated_log_name = (char*)malloc(strlen(logBaseName) + strlen(ts) + 2) ; ASSERT( rotated_log_name ); (void)sprintf( rotated_log_name, "%s.%s", logBaseName, ts ); save_errno = rotate_file_dprintf(logBaseName, rotated_log_name, 1); free(rotated_log_name); return save_errno; // will be 0 in case of success. } /* tj : change to delete files rather than 'rotating' them when the number exceeds 1 this code currently will take the oldest .timestamp file and rename it to .old which seems wrong. */ int cleanUpOldLogFiles(int maxNum) { int count; char *oldFile = NULL; char empty[BUFSIZ]; /* even if current maxNum is set to 1, clean up in case a config change took place. */ if (maxNum > 0 ) { oldFile = findOldest(baseDirName, &count); while (count > maxNum) { (void)sprintf( empty, "%s.old", logBaseName ); // catch the exception that the file name pattern is disturbed by external influence if (strcmp(oldFile, empty) == 0) break; if ( rotate_file(oldFile,empty) != 0) { dprintf(D_ALWAYS, "Rotation cleanup of old file %s failed.\n", oldFile); } free(oldFile); oldFile = findOldest(baseDirName, &count); } } if (oldFile != NULL) { free(oldFile); oldFile = NULL; } return 0; } static int isOldString(const char *str){ if (strcmp(str, "old") == 0) return 1; return 0; } static int isTimestampString(const char *str) { int len = strlen(str); if (len != 15) { return 0; } int i = 0; while (i < 8) { if (str[i] < '0' || str[i] > '9') return 0; ++i; } if (str[i++] != 'T') return 0; while (i < len) { if (str[i] < '0' || str[i] > '9') return 0; ++i; } return 1; } static int isLogFilename(const char *filename) { int dirLen = strlen(baseDirName); #ifdef WIN32 if (baseDirName[dirLen-1] != DIR_DELIM_CHAR && baseDirName[dirLen-1] != '/') ++dirLen; #else if (baseDirName[dirLen-1] != DIR_DELIM_CHAR) ++dirLen; #endif int fLen = strlen(logBaseName); if (strncmp(filename, (logBaseName+dirLen), fLen - dirLen) == 0 ) { if ( (strlen(filename) > unsigned(fLen-dirLen)) && (filename[fLen-dirLen] == '.') ) { if ( (isTimestampString(filename+(fLen-dirLen+1)) == 1) || (isOldString(filename+(fLen-dirLen+1)) == 1) ) return 1; } } return 0; } #ifndef WIN32 static int file_select(const struct dirent *entry) { return isLogFilename(entry->d_name); } char *findOldest(char *dirName, int *count) { struct dirent **files; int len; *count = scandirectory(dirName, &files, file_select, doalphasort); // no matching files in the directory if (*count <= 0) if (files) { free(files); } return NULL; char *oldFile = (char*)files[0]->d_name; len = strlen(oldFile); char *result = (char*)malloc(len+1 + strlen(dirName) + 1); (void)sprintf(result, "%s%c%s", dirName, DIR_DELIM_CHAR, oldFile); for(int i = 0; i < *count; i++) { free(files[i]); } free(files); return result; } #else // return a count of files matching the logfile name pattern, // and the filename of the oldest of these files. char *findOldest(char *dirName, int *count) { char *oldFile = NULL; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; int result; int cchBase = strlen(logBaseName); *count = 0; hFind = FindFirstFile(searchLogName, &ffd); if (hFind == INVALID_HANDLE_VALUE) { return NULL; } // the filenames returned from FindNextFile aren't necessarily sorted // so scan the list, and return the one that sorts the lowest // this should work correctly for .old (because there is only one) // and for .{TIMESTAMP} because the timestamps will sort by date. while ((result = FindNextFile(hFind, &ffd)) != 0) { if ( ! isLogFilename(ffd.cFileName)) continue; ++(*count); if ( ! oldFile) { oldFile = (char*)malloc(strlen(logBaseName) + 2 + MAX_ISO_TIMESTAMP); ASSERT( oldFile ); strcpy(oldFile, ffd.cFileName); } else { int cch = strlen(ffd.cFileName); if (cch > cchBase && strcmp(ffd.cFileName+cchBase, oldFile+cchBase) < 0) { strcpy(oldFile, ffd.cFileName); } } } FindClose(hFind); return oldFile; } #endif <|endoftext|>
<commit_before>// // 16bitBinaryLoader.cpp // Phantasma // // Created by Thomas Harte on 17/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "16bitBinaryLoader.h" #include "Parser.h" #include "16bitDetokeniser.h" class StreamLoader { private: vector<uint8_t>::size_type bytePointer; vector <uint8_t> binary; public: StreamLoader(vector <uint8_t> &_binary) { binary = _binary; bytePointer = 0; } uint8_t get8() { if(!eof()) return binary[bytePointer++]; return 0; } uint16_t get16() { uint16_t result = (uint16_t)(get8() << 8); result |= get8(); return result; } uint32_t get32() { uint32_t result = (uint32_t)(get16() << 16); result |= get16(); return result; } bool eof() { return bytePointer >= binary.size(); } void alignPointer() { if(bytePointer&1) bytePointer++; } void skipBytes(vector<uint8_t>::size_type numberOfBytes) { bytePointer += numberOfBytes; } shared_ptr<vector<uint8_t>> nextBytes(vector<uint8_t>::size_type numberOfBytes) { shared_ptr<vector<uint8_t>> returnBuffer(new vector<uint8_t>); while(numberOfBytes--) returnBuffer->push_back(get8()); return returnBuffer; } }; bool load16bitBinary(vector <uint8_t> &binary) { StreamLoader streamLoader(binary); // find DOS end of file and consume it while(!streamLoader.eof() && streamLoader.get8() != 0x1a); streamLoader.get8(); // advance to the next two-byte boundary if necessary streamLoader.alignPointer(); // skip bytes with meaning unknown streamLoader.get16(); // check that the next two bytes are "PC", then // skip the number that comes after if(streamLoader.get8() != 'C' || streamLoader.get8() != 'P') return false; streamLoader.get16(); // start grabbing some of the basics... uint16_t numberOfAreas = streamLoader.get16(); streamLoader.get16(); // meaning unknown cout << numberOfAreas << " Areas" << endl; uint16_t windowCentreX = streamLoader.get16(); uint16_t windowCentreY = streamLoader.get16(); uint16_t windowWidth = streamLoader.get16(); uint16_t windowHeight = streamLoader.get16(); cout << "Window centre: (" << windowCentreX << ", " << windowCentreY << ")" << endl; cout << "Window size: (" << windowWidth << ", " << windowHeight << ")" << endl; uint16_t scaleX = streamLoader.get16(); uint16_t scaleY = streamLoader.get16(); uint16_t scaleZ = streamLoader.get16(); cout << "Scale: " << scaleX << ", " << scaleY << ", " << scaleZ << endl; uint16_t timerReload = streamLoader.get16(); cout << "Timer: every " << timerReload << " 50Hz frames"; uint16_t maximumActivationDistance = streamLoader.get16(); uint16_t maximumFallDistance = streamLoader.get16(); uint16_t maximumClimbDistance = streamLoader.get16(); cout << "Maximum activation distance: " << maximumActivationDistance << endl; cout << "Maximum fall distance: " << maximumFallDistance << endl; cout << "Maximum climb distance: " << maximumClimbDistance << endl; uint16_t startArea = streamLoader.get16(); uint16_t startEntrance = streamLoader.get16(); cout << "Start at entrance " << startEntrance << " in area " << startArea << endl; uint16_t playerHeight = streamLoader.get16(); uint16_t playerStep = streamLoader.get16(); uint16_t playerAngle = streamLoader.get16(); cout << "Height " << playerHeight << ", stap " << playerStep << ", angle " << playerAngle << endl; uint16_t startVehicle = streamLoader.get16(); uint16_t executeGlobalCondition = streamLoader.get16(); cout << "Start vehicle " << startVehicle << ", execute global condition " << executeGlobalCondition << endl; // I haven't figured out what the next 106 // bytes mean, so we'll skip them — global objects // maybe? Likely not 106 bytes in every file. // // ADDED: having rediscovered my source for the 8bit // file format, could this be shading information by // analogy with that? streamLoader.skipBytes(106); // at this point I should properly load the border/key/mouse // bindings, but I'm not worried about it for now. // // Format is: // (left x, top y, right x, bottom y) - all 16 bit // keyboard key as an ASCII character (or zero for none) // mouse button masl; 00 = both, 01 = left, 02 = right // // So, 10 bytes per binding. Bindings are listed in the order: // // move forwards, move backwards, move right, move left, rise, // fall, turn left, turn right, look up, look down, tilt left, // tilt right, face forward, u-turn, change vehicle type, // select this vehicle, quit game, fire, activate object, // centre cursor on/off, save game position, load game position // // So 35 total. Which means this area takes up 350 bytes. streamLoader.skipBytes(350); // there are then file pointers for every area — these are // the number of shorts from the 'PC' tag, so multiply by // two for bytes. Each is four bytes uint32_t *fileOffsetForArea = new uint32_t[numberOfAreas]; for(uint16_t area = 0; area < numberOfAreas; area++) fileOffsetForArea[area] = (uint32_t)streamLoader.get32() << 1; // now come the global conditions uint16_t numberOfGlobalConditions = streamLoader.get16(); for(uint16_t globalCondition = 0; globalCondition < numberOfGlobalConditions; globalCondition++) { // 12 bytes for the name of the condition; // we don't care streamLoader.skipBytes(12); // get the length and the data itself, converting from // shorts to bytes uint32_t lengthOfCondition = (uint32_t)streamLoader.get16() << 1; // get the condition shared_ptr<vector<uint8_t>> conditionData = streamLoader.nextBytes(lengthOfCondition); cout << "Global condition " << globalCondition+1 << endl; cout << *detokenise16bitCondition(*conditionData) << endl; } delete[] fileOffsetForArea; return true; } <commit_msg>This now manages to log some basic area information.<commit_after>// // 16bitBinaryLoader.cpp // Phantasma // // Created by Thomas Harte on 17/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "16bitBinaryLoader.h" #include "Parser.h" #include "16bitDetokeniser.h" class StreamLoader { private: vector<uint8_t>::size_type bytePointer; vector <uint8_t> binary; public: StreamLoader(vector <uint8_t> &_binary) { binary = _binary; bytePointer = 0; } uint8_t get8() { if(!eof()) return binary[bytePointer++]; return 0; } uint16_t get16() { uint16_t result = (uint16_t)(get8() << 8); result |= get8(); return result; } uint32_t get32() { uint32_t result = (uint32_t)(get16() << 16); result |= get16(); return result; } bool eof() { return bytePointer >= binary.size(); } void alignPointer() { if(bytePointer&1) bytePointer++; } void skipBytes(vector<uint8_t>::size_type numberOfBytes) { bytePointer += numberOfBytes; } shared_ptr<vector<uint8_t>> nextBytes(vector<uint8_t>::size_type numberOfBytes) { shared_ptr<vector<uint8_t>> returnBuffer(new vector<uint8_t>); while(numberOfBytes--) returnBuffer->push_back(get8()); return returnBuffer; } vector<uint8_t>::size_type getFileOffset() { return bytePointer; } void setFileOffset(vector<uint8_t>::size_type newOffset) { bytePointer = newOffset; } }; static void load16bitArea(StreamLoader &stream) { // the lowest bit of this value seems to indicate // horizon on or off; this is as much as I currently know uint16_t skippedValue = stream.get16(); cout << "Skipped value " << skippedValue << endl; uint16_t numberOfObjects = stream.get16(); uint16_t areaScale = stream.get16(); cout << "Objects: " << numberOfObjects << endl; cout << "Scale: " << areaScale << endl; // I've yet to decipher this fully uint16_t horizonColour = stream.get16(); cout << "Horizon colour " << hex << (int)horizonColour << dec << endl; // this is just a complete guess for(int paletteEntry = 0; paletteEntry < 22; paletteEntry++) { uint8_t paletteColour = stream.get8(); cout << "Palette colour (?) " << hex << (int)paletteColour << dec << endl; } // get the objects or whatever for(uint16_t object = 0; object < numberOfObjects; object++) { uint16_t objectType = stream.get16(); uint16_t objectFlags = stream.get16(); // location, size here stream.skipBytes(12); uint16_t objectID = stream.get16(); uint32_t sizeOfObject = (uint32_t)(stream.get16() << 1) - 20; cout << endl; cout << "Object " << objectID << endl; cout << "Type " << hex << objectType << "; flags " << objectFlags << dec << endl; stream.skipBytes(sizeOfObject); } } bool load16bitBinary(vector <uint8_t> &binary) { StreamLoader streamLoader(binary); // find DOS end of file and consume it while(!streamLoader.eof() && streamLoader.get8() != 0x1a); streamLoader.get8(); // advance to the next two-byte boundary if necessary streamLoader.alignPointer(); // skip bytes with meaning unknown streamLoader.get16(); // this brings us to the beginning of the embedded // .KIT file, so we'll grab the base offset for // finding areas later vector<uint8_t>::size_type baseOffset = streamLoader.getFileOffset(); // check that the next two bytes are "PC", then // skip the number that comes after if(streamLoader.get8() != 'C' || streamLoader.get8() != 'P') return false; streamLoader.get16(); // start grabbing some of the basics... uint16_t numberOfAreas = streamLoader.get16(); streamLoader.get16(); // meaning unknown cout << numberOfAreas << " Areas" << endl; uint16_t windowCentreX = streamLoader.get16(); uint16_t windowCentreY = streamLoader.get16(); uint16_t windowWidth = streamLoader.get16(); uint16_t windowHeight = streamLoader.get16(); cout << "Window centre: (" << windowCentreX << ", " << windowCentreY << ")" << endl; cout << "Window size: (" << windowWidth << ", " << windowHeight << ")" << endl; uint16_t scaleX = streamLoader.get16(); uint16_t scaleY = streamLoader.get16(); uint16_t scaleZ = streamLoader.get16(); cout << "Scale: " << scaleX << ", " << scaleY << ", " << scaleZ << endl; uint16_t timerReload = streamLoader.get16(); cout << "Timer: every " << timerReload << " 50Hz frames"; uint16_t maximumActivationDistance = streamLoader.get16(); uint16_t maximumFallDistance = streamLoader.get16(); uint16_t maximumClimbDistance = streamLoader.get16(); cout << "Maximum activation distance: " << maximumActivationDistance << endl; cout << "Maximum fall distance: " << maximumFallDistance << endl; cout << "Maximum climb distance: " << maximumClimbDistance << endl; uint16_t startArea = streamLoader.get16(); uint16_t startEntrance = streamLoader.get16(); cout << "Start at entrance " << startEntrance << " in area " << startArea << endl; uint16_t playerHeight = streamLoader.get16(); uint16_t playerStep = streamLoader.get16(); uint16_t playerAngle = streamLoader.get16(); cout << "Height " << playerHeight << ", stap " << playerStep << ", angle " << playerAngle << endl; uint16_t startVehicle = streamLoader.get16(); uint16_t executeGlobalCondition = streamLoader.get16(); cout << "Start vehicle " << startVehicle << ", execute global condition " << executeGlobalCondition << endl; // I haven't figured out what the next 106 // bytes mean, so we'll skip them — global objects // maybe? Likely not 106 bytes in every file. // // ADDED: having rediscovered my source for the 8bit // file format, could this be shading information by // analogy with that? streamLoader.skipBytes(106); // at this point I should properly load the border/key/mouse // bindings, but I'm not worried about it for now. // // Format is: // (left x, top y, right x, bottom y) - all 16 bit // keyboard key as an ASCII character (or zero for none) // mouse button masl; 00 = both, 01 = left, 02 = right // // So, 10 bytes per binding. Bindings are listed in the order: // // move forwards, move backwards, move right, move left, rise, // fall, turn left, turn right, look up, look down, tilt left, // tilt right, face forward, u-turn, change vehicle type, // select this vehicle, quit game, fire, activate object, // centre cursor on/off, save game position, load game position // // So 35 total. Which means this area takes up 350 bytes. streamLoader.skipBytes(350); // there are then file pointers for every area — these are // the number of shorts from the 'PC' tag, so multiply by // two for bytes. Each is four bytes uint32_t *fileOffsetForArea = new uint32_t[numberOfAreas]; for(uint16_t area = 0; area < numberOfAreas; area++) fileOffsetForArea[area] = (uint32_t)streamLoader.get32() << 1; // now come the global conditions uint16_t numberOfGlobalConditions = streamLoader.get16(); for(uint16_t globalCondition = 0; globalCondition < numberOfGlobalConditions; globalCondition++) { // 12 bytes for the name of the condition; // we don't care streamLoader.skipBytes(12); // get the length and the data itself, converting from // shorts to bytes uint32_t lengthOfCondition = (uint32_t)streamLoader.get16() << 1; // get the condition shared_ptr<vector<uint8_t>> conditionData = streamLoader.nextBytes(lengthOfCondition); cout << "Global condition " << globalCondition+1 << endl; cout << *detokenise16bitCondition(*conditionData) << endl; } // grab the areas (well, for now, print them) for(uint16_t area = 0; area < numberOfAreas; area++) { cout << "Area " << area+1 << endl; streamLoader.setFileOffset(fileOffsetForArea[area] + baseOffset); load16bitArea(streamLoader); cout << endl; } delete[] fileOffsetForArea; return true; } <|endoftext|>
<commit_before>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2010 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <oxt/system_calls.hpp> #include <oxt/backtrace.hpp> #include <oxt/thread.hpp> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include "../AgentBase.h" #include "../AccountsDatabase.h" #include "../Account.h" #include "../ServerInstanceDir.h" #include "LoggingServer.h" #include "../Exceptions.h" #include "../Utils.h" #include "../Utils/IOUtils.h" #include "../Utils/Base64.h" #include "../Utils/VariantMap.h" using namespace oxt; using namespace Passenger; static struct ev_loop *eventLoop; static struct ev_loop * createEventLoop() { struct ev_loop *loop; // libev doesn't like choosing epoll and kqueue because the author thinks they're broken, // so let's try to force it. loop = ev_default_loop(EVBACKEND_EPOLL); if (loop == NULL) { loop = ev_default_loop(EVBACKEND_KQUEUE); } if (loop == NULL) { loop = ev_default_loop(0); } if (loop == NULL) { throw RuntimeException("Cannot create an event loop"); } else { return loop; } } static void lowerPrivilege(const string &username, const struct passwd *user, const struct group *group) { int e; if (initgroups(username.c_str(), group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to set supplementary groups for " << "PassengerLoggingAgent: " << strerror(e) << " (" << e << ")"); } if (setgid(group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set group ID to " << group->gr_gid << ": " << strerror(e) << " (" << e << ")"); } if (setuid(user->pw_uid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set user ID: " << strerror(e) << " (" << e << ")"); } } void feedbackFdBecameReadable(ev::io &watcher, int revents) { /* This event indicates that the watchdog has been killed. * In this case we'll kill all descendant * processes and exit. There's no point in keeping this agent * running because we can't detect when the web server exits, * and because this agent doesn't own the server instance * directory. As soon as passenger-status is run, the server * instance directory will be cleaned up, making this agent's * services inaccessible. */ syscalls::killpg(getpgrp(), SIGKILL); _exit(2); // In case killpg() fails. } int main(int argc, char *argv[]) { VariantMap options = initializeAgent(argc, argv, "PassengerLoggingAgent"); string socketAddress = options.get("logging_agent_address"); string loggingDir = options.get("analytics_log_dir"); string username = options.get("analytics_log_user"); string groupname = options.get("analytics_log_group"); string permissions = options.get("analytics_log_permissions"); string password = options.get("logging_agent_password"); string unionStationServiceAddress = options.get("union_station_service_address", false, DEFAULT_UNION_STATION_SERVICE_ADDRESS); int unionStationServicePort = options.getInt("union_station_service_port", false, DEFAULT_UNION_STATION_SERVICE_PORT); string unionStationServiceCert = options.get("union_station_service_cert", false); curl_global_init(CURL_GLOBAL_ALL); try { /********** Now begins the real initialization **********/ /* Create all the necessary objects and sockets... */ AccountsDatabasePtr accountsDatabase; FileDescriptor serverSocketFd; struct passwd *user; struct group *group; int ret; eventLoop = createEventLoop(); accountsDatabase = ptr(new AccountsDatabase()); serverSocketFd = createServer(socketAddress.c_str()); if (getSocketAddressType(socketAddress) == SAT_UNIX) { do { ret = chmod(parseUnixSocketAddress(socketAddress).c_str(), S_ISVTX | S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } while (ret == -1 && errno == EINTR); } /* Sanity check user accounts. */ user = getpwnam(username.c_str()); if (user == NULL) { throw NonExistentUserException(string("The configuration option ") + "'PassengerAnalyticsLogUser' (Apache) or " + "'passenger_analytics_log_user' (Nginx) was set to '" + username + "', but this user doesn't exist. Please fix " + "the configuration option."); } if (groupname.empty()) { group = getgrgid(user->pw_gid); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) wasn't set, " + "so PassengerLoggingAgent tried to use the default group " + "for user '" + username + "' - which is GID #" + toString(user->pw_gid) + " - as the group for the analytics " + "log dir, but this GID doesn't exist. " + "You can solve this problem by explicitly " + "setting PassengerAnalyticsLogGroup (Apache) or " + "passenger_analytics_log_group (Nginx) to a group that " + "does exist. In any case, it looks like your system's user " + "database is broken; Phusion Passenger can work fine even " + "with this broken user database, but you should still fix it."); } else { groupname = group->gr_name; } } else { group = getgrnam(groupname.c_str()); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) was set to '" + groupname + "', but this group doesn't exist. Please fix " + "the configuration option."); } } /* Create the logging directory if necessary. */ if (getFileType(loggingDir) == FT_NONEXISTANT) { if (geteuid() == 0) { makeDirTree(loggingDir, permissions, user->pw_uid, group->gr_gid); } else { makeDirTree(loggingDir, permissions); } } /* Now's a good time to lower the privilege. */ if (geteuid() == 0) { lowerPrivilege(username, user, group); } /* Now setup the actual logging server. */ accountsDatabase->add("logging", Base64::decode(password), false); LoggingServer server(eventLoop, serverSocketFd, accountsDatabase, loggingDir, "u=rwx,g=rx,o=rx", GROUP_NOT_GIVEN, unionStationServiceAddress, unionStationServicePort, unionStationServiceCert); if (feedbackFdAvailable()) { MessageChannel feedbackChannel(FEEDBACK_FD); ev::io feedbackFdWatcher(eventLoop); feedbackFdWatcher.set<&feedbackFdBecameReadable>(); feedbackFdWatcher.start(FEEDBACK_FD, ev::READ); feedbackChannel.write("initialized", NULL); } /********** Initialized! Enter main loop... **********/ ev_loop(eventLoop, 0); return 0; } catch (const tracable_exception &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); return 1; } } <commit_msg>Make some more LoggingAgent options optional.<commit_after>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2010 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <oxt/system_calls.hpp> #include <oxt/backtrace.hpp> #include <oxt/thread.hpp> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include "../AgentBase.h" #include "../AccountsDatabase.h" #include "../Account.h" #include "../ServerInstanceDir.h" #include "LoggingServer.h" #include "../Exceptions.h" #include "../Utils.h" #include "../Utils/IOUtils.h" #include "../Utils/Base64.h" #include "../Utils/VariantMap.h" using namespace oxt; using namespace Passenger; static struct ev_loop *eventLoop; static struct ev_loop * createEventLoop() { struct ev_loop *loop; // libev doesn't like choosing epoll and kqueue because the author thinks they're broken, // so let's try to force it. loop = ev_default_loop(EVBACKEND_EPOLL); if (loop == NULL) { loop = ev_default_loop(EVBACKEND_KQUEUE); } if (loop == NULL) { loop = ev_default_loop(0); } if (loop == NULL) { throw RuntimeException("Cannot create an event loop"); } else { return loop; } } static void lowerPrivilege(const string &username, const struct passwd *user, const struct group *group) { int e; if (initgroups(username.c_str(), group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to set supplementary groups for " << "PassengerLoggingAgent: " << strerror(e) << " (" << e << ")"); } if (setgid(group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set group ID to " << group->gr_gid << ": " << strerror(e) << " (" << e << ")"); } if (setuid(user->pw_uid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set user ID: " << strerror(e) << " (" << e << ")"); } } void feedbackFdBecameReadable(ev::io &watcher, int revents) { /* This event indicates that the watchdog has been killed. * In this case we'll kill all descendant * processes and exit. There's no point in keeping this agent * running because we can't detect when the web server exits, * and because this agent doesn't own the server instance * directory. As soon as passenger-status is run, the server * instance directory will be cleaned up, making this agent's * services inaccessible. */ syscalls::killpg(getpgrp(), SIGKILL); _exit(2); // In case killpg() fails. } static string myself() { struct passwd *entry = getpwuid(geteuid()); if (entry != NULL) { return entry->pw_name; } else { throw NonExistentUserException(string("The current user, UID ") + toString(geteuid()) + ", doesn't have a corresponding " + "entry in the system's user database. Please fix your " + "system's user database first."); } } int main(int argc, char *argv[]) { VariantMap options = initializeAgent(argc, argv, "PassengerLoggingAgent"); string socketAddress = options.get("logging_agent_address"); string loggingDir = options.get("analytics_log_dir"); string password = options.get("logging_agent_password"); string username = options.get("analytics_log_user", false, myself()); string groupname = options.get("analytics_log_group", false); string permissions = options.get("analytics_log_permissions", false, DEFAULT_ANALYTICS_LOG_PERMISSIONS); string unionStationServiceAddress = options.get("union_station_service_address", false, DEFAULT_UNION_STATION_SERVICE_ADDRESS); int unionStationServicePort = options.getInt("union_station_service_port", false, DEFAULT_UNION_STATION_SERVICE_PORT); string unionStationServiceCert = options.get("union_station_service_cert", false); curl_global_init(CURL_GLOBAL_ALL); try { /********** Now begins the real initialization **********/ /* Create all the necessary objects and sockets... */ AccountsDatabasePtr accountsDatabase; FileDescriptor serverSocketFd; struct passwd *user; struct group *group; int ret; eventLoop = createEventLoop(); accountsDatabase = ptr(new AccountsDatabase()); serverSocketFd = createServer(socketAddress.c_str()); if (getSocketAddressType(socketAddress) == SAT_UNIX) { do { ret = chmod(parseUnixSocketAddress(socketAddress).c_str(), S_ISVTX | S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } while (ret == -1 && errno == EINTR); } /* Sanity check user accounts. */ user = getpwnam(username.c_str()); if (user == NULL) { throw NonExistentUserException(string("The configuration option ") + "'PassengerAnalyticsLogUser' (Apache) or " + "'passenger_analytics_log_user' (Nginx) was set to '" + username + "', but this user doesn't exist. Please fix " + "the configuration option."); } if (groupname.empty()) { group = getgrgid(user->pw_gid); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) wasn't set, " + "so PassengerLoggingAgent tried to use the default group " + "for user '" + username + "' - which is GID #" + toString(user->pw_gid) + " - as the group for the analytics " + "log dir, but this GID doesn't exist. " + "You can solve this problem by explicitly " + "setting PassengerAnalyticsLogGroup (Apache) or " + "passenger_analytics_log_group (Nginx) to a group that " + "does exist. In any case, it looks like your system's user " + "database is broken; Phusion Passenger can work fine even " + "with this broken user database, but you should still fix it."); } else { groupname = group->gr_name; } } else { group = getgrnam(groupname.c_str()); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) was set to '" + groupname + "', but this group doesn't exist. Please fix " + "the configuration option."); } } /* Create the logging directory if necessary. */ if (getFileType(loggingDir) == FT_NONEXISTANT) { if (geteuid() == 0) { makeDirTree(loggingDir, permissions, user->pw_uid, group->gr_gid); } else { makeDirTree(loggingDir, permissions); } } /* Now's a good time to lower the privilege. */ if (geteuid() == 0) { lowerPrivilege(username, user, group); } /* Now setup the actual logging server. */ accountsDatabase->add("logging", Base64::decode(password), false); LoggingServer server(eventLoop, serverSocketFd, accountsDatabase, loggingDir, "u=rwx,g=rx,o=rx", GROUP_NOT_GIVEN, unionStationServiceAddress, unionStationServicePort, unionStationServiceCert); if (feedbackFdAvailable()) { MessageChannel feedbackChannel(FEEDBACK_FD); ev::io feedbackFdWatcher(eventLoop); feedbackFdWatcher.set<&feedbackFdBecameReadable>(); feedbackFdWatcher.start(FEEDBACK_FD, ev::READ); feedbackChannel.write("initialized", NULL); } /********** Initialized! Enter main loop... **********/ ev_loop(eventLoop, 0); return 0; } catch (const tracable_exception &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); return 1; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleDrawDocumentView.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: af $ $Date: 2002-04-18 17:54:21 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_DRAW_DOCUMENT_VIEW_HXX #include "AccessibleDrawDocumentView.hxx" #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_ #include <com/sun/star/drawing/XDrawView.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_ #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_ #include <com/sun/star/document/XEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_H_ #include <rtl/ustring.h> #endif #ifndef _SFXFRAME_HXX #include<sfx2/viewfrm.hxx> #endif #include <svx/AccessibleShape.hxx> #include <svx/svdobj.hxx> #include <svx/svdmodel.hxx> #include <svx/unoapi.hxx> #include <toolkit/helper/vclunohelper.hxx> #include "sdwindow.hxx" #include <vcl/svapp.hxx> #ifndef _SD_VIEWSHEL_HXX #include "viewshel.hxx" #endif #ifndef _SD_SDVIEW_HXX #include "sdview.hxx" #endif #include <memory> using namespace ::rtl; using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; class SfxViewFrame; namespace accessibility { //===== internal ============================================================ AccessibleDrawDocumentView::AccessibleDrawDocumentView ( SdWindow* pSdWindow, SdViewShell* pViewShell, const uno::Reference<frame::XController>& rxController, const uno::Reference<XAccessible>& rxParent) : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent), mpChildrenManager (NULL) { } AccessibleDrawDocumentView::~AccessibleDrawDocumentView (void) { OSL_TRACE ("~AccessibleDrawDocumentView"); // Unregister from the various event broadcasters. if (mpChildrenManager != NULL) delete mpChildrenManager; } void AccessibleDrawDocumentView::Init (void) { AccessibleDocumentViewBase::Init (); // Determine the list of shapes on the current page. uno::Reference<drawing::XShapes> xShapeList; uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) xShapeList = uno::Reference<drawing::XShapes> ( xView->getCurrentPage(), uno::UNO_QUERY); // Create the children manager. mpChildrenManager = new ChildrenManager(this, xShapeList, maShapeTreeInfo, *this); // Here is missing the code to handle a failed creation of the children manager. mpChildrenManager->AddAccessibleShape (UpdateDrawPageShape()); mpChildrenManager->Update (); } void AccessibleDrawDocumentView::ViewForwarderChanged (ChangeType aChangeType, const IAccessibleViewForwarder* pViewForwarder) { AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder); if (mpChildrenManager != NULL) mpChildrenManager->ViewForwarderChanged (aChangeType, pViewForwarder); } /** The page shape is created on every call at the moment (provided that every thing goes well). */ AccessiblePageShape* AccessibleDrawDocumentView::UpdateDrawPageShape (void) { AccessiblePageShape* pShape = NULL; // Create a shape that represents the actual draw page. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) { uno::Reference<beans::XPropertySet> xSet ( uno::Reference<beans::XPropertySet> (xView->getCurrentPage(), uno::UNO_QUERY)); if (xSet.is()) { // Create a rectangle shape that will represent the draw page. uno::Reference<lang::XMultiServiceFactory> xFactory (mxModel, uno::UNO_QUERY); uno::Reference<drawing::XShape> xRectangle; if (xFactory.is()) xRectangle = uno::Reference<drawing::XShape>(xFactory->createInstance ( OUString (RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.RectangleShape"))), uno::UNO_QUERY); // Set the shape's size and position. if (xRectangle.is()) { uno::Any aValue; awt::Point aPosition; awt::Size aSize; // Set size and position of the shape to those of the draw // page. aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft"))); aValue >>= aPosition.X; aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop"))); aValue >>= aPosition.Y; xRectangle->setPosition (aPosition); aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("Width"))); aValue >>= aSize.Width; aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("Height"))); aValue >>= aSize.Height; xRectangle->setSize (aSize); // Create the accessible object for the shape and set its // name and description to something more meaningfull than // "Rectangle..." pShape = new AccessiblePageShape ( xView->getCurrentPage(), this, maShapeTreeInfo); mxPageShape = pShape; } } } return pShape; } //===== XAccessibleContext ================================================== sal_Int32 SAL_CALL AccessibleDrawDocumentView::getAccessibleChildCount (void) throw (uno::RuntimeException) { long mpChildCount = 0; // Forward request to children manager. if (mpChildrenManager != NULL) mpChildCount += mpChildrenManager->GetChildCount (); return mpChildCount; } uno::Reference<XAccessible> SAL_CALL AccessibleDrawDocumentView::getAccessibleChild (long nIndex) throw (::com::sun::star::uno::RuntimeException) { if (mpChildrenManager != NULL) { // Forward request to children manager. return mpChildrenManager->GetChild (nIndex); } else throw lang::IndexOutOfBoundsException ( ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex, static_cast<uno::XWeak*>(this)); } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessibleDrawDocumentView::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView")); } //===== XEventListener ====================================================== void SAL_CALL AccessibleDrawDocumentView::disposing (const lang::EventObject& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::disposing (rEventObject); if (rEventObject.Source == mxModel) { ::osl::Guard< ::osl::Mutex> aGuard (::osl::Mutex::getGlobalMutex()); // maShapeTreeInfo has been modified in base class. mpChildrenManager->SetInfo (maShapeTreeInfo); } } //===== XFrameActionListener ================================================ void SAL_CALL AccessibleDrawDocumentView::frameAction (const frame::FrameActionEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::frameAction (rEventObject); if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED) { mpChildrenManager->ClearAccessibleShapeList (); mpChildrenManager->SetInfo (maShapeTreeInfo); mpChildrenManager->ViewForwarderChanged ( IAccessibleViewForwarderListener::TRANSFORMATION, &maViewForwarder); // To properly inform the registered listeners of this we just have // to call the children manager and update its shape list. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) mpChildrenManager->SetShapeList ( uno::Reference<drawing::XShapes> ( xView->getCurrentPage(), uno::UNO_QUERY)); mpChildrenManager->AddAccessibleShape (UpdateDrawPageShape ()); mpChildrenManager->Update (false); OSL_TRACE ("done handling frame event for AccessibleDrawDocumentView"); } } //===== XPropertyChangeListener ============================================= void SAL_CALL AccessibleDrawDocumentView::propertyChange (const beans::PropertyChangeEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::propertyChange (rEventObject); OSL_TRACE ("AccessibleDrawDocumentView::propertyChange"); if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage"))) { OSL_TRACE (" current page changed"); // The current page changed. Update the children manager accordingly. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is() && mpChildrenManager!=NULL) { // Inform the children manager to forget all children and give // him the new ones. mpChildrenManager->ClearAccessibleShapeList (); uno::Reference<drawing::XShapes> xShapeList ( xView->getCurrentPage(), uno::UNO_QUERY); mpChildrenManager->SetShapeList (xShapeList); mpChildrenManager->AddAccessibleShape (UpdateDrawPageShape ()); mpChildrenManager->Update (false); } else OSL_TRACE ("View invalid"); } else if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea"))) { OSL_TRACE (" visible area changed"); mpChildrenManager->ViewForwarderChanged ( IAccessibleViewForwarderListener::VISIBLE_AREA, &maViewForwarder); } else { OSL_TRACE (" unhandled"); } OSL_TRACE (" done"); } /// Create a name for this view. ::rtl::OUString AccessibleDrawDocumentView::CreateAccessibleName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView")); } /** Create a description for this view. Use the model's description or URL if a description is not available. */ ::rtl::OUString AccessibleDrawDocumentView::CreateAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { rtl::OUString sDescription; uno::Reference<lang::XServiceInfo> xInfo (mxController, uno::UNO_QUERY); if (xInfo.is()) { OUString sFirstService = xInfo->getSupportedServiceNames()[0]; if (sFirstService == OUString ( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocumentDrawView"))) { sDescription = OUString (RTL_CONSTASCII_USTRINGPARAM("Draw Document")); } else sDescription = sFirstService; } else sDescription = OUString ( RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document")); return sDescription; } } // end of namespace accessibility <commit_msg>#95585# Added some guards against a failed construction of the children manager.<commit_after>/************************************************************************* * * $RCSfile: AccessibleDrawDocumentView.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: af $ $Date: 2002-04-22 08:38:30 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef _SD_ACCESSIBILITY_ACCESSIBLE_DRAW_DOCUMENT_VIEW_HXX #include "AccessibleDrawDocumentView.hxx" #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_ #include <com/sun/star/drawing/XDrawView.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_ #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_ #include <com/sun/star/document/XEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _RTL_USTRING_H_ #include <rtl/ustring.h> #endif #ifndef _SFXFRAME_HXX #include<sfx2/viewfrm.hxx> #endif #include <svx/AccessibleShape.hxx> #include <svx/svdobj.hxx> #include <svx/svdmodel.hxx> #include <svx/unoapi.hxx> #include <toolkit/helper/vclunohelper.hxx> #include "sdwindow.hxx" #include <vcl/svapp.hxx> #ifndef _SD_VIEWSHEL_HXX #include "viewshel.hxx" #endif #ifndef _SD_SDVIEW_HXX #include "sdview.hxx" #endif #include <memory> using namespace ::rtl; using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; class SfxViewFrame; namespace accessibility { //===== internal ============================================================ AccessibleDrawDocumentView::AccessibleDrawDocumentView ( SdWindow* pSdWindow, SdViewShell* pViewShell, const uno::Reference<frame::XController>& rxController, const uno::Reference<XAccessible>& rxParent) : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent), mpChildrenManager (NULL) { } AccessibleDrawDocumentView::~AccessibleDrawDocumentView (void) { OSL_TRACE ("~AccessibleDrawDocumentView"); // Unregister from the various event broadcasters. if (mpChildrenManager != NULL) delete mpChildrenManager; } void AccessibleDrawDocumentView::Init (void) { AccessibleDocumentViewBase::Init (); // Determine the list of shapes on the current page. uno::Reference<drawing::XShapes> xShapeList; uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) xShapeList = uno::Reference<drawing::XShapes> ( xView->getCurrentPage(), uno::UNO_QUERY); // Create the children manager. mpChildrenManager = new ChildrenManager(this, xShapeList, maShapeTreeInfo, *this); if (mpChildrenManager != NULL) { mpChildrenManager->AddAccessibleShape (CreateDrawPageShape()); mpChildrenManager->Update (); } } void AccessibleDrawDocumentView::ViewForwarderChanged (ChangeType aChangeType, const IAccessibleViewForwarder* pViewForwarder) { AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder); if (mpChildrenManager != NULL) mpChildrenManager->ViewForwarderChanged (aChangeType, pViewForwarder); } /** The page shape is created on every call at the moment (provided that every thing goes well). */ AccessiblePageShape* AccessibleDrawDocumentView::CreateDrawPageShape (void) { AccessiblePageShape* pShape = NULL; // Create a shape that represents the actual draw page. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) { uno::Reference<beans::XPropertySet> xSet ( uno::Reference<beans::XPropertySet> (xView->getCurrentPage(), uno::UNO_QUERY)); if (xSet.is()) { // Create a rectangle shape that will represent the draw page. uno::Reference<lang::XMultiServiceFactory> xFactory (mxModel, uno::UNO_QUERY); uno::Reference<drawing::XShape> xRectangle; if (xFactory.is()) xRectangle = uno::Reference<drawing::XShape>(xFactory->createInstance ( OUString (RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.RectangleShape"))), uno::UNO_QUERY); // Set the shape's size and position. if (xRectangle.is()) { uno::Any aValue; awt::Point aPosition; awt::Size aSize; // Set size and position of the shape to those of the draw // page. aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft"))); aValue >>= aPosition.X; aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop"))); aValue >>= aPosition.Y; xRectangle->setPosition (aPosition); aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("Width"))); aValue >>= aSize.Width; aValue = xSet->getPropertyValue ( OUString (RTL_CONSTASCII_USTRINGPARAM("Height"))); aValue >>= aSize.Height; xRectangle->setSize (aSize); // Create the accessible object for the shape and set its // name and description to something more meaningfull than // "Rectangle..." pShape = new AccessiblePageShape ( xView->getCurrentPage(), this, maShapeTreeInfo); } } } return pShape; } //===== XAccessibleContext ================================================== sal_Int32 SAL_CALL AccessibleDrawDocumentView::getAccessibleChildCount (void) throw (uno::RuntimeException) { long mpChildCount = 0; // Forward request to children manager. if (mpChildrenManager != NULL) mpChildCount += mpChildrenManager->GetChildCount (); return mpChildCount; } uno::Reference<XAccessible> SAL_CALL AccessibleDrawDocumentView::getAccessibleChild (long nIndex) throw (::com::sun::star::uno::RuntimeException) { if (mpChildrenManager != NULL) { // Forward request to children manager. return mpChildrenManager->GetChild (nIndex); } else throw lang::IndexOutOfBoundsException ( ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex, static_cast<uno::XWeak*>(this)); } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessibleDrawDocumentView::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView")); } //===== XEventListener ====================================================== void SAL_CALL AccessibleDrawDocumentView::disposing (const lang::EventObject& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::disposing (rEventObject); if (rEventObject.Source == mxModel) { ::osl::Guard< ::osl::Mutex> aGuard (::osl::Mutex::getGlobalMutex()); // maShapeTreeInfo has been modified in base class. if (mpChildrenManager != NULL) mpChildrenManager->SetInfo (maShapeTreeInfo); } } //===== XFrameActionListener ================================================ void SAL_CALL AccessibleDrawDocumentView::frameAction (const frame::FrameActionEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::frameAction (rEventObject); if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED) { if (mpChildrenManager != NULL) { mpChildrenManager->ClearAccessibleShapeList (); mpChildrenManager->SetInfo (maShapeTreeInfo); mpChildrenManager->ViewForwarderChanged ( IAccessibleViewForwarderListener::TRANSFORMATION, &maViewForwarder); // To properly inform the registered listeners of this we just have // to call the children manager and update its shape list. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is()) mpChildrenManager->SetShapeList ( uno::Reference<drawing::XShapes> ( xView->getCurrentPage(), uno::UNO_QUERY)); mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ()); mpChildrenManager->Update (false); OSL_TRACE ("done handling frame event for AccessibleDrawDocumentView"); } } } //===== XPropertyChangeListener ============================================= void SAL_CALL AccessibleDrawDocumentView::propertyChange (const beans::PropertyChangeEvent& rEventObject) throw (::com::sun::star::uno::RuntimeException) { AccessibleDocumentViewBase::propertyChange (rEventObject); OSL_TRACE ("AccessibleDrawDocumentView::propertyChange"); if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage"))) { OSL_TRACE (" current page changed"); // The current page changed. Update the children manager accordingly. uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY); if (xView.is() && mpChildrenManager!=NULL) { // Inform the children manager to forget all children and give // him the new ones. mpChildrenManager->ClearAccessibleShapeList (); uno::Reference<drawing::XShapes> xShapeList ( xView->getCurrentPage(), uno::UNO_QUERY); mpChildrenManager->SetShapeList (xShapeList); mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ()); mpChildrenManager->Update (false); } else OSL_TRACE ("View invalid"); } else if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea"))) { OSL_TRACE (" visible area changed"); if (mpChildreManager != NULL) mpChildrenManager->ViewForwarderChanged ( IAccessibleViewForwarderListener::VISIBLE_AREA, &maViewForwarder); } else { OSL_TRACE (" unhandled"); } OSL_TRACE (" done"); } /// Create a name for this view. ::rtl::OUString AccessibleDrawDocumentView::CreateAccessibleName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView")); } /** Create a description for this view. Use the model's description or URL if a description is not available. */ ::rtl::OUString AccessibleDrawDocumentView::CreateAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { rtl::OUString sDescription; uno::Reference<lang::XServiceInfo> xInfo (mxController, uno::UNO_QUERY); if (xInfo.is()) { OUString sFirstService = xInfo->getSupportedServiceNames()[0]; if (sFirstService == OUString ( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocumentDrawView"))) { sDescription = OUString (RTL_CONSTASCII_USTRINGPARAM("Draw Document")); } else sDescription = sFirstService; } else sDescription = OUString ( RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document")); return sDescription; } } // end of namespace accessibility <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <cassert> #include "boost/format.hpp" #include "maya/MFnMeshData.h" #include "maya/MFnMesh.h" #include "maya/MPointArray.h" #include "maya/MFloatPointArray.h" #include "maya/MFloatVectorArray.h" #include "maya/MFloatArray.h" #include "maya/MIntArray.h" #include "IECore/MeshPrimitive.h" #include "IECore/PrimitiveVariable.h" #include "IECore/MessageHandler.h" #include "IECoreMaya/Convert.h" #include "IECoreMaya/ToMayaMeshConverter.h" using namespace IECoreMaya; ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDataDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMeshData ); ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMesh ); ToMayaMeshConverter::ToMayaMeshConverter( IECore::ConstObjectPtr object ) : ToMayaObjectConverter( "ToMayaMeshConverter", "Converts IECore::MeshPrimitive objects to a Maya object.", object) { } void ToMayaMeshConverter::addUVSet( MFnMesh &fnMesh, const MIntArray &polygonCounts, IECore::ConstMeshPrimitivePtr mesh, const std::string &sPrimVarName, const std::string &tPrimVarName, MString *uvSetName ) const { IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( sPrimVarName ); bool haveS = sIt != mesh->variables.end(); IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( tPrimVarName ); bool haveT = tIt != mesh->variables.end(); if ( haveS && haveT ) { if ( sIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying ) { IECore::msg( IECore::Msg::Warning,"ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % sPrimVarName ); return; } if ( tIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % tPrimVarName); return; } if ( !sIt->second.data ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % sPrimVarName ); } if ( !tIt->second.data ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % tPrimVarName ); } /// \todo Employ some M*Array converters to simplify this int numUVs = mesh->variableSize( IECore::PrimitiveVariable::FaceVarying ); MFloatArray uArray; IECore::ConstFloatVectorDataPtr u = IECore::runTimeCast<const IECore::FloatVectorData>(sIt->second.data); if ( !u ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % sPrimVarName % sIt->second.data->typeName() ); return; } assert( (int)u->readable().size() == numUVs ); uArray.setLength( numUVs ); MFloatArray vArray; IECore::ConstFloatVectorDataPtr v = IECore::runTimeCast<const IECore::FloatVectorData>(tIt->second.data); if ( !v ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % tPrimVarName % tIt->second.data->typeName() ); return; } assert( (int)v->readable().size() == numUVs ); vArray.setLength( numUVs ); MIntArray uvIds; uvIds.setLength( numUVs ); for ( int i = 0; i < numUVs; i++) { uArray[i] = u->readable()[i]; vArray[i] = v->readable()[i]; uvIds[i] = i; } if ( uvSetName ) { fnMesh.createUVSetWithName( *uvSetName ); } MStatus s = fnMesh.setUVs( uArray, vArray, uvSetName ); if ( !s ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to set UVs." ); return; } fnMesh.assignUVs( polygonCounts, uvIds, uvSetName ); if ( !s ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to assign UVs." ); return; } } else if ( haveS ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % sPrimVarName % tPrimVarName ); } else if ( haveT ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % tPrimVarName % sPrimVarName ); } else { assert( !uvSetName ); } } bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const { MStatus s; IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from ); assert( mesh ); if ( !mesh->arePrimitiveVariablesValid() ) { return false; } MFloatPointArray vertexArray; MIntArray polygonCounts; MIntArray polygonConnects; MFnMesh fnMesh; int numVertices = 0; IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P"); if ( it != mesh->variables.end() ) { /// \todo Employ some M*Array converters to simplify this IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data); if (p) { numVertices = p->readable().size(); vertexArray.setLength( numVertices ); for (int i = 0; i < numVertices; i++) { vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] ); } } else { IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data); if (p) { numVertices = p->readable().size(); vertexArray.setLength( numVertices ); for (int i = 0; i < numVertices; i++) { vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] ); } } else { // "P" is not convertible to an array of "points" return false; } } } IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace(); assert( verticesPerFace ); int numPolygons = verticesPerFace->readable().size(); polygonCounts.setLength( numPolygons ); for (int i = 0; i < numPolygons; i++) { polygonCounts[i] = verticesPerFace->readable()[i]; } IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds(); assert( vertexIds ); int numPolygonConnects = vertexIds->readable().size(); polygonConnects.setLength( numPolygonConnects ); for (int i = 0; i < numPolygonConnects; i++) { polygonConnects[i] = vertexIds->readable()[i]; } fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s ); if (!s) { return false; } it = mesh->variables.find("N"); if ( it != mesh->variables.end() ) { if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying ) { /// \todo Employ some M*Array converters to simplify this MFloatVectorArray vertexNormalsArray; IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data); if (n) { int numVertexNormals = n->readable().size(); vertexNormalsArray.setLength( numVertexNormals ); for (int i = 0; i < numVertexNormals; i++) { vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3f>( n->readable()[i] ); } fnMesh.setNormals( vertexNormalsArray ); } else { IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data); if (n) { int numVertexNormals = n->readable().size(); vertexNormalsArray.setLength( numVertexNormals ); for (int i = 0; i < numVertexNormals; i++) { vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3d>( n->readable()[i] ); } fnMesh.setNormals( vertexNormalsArray ); } else { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"N\" has unsupported type \"%s\"." ) % it->second.data->typeName() ); } } } else { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "PrimitiveVariable \"N\" has unsupported interpolation (expected FaceVarying)." ); } } /// Add default UV set addUVSet( fnMesh, polygonCounts, mesh, "s", "t" ); /// Add other UV sets std::set< std::string > uvSets; for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it ) { const std::string &sName = it->first; size_t suffixOffset = sName.rfind( "_s" ); if ( ( suffixOffset != std::string::npos) && ( suffixOffset == sName.length() - 2 ) ) { std::string uvSetNameStr = sName.substr( 0, suffixOffset ); if ( uvSetNameStr.size() ) { MString uvSetName = uvSetNameStr.c_str(); std::string tName = uvSetNameStr + "_t"; addUVSet( fnMesh, polygonCounts, mesh, sName, tName, &uvSetName ); uvSets.insert( uvSetNameStr ); } } } /// We do the search again, but looking for primvars ending "_t", so we can catch cases where either "UVSETNAME_s" or "UVSETNAME_t" is present, but not both, taking care /// not to attempt adding any duplicate sets for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it ) { const std::string &tName = it->first; size_t suffixOffset = tName.rfind( "_t" ); if ( ( suffixOffset != std::string::npos) && ( suffixOffset == tName.length() - 2 ) ) { std::string uvSetNameStr = tName.substr( 0, suffixOffset ); if ( uvSetNameStr.size() && uvSets.find( uvSetNameStr ) == uvSets.end() ) { MString uvSetName = uvSetNameStr.c_str(); std::string sName = uvSetNameStr + "_s"; addUVSet( fnMesh, polygonCounts, mesh, sName, tName, &uvSetName ); uvSets.insert( uvSetNameStr ); } } } /// \todo Other primvars, e.g. vertex color ("Cs") return true; } <commit_msg>Added todo<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include <cassert> #include "boost/format.hpp" #include "maya/MFnMeshData.h" #include "maya/MFnMesh.h" #include "maya/MPointArray.h" #include "maya/MFloatPointArray.h" #include "maya/MFloatVectorArray.h" #include "maya/MFloatArray.h" #include "maya/MIntArray.h" #include "IECore/MeshPrimitive.h" #include "IECore/PrimitiveVariable.h" #include "IECore/MessageHandler.h" #include "IECoreMaya/Convert.h" #include "IECoreMaya/ToMayaMeshConverter.h" using namespace IECoreMaya; ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDataDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMeshData ); ToMayaMeshConverter::Description ToMayaMeshConverter::g_meshDescription( IECore::MeshPrimitive::staticTypeId(), MFn::kMesh ); ToMayaMeshConverter::ToMayaMeshConverter( IECore::ConstObjectPtr object ) : ToMayaObjectConverter( "ToMayaMeshConverter", "Converts IECore::MeshPrimitive objects to a Maya object.", object) { } void ToMayaMeshConverter::addUVSet( MFnMesh &fnMesh, const MIntArray &polygonCounts, IECore::ConstMeshPrimitivePtr mesh, const std::string &sPrimVarName, const std::string &tPrimVarName, MString *uvSetName ) const { IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( sPrimVarName ); bool haveS = sIt != mesh->variables.end(); IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( tPrimVarName ); bool haveT = tIt != mesh->variables.end(); if ( haveS && haveT ) { if ( sIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying ) { IECore::msg( IECore::Msg::Warning,"ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % sPrimVarName ); return; } if ( tIt->second.interpolation != IECore::PrimitiveVariable::FaceVarying ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported interpolation (expected FaceVarying).") % tPrimVarName); return; } if ( !sIt->second.data ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % sPrimVarName ); } if ( !tIt->second.data ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has no data." ) % tPrimVarName ); } /// \todo Employ some M*Array converters to simplify this int numUVs = mesh->variableSize( IECore::PrimitiveVariable::FaceVarying ); MFloatArray uArray; IECore::ConstFloatVectorDataPtr u = IECore::runTimeCast<const IECore::FloatVectorData>(sIt->second.data); if ( !u ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % sPrimVarName % sIt->second.data->typeName() ); return; } assert( (int)u->readable().size() == numUVs ); uArray.setLength( numUVs ); MFloatArray vArray; IECore::ConstFloatVectorDataPtr v = IECore::runTimeCast<const IECore::FloatVectorData>(tIt->second.data); if ( !v ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"%s\" has unsupported type \"%s\"." ) % tPrimVarName % tIt->second.data->typeName() ); return; } assert( (int)v->readable().size() == numUVs ); vArray.setLength( numUVs ); /// \todo The FromMayaMeshConverter inverts the UVs - shouldn't we do the same here? MIntArray uvIds; uvIds.setLength( numUVs ); for ( int i = 0; i < numUVs; i++) { uArray[i] = u->readable()[i]; vArray[i] = v->readable()[i]; uvIds[i] = i; } if ( uvSetName ) { fnMesh.createUVSetWithName( *uvSetName ); } MStatus s = fnMesh.setUVs( uArray, vArray, uvSetName ); if ( !s ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to set UVs." ); return; } fnMesh.assignUVs( polygonCounts, uvIds, uvSetName ); if ( !s ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to assign UVs." ); return; } } else if ( haveS ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % sPrimVarName % tPrimVarName ); } else if ( haveT ) { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "Primitive variable \"%s\" found, but not \"%s\"." ) % tPrimVarName % sPrimVarName ); } else { assert( !uvSetName ); } } bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const { MStatus s; IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from ); assert( mesh ); if ( !mesh->arePrimitiveVariablesValid() ) { return false; } MFloatPointArray vertexArray; MIntArray polygonCounts; MIntArray polygonConnects; MFnMesh fnMesh; int numVertices = 0; IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P"); if ( it != mesh->variables.end() ) { /// \todo Employ some M*Array converters to simplify this IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data); if (p) { numVertices = p->readable().size(); vertexArray.setLength( numVertices ); for (int i = 0; i < numVertices; i++) { vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] ); } } else { IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data); if (p) { numVertices = p->readable().size(); vertexArray.setLength( numVertices ); for (int i = 0; i < numVertices; i++) { vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] ); } } else { // "P" is not convertible to an array of "points" return false; } } } IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace(); assert( verticesPerFace ); int numPolygons = verticesPerFace->readable().size(); polygonCounts.setLength( numPolygons ); for (int i = 0; i < numPolygons; i++) { polygonCounts[i] = verticesPerFace->readable()[i]; } IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds(); assert( vertexIds ); int numPolygonConnects = vertexIds->readable().size(); polygonConnects.setLength( numPolygonConnects ); for (int i = 0; i < numPolygonConnects; i++) { polygonConnects[i] = vertexIds->readable()[i]; } fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s ); if (!s) { return false; } it = mesh->variables.find("N"); if ( it != mesh->variables.end() ) { if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying ) { /// \todo Employ some M*Array converters to simplify this MFloatVectorArray vertexNormalsArray; IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data); if (n) { int numVertexNormals = n->readable().size(); vertexNormalsArray.setLength( numVertexNormals ); for (int i = 0; i < numVertexNormals; i++) { vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3f>( n->readable()[i] ); } fnMesh.setNormals( vertexNormalsArray ); } else { IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data); if (n) { int numVertexNormals = n->readable().size(); vertexNormalsArray.setLength( numVertexNormals ); for (int i = 0; i < numVertexNormals; i++) { vertexNormalsArray[i] = IECore::convert<MFloatVector, Imath::V3d>( n->readable()[i] ); } fnMesh.setNormals( vertexNormalsArray ); } else { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"N\" has unsupported type \"%s\"." ) % it->second.data->typeName() ); } } } else { IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "PrimitiveVariable \"N\" has unsupported interpolation (expected FaceVarying)." ); } } /// Add default UV set addUVSet( fnMesh, polygonCounts, mesh, "s", "t" ); /// Add other UV sets std::set< std::string > uvSets; for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it ) { const std::string &sName = it->first; size_t suffixOffset = sName.rfind( "_s" ); if ( ( suffixOffset != std::string::npos) && ( suffixOffset == sName.length() - 2 ) ) { std::string uvSetNameStr = sName.substr( 0, suffixOffset ); if ( uvSetNameStr.size() ) { MString uvSetName = uvSetNameStr.c_str(); std::string tName = uvSetNameStr + "_t"; addUVSet( fnMesh, polygonCounts, mesh, sName, tName, &uvSetName ); uvSets.insert( uvSetNameStr ); } } } /// We do the search again, but looking for primvars ending "_t", so we can catch cases where either "UVSETNAME_s" or "UVSETNAME_t" is present, but not both, taking care /// not to attempt adding any duplicate sets for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it ) { const std::string &tName = it->first; size_t suffixOffset = tName.rfind( "_t" ); if ( ( suffixOffset != std::string::npos) && ( suffixOffset == tName.length() - 2 ) ) { std::string uvSetNameStr = tName.substr( 0, suffixOffset ); if ( uvSetNameStr.size() && uvSets.find( uvSetNameStr ) == uvSets.end() ) { MString uvSetName = uvSetNameStr.c_str(); std::string sName = uvSetNameStr + "_s"; addUVSet( fnMesh, polygonCounts, mesh, sName, tName, &uvSetName ); uvSets.insert( uvSetNameStr ); } } } /// \todo Other primvars, e.g. vertex color ("Cs") return true; } <|endoftext|>
<commit_before>#include <algorithm> #include <cstddef> #include <optional> #include <string_view> #include <type_traits> template <std::size_t N> struct fixed_string { constexpr fixed_string(const char (&foo)[N + 1]) { std::copy_n(foo, N + 1, data); } constexpr fixed_string(std::string_view s) { static_assert(s.size() <= N); std::copy(s.begin(), s.end(), data); } constexpr std::string_view sv() const { return std::string_view(data); } auto operator<=>(const fixed_string&) const = default; char data[N + 1] = {}; }; template <std::size_t N> fixed_string(const char (&str)[N]) -> fixed_string<N - 1>; template <fixed_string Tag, typename T> struct tag_and_value { T value; }; template <typename... Members> struct meta_struct; template <typename... Members> meta_struct(Members...) -> meta_struct<Members...>; template <> struct meta_struct<> {}; struct no_conversion {}; template <typename... TagsAndValues> struct parms : TagsAndValues... { constexpr operator no_conversion() const { return no_conversion{}; } }; template <typename... TagsAndValues> parms(TagsAndValues...) -> parms<TagsAndValues...>; template <fixed_string Tag> struct arg_type { template <typename T> constexpr auto operator=(T t) const { return tag_and_value<Tag, T>{std::move(t)}; } }; template <typename T> struct default_init { constexpr default_init() = default; auto operator<=>(const default_init&) const = default; constexpr auto operator()() const { if constexpr (std::is_default_constructible_v<T>) { return T{}; } } }; template <typename T, typename Self, typename F> auto call_init(Self&, F& f) requires(requires { { f() } -> std::convertible_to<T>; }) { return f(); } template <typename T, typename Self, typename F> auto call_init(Self& self, F& f) requires(requires { { f(self) } -> std::convertible_to<T>; }) { return f(self); } template <typename T, typename Self, typename F> auto call_init(Self& self, F& f) requires(requires { { f() } -> std::same_as<void>; }) { static_assert(!std::is_same_v<decltype(f()), void>, "Required argument not specified"); } inline constexpr auto required = [] {}; template <fixed_string Tag, typename T, auto Init = default_init<T>(), meta_struct Attributes = {}> struct member { constexpr static auto tag() { return Tag; } constexpr static auto init() { return Init; } constexpr static auto attributes() { return Attributes; } using element_type = T; T value; template <typename Self, typename OtherT> constexpr member(Self&, tag_and_value<Tag, OtherT> tv) : value(std::move(tv.value)) {} template <typename Self> constexpr member(Self& self, no_conversion) : value(call_init<T>(self, Init)) {} template <typename Self> constexpr member(Self& self, tag_and_value<Tag, std::optional<std::remove_reference_t<T>>> tv_or) requires(!std::is_reference_v<T>) : value(tv_or.value.has_value() ? std::move(*tv_or.value) : call_init<T>(self, Init)) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, const member<Tag, OtherT, OtherInit, OtherAttributes>& other) : value(other.value) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, member<Tag, OtherT, OtherInit, OtherAttributes>&& other) : value(std::move(other.value)) {} template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( const member<Tag, OtherT, OtherInit, OtherAttributes>& other) { value = other.value; return *this; } template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( member<Tag, OtherT, OtherInit, OtherAttributes>&& other) { value = std::move(other.value); return *this; } constexpr member(member&&) = default; constexpr member(const member&) = default; constexpr member& operator=(member&&) = default; constexpr member& operator=(const member&) = default; auto operator<=>(const member&) const = default; }; template <typename... Members> struct meta_struct_impl : Members... { template <typename... Args> constexpr meta_struct_impl(parms<Args...> p) : Members(*this, std::move(p))... {} constexpr meta_struct_impl() : Members(*this, no_conversion{})... {} constexpr meta_struct_impl(meta_struct_impl&&) = default; constexpr meta_struct_impl(const meta_struct_impl&) = default; constexpr meta_struct_impl& operator=(meta_struct_impl&&) = default; constexpr meta_struct_impl& operator=(const meta_struct_impl&) = default; template <typename... OtherMembers> constexpr meta_struct_impl(meta_struct_impl<OtherMembers...>&& other) : Members(*this, std::move(other))... {}; template <typename... OtherMembers> constexpr meta_struct_impl(const meta_struct_impl<OtherMembers...>& other) : Members(*this, other)... {}; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( meta_struct_impl<OtherMembers...>&& other) { ((static_cast<Members&>(*this) = std::move(other)), ...); return *this; }; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( const meta_struct_impl<OtherMembers...>& other) { ((static_cast<Members&>(*this) = other), ...); return *this; }; constexpr operator no_conversion() const { return no_conversion{}; } auto operator<=>(const meta_struct_impl&) const = default; }; template <typename... Members> struct meta_struct : meta_struct_impl<Members...> { using super = meta_struct_impl<Members...>; template <typename... TagsAndValues> constexpr meta_struct(TagsAndValues... tags_and_values) : super(parms(std::move(tags_and_values)...)) {} constexpr meta_struct() = default; constexpr meta_struct(meta_struct&&) = default; constexpr meta_struct(const meta_struct&) = default; constexpr meta_struct& operator=(meta_struct&&) = default; constexpr meta_struct& operator=(const meta_struct&) = default; template <typename... OtherMembers> constexpr meta_struct(meta_struct<OtherMembers...>&& other) : super(std::move(other)) {} template <typename... OtherMembers> constexpr meta_struct(const meta_struct<OtherMembers...>& other) : super(other) {} template <typename... OtherMembers> constexpr meta_struct& operator=(meta_struct<OtherMembers...>&& other) { static_cast<super&>(*this) = std::move(other); return *this; } template <typename... OtherMembers> constexpr meta_struct& operator=(const meta_struct<OtherMembers...>& other) { static_cast<super&>(*this) = other; return *this; } auto operator<=>(const meta_struct&) const = default; }; template <fixed_string Tag> struct attr_type { template <typename T> constexpr auto operator=(T t) const { return member<Tag, T>(*this, tag_and_value<Tag, T>(std::move(t))); } }; template <fixed_string Tag> inline constexpr auto attr = attr_type<Tag>{}; template <fixed_string Tag> inline constexpr auto arg = attr_type<Tag>{}; template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, meta_struct_impl<MembersImpl...>& m) { return std::forward<F>(f)(static_cast<MembersImpl&>(m)...); } template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, const meta_struct_impl<MembersImpl...>& m) { return std::forward<F>(f)(static_cast<const MembersImpl&>(m)...); } template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, meta_struct_impl<MembersImpl...>&& m) { return std::forward<F>(f)(static_cast<MembersImpl&&>(m)...); } template <typename MetaStructImpl> struct apply_static_impl; template <typename... MembersImpl> struct apply_static_impl<meta_struct_impl<MembersImpl...>> { template <typename F> constexpr static decltype(auto) apply(F&& f) { return f(static_cast<MembersImpl*>(nullptr)...); } }; template <typename MetaStruct, typename F> constexpr auto meta_struct_apply(F&& f) { return apply_static_impl<typename MetaStruct::super>::apply( std::forward<F>(f)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(const member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>&& m) { return std::move(m.value); } template <fixed_string tag, typename MetaStruct> constexpr decltype(auto) get(MetaStruct&& s) { return get_impl<tag>(std::forward<MetaStruct>(s)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr member<tag, T, Init, Attributes> get_member_impl( const member<tag, T, Init, Attributes>& m); template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes(MetaStruct&& s) { return decltype(get_member_impl(s))::attributes(); } template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes() { return decltype(get_member_impl<Tag>(std::declval<MetaStruct&>()))::attributes(); } #include <iostream> #include <string> template <typename MetaStruct> void print(std::ostream& os, const MetaStruct& ms) { meta_struct_apply( [&](const auto&... m) { auto print_item = [&](auto& m) { std::cout << m.tag().sv() << ":" << m.value << "\n"; }; (print_item(m), ...); }, ms); }; using NameAndIdArgs = meta_struct< // member<"name", std::string_view>, // member<"id", const int&> // >; void print_name_id(NameAndIdArgs args) { std::cout << "Name is " << get<"name">(args) << " and id is " << get<"id">(args) << "\n"; } int main() { using Person = meta_struct< // member<"id", int, required>, // member<"name", std::string, required, {attr<"attribute"> = true}>, // member<"score", int, [](auto& self) { return get<"id">(self) + 1; }> // >; constexpr meta_struct<member<"attribute", bool, [] { return false; }>> attributes = get_attributes<"name", Person>(); if constexpr (get<"attribute">(attributes)) { std::cout << "Attribute was true"; } auto print = [](auto& t) { meta_struct_apply( [&](const auto&... m) { ((std::cout << m.tag().sv() << ":" << m.value << "\n"), ...); }, t); }; Person p{arg<"id"> = 2, arg<"name"> = "John"}; using NameAndId = meta_struct< // member<"name", std::string_view>, // member<"id", int> // >; print(p); std::cout << "\n"; NameAndId n = p; print(n); std::cout << "\n"; print_name_id(p); print_name_id(n); } <commit_msg>add has function for meta_struct<commit_after>#include <algorithm> #include <cstddef> #include <optional> #include <string_view> #include <type_traits> template <std::size_t N> struct fixed_string { constexpr fixed_string(const char (&foo)[N + 1]) { std::copy_n(foo, N + 1, data); } constexpr fixed_string(std::string_view s) { static_assert(s.size() <= N); std::copy(s.begin(), s.end(), data); } constexpr std::string_view sv() const { return std::string_view(data); } auto operator<=>(const fixed_string&) const = default; char data[N + 1] = {}; }; template <std::size_t N> fixed_string(const char (&str)[N]) -> fixed_string<N - 1>; template <fixed_string Tag, typename T> struct tag_and_value { T value; }; template <typename... Members> struct meta_struct; template <typename... Members> meta_struct(Members...) -> meta_struct<Members...>; template <> struct meta_struct<> {}; struct no_conversion {}; template <typename... TagsAndValues> struct parms : TagsAndValues... { constexpr operator no_conversion() const { return no_conversion{}; } }; template <typename... TagsAndValues> parms(TagsAndValues...) -> parms<TagsAndValues...>; template <typename T> struct default_init { constexpr default_init() = default; auto operator<=>(const default_init&) const = default; constexpr auto operator()() const { if constexpr (std::is_default_constructible_v<T>) { return T{}; } } }; template <typename T, typename Self, typename F> constexpr auto call_init(Self&, F& f) requires(requires { { f() } -> std::convertible_to<T>; }) { return f(); } template <typename T, typename Self, typename F> constexpr auto call_init(Self& self, F& f) requires(requires { { f(self) } -> std::convertible_to<T>; }) { return f(self); } template <typename T, typename Self, typename F> constexpr auto call_init(Self& self, F& f) requires(requires { { f() } -> std::same_as<void>; }) { static_assert(!std::is_same_v<decltype(f()), void>, "Required argument not specified"); } inline constexpr auto required = [] {}; template <fixed_string Tag, typename T, auto Init = default_init<T>(), meta_struct Attributes = {}> struct member { constexpr static auto tag() { return Tag; } constexpr static auto init() { return Init; } constexpr static auto attributes() { return Attributes; } using element_type = T; T value; template <typename Self, typename OtherT> constexpr member(Self&, tag_and_value<Tag, OtherT> tv) : value(std::move(tv.value)) {} template <typename Self> constexpr member(Self& self, no_conversion) : value(call_init<T>(self, Init)) {} template <typename Self> constexpr member(Self& self, tag_and_value<Tag, std::optional<std::remove_reference_t<T>>> tv_or) requires(!std::is_reference_v<T>) : value(tv_or.value.has_value() ? std::move(*tv_or.value) : call_init<T>(self, Init)) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, const member<Tag, OtherT, OtherInit, OtherAttributes>& other) : value(other.value) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, member<Tag, OtherT, OtherInit, OtherAttributes>&& other) : value(std::move(other.value)) {} template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( const member<Tag, OtherT, OtherInit, OtherAttributes>& other) { value = other.value; return *this; } template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( member<Tag, OtherT, OtherInit, OtherAttributes>&& other) { value = std::move(other.value); return *this; } constexpr member(member&&) = default; constexpr member(const member&) = default; constexpr member& operator=(member&&) = default; constexpr member& operator=(const member&) = default; auto operator<=>(const member&) const = default; }; template <typename... Members> struct meta_struct_impl : Members... { template <typename... Args> constexpr meta_struct_impl(parms<Args...> p) : Members(*this, std::move(p))... {} constexpr meta_struct_impl() : Members(*this, no_conversion{})... {} constexpr meta_struct_impl(meta_struct_impl&&) = default; constexpr meta_struct_impl(const meta_struct_impl&) = default; constexpr meta_struct_impl& operator=(meta_struct_impl&&) = default; constexpr meta_struct_impl& operator=(const meta_struct_impl&) = default; template <typename... OtherMembers> constexpr meta_struct_impl(meta_struct_impl<OtherMembers...>&& other) : Members(*this, std::move(other))... {}; template <typename... OtherMembers> constexpr meta_struct_impl(const meta_struct_impl<OtherMembers...>& other) : Members(*this, other)... {}; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( meta_struct_impl<OtherMembers...>&& other) { ((static_cast<Members&>(*this) = std::move(other)), ...); return *this; }; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( const meta_struct_impl<OtherMembers...>& other) { ((static_cast<Members&>(*this) = other), ...); return *this; }; constexpr operator no_conversion() const { return no_conversion{}; } auto operator<=>(const meta_struct_impl&) const = default; }; template <typename... Members> struct meta_struct : meta_struct_impl<Members...> { using super = meta_struct_impl<Members...>; template <typename... TagsAndValues> constexpr meta_struct(TagsAndValues... tags_and_values) : super(parms(std::move(tags_and_values)...)) {} constexpr meta_struct() = default; constexpr meta_struct(meta_struct&&) = default; constexpr meta_struct(const meta_struct&) = default; constexpr meta_struct& operator=(meta_struct&&) = default; constexpr meta_struct& operator=(const meta_struct&) = default; template <typename... OtherMembers> constexpr meta_struct(meta_struct<OtherMembers...>&& other) : super(std::move(other)) {} template <typename... OtherMembers> constexpr meta_struct(const meta_struct<OtherMembers...>& other) : super(other) {} template <typename... OtherMembers> constexpr meta_struct& operator=(meta_struct<OtherMembers...>&& other) { static_cast<super&>(*this) = std::move(other); return *this; } template <typename... OtherMembers> constexpr meta_struct& operator=(const meta_struct<OtherMembers...>& other) { static_cast<super&>(*this) = other; return *this; } auto operator<=>(const meta_struct&) const = default; }; template <fixed_string Tag> struct arg_type { template <typename T> constexpr auto operator=(T t) const { return member<Tag, T>(*this, tag_and_value<Tag, T>(std::move(t))); } }; template <fixed_string Tag> inline constexpr auto arg = arg_type<Tag>{}; template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, meta_struct_impl<MembersImpl...>& m) { return std::forward<F>(f)(static_cast<MembersImpl&>(m)...); } template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, const meta_struct_impl<MembersImpl...>& m) { return std::forward<F>(f)(static_cast<const MembersImpl&>(m)...); } template <typename F, typename... MembersImpl> constexpr decltype(auto) meta_struct_apply( F&& f, meta_struct_impl<MembersImpl...>&& m) { return std::forward<F>(f)(static_cast<MembersImpl&&>(m)...); } template <typename MetaStructImpl> struct apply_static_impl; template <typename... MembersImpl> struct apply_static_impl<meta_struct_impl<MembersImpl...>> { template <typename F> constexpr static decltype(auto) apply(F&& f) { return f(static_cast<MembersImpl*>(nullptr)...); } }; template <typename MetaStruct, typename F> constexpr auto meta_struct_apply(F&& f) { return apply_static_impl<typename MetaStruct::super>::apply( std::forward<F>(f)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(const member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>&& m) { return std::move(m.value); } template <fixed_string tag, typename MetaStruct> constexpr decltype(auto) get(MetaStruct&& s) { return get_impl<tag>(std::forward<MetaStruct>(s)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr member<tag, T, Init, Attributes> get_member_impl( const member<tag, T, Init, Attributes>& m); template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes(MetaStruct&& s) { return decltype(get_member_impl(s))::attributes(); } template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes() { return decltype(get_member_impl<Tag>( std::declval<MetaStruct&>()))::attributes(); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr std::true_type has_impl(const member<tag, T, Init, Attributes>&); template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr std::false_type has_impl(no_conversion); template <fixed_string tag, typename MetaStruct> constexpr bool has(MetaStruct&& s) { return decltype(has_impl<tag>(s))::value; } template <fixed_string tag, typename MetaStruct> constexpr bool has() { return decltype(has_impl<tag>(std::declval<MetaStruct&>()))::value; } #include <iostream> #include <string> template <typename MetaStruct> void print(std::ostream& os, const MetaStruct& ms) { meta_struct_apply( [&](const auto&... m) { auto print_item = [&](auto& m) { std::cout << m.tag().sv() << ":" << m.value << "\n"; }; (print_item(m), ...); }, ms); }; using NameAndIdArgs = meta_struct< // member<"name", std::string_view>, // member<"id", const int&> // >; void print_name_id(NameAndIdArgs args) { std::cout << "Name is " << get<"name">(args) << " and id is " << get<"id">(args) << "\n"; } enum class encoding : int { fixed = 0, variable = 1 }; int main() { using Person = meta_struct< // member<"id", int, required, {arg<"encoding"> = encoding::variable}>, // member<"name", std::string, required>, // member<"score", int, [](auto& self) { return get<"id">(self) + 1; }> // >; constexpr auto attributes = get_attributes<"id", Person>(); if constexpr (has<"encoding">(attributes) && get<"encoding">(attributes) == encoding::variable) { std::cout << "Encoding was variable"; } else { std::cout << "Encoding was fixed"; } auto print = [](auto& t) { meta_struct_apply( [&](const auto&... m) { ((std::cout << m.tag().sv() << ":" << m.value << "\n"), ...); }, t); }; Person p{arg<"id"> = 2, arg<"name"> = "John"}; using NameAndId = meta_struct< // member<"name", std::string_view>, // member<"id", int> // >; print(p); std::cout << "\n"; NameAndId n = p; print(n); std::cout << "\n"; print_name_id(p); print_name_id(n); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // Credits: // I gratefully acknowledge the inspiring work of Maxim Shemanarev (McSeem), // author of Anti-Grain Geometry (http://www.antigrain.com). I have used // the datastructure from AGG as a template for my own. //$Id: vertex_vector.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef VERTEX_VECTOR_HPP #define VERTEX_VECTOR_HPP // mapnik #include <mapnik/vertex.hpp> #include <mapnik/ctrans.hpp> // boost #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> // stl #include <vector> #include <cstring> namespace mapnik { template <typename T> class vertex_vector : private boost::noncopyable { typedef typename T::type value_type; typedef vertex<value_type,2> vertex_type; enum block_e { block_shift = 8, block_size = 1<<block_shift, block_mask = block_size - 1, grow_by = 256 }; private: unsigned num_blocks_; unsigned max_blocks_; value_type** vertexs_; unsigned char** commands_; unsigned pos_; public: vertex_vector() : num_blocks_(0), max_blocks_(0), vertexs_(0), commands_(0), pos_(0) {} ~vertex_vector() { if ( num_blocks_ ) { value_type** vertexs=vertexs_ + num_blocks_ - 1; while ( num_blocks_-- ) { delete [] *vertexs; --vertexs; } delete [] vertexs_; } } unsigned size() const { return pos_; } void push_back (value_type x,value_type y,unsigned command) { unsigned block = pos_ >> block_shift; if (block >= num_blocks_) { allocate_block(block); } value_type* vertex = vertexs_[block] + ((pos_ & block_mask) << 1); unsigned char* cmd= commands_[block] + (pos_ & block_mask); *cmd = static_cast<unsigned char>(command); *vertex++ = x; *vertex = y; ++pos_; } unsigned get_vertex(unsigned pos,value_type* x,value_type* y) const { if (pos >= pos_) return SEG_END; unsigned block = pos >> block_shift; const value_type* vertex = vertexs_[block] + (( pos & block_mask) << 1); *x = (*vertex++); *y = (*vertex); return commands_[block] [pos & block_mask]; } void set_capacity(size_t) { //do nothing } private: void allocate_block(unsigned block) { if (block >= max_blocks_) { value_type** new_vertexs = new value_type* [(max_blocks_ + grow_by) * 2]; unsigned char** new_commands = (unsigned char**)(new_vertexs + max_blocks_ + grow_by); if (vertexs_) { std::memcpy(new_vertexs,vertexs_,max_blocks_ * sizeof(value_type*)); std::memcpy(new_commands,commands_,max_blocks_ * sizeof(unsigned char*)); delete [] vertexs_; } vertexs_ = new_vertexs; commands_ = new_commands; max_blocks_ += grow_by; } vertexs_[block] = new value_type [block_size * 2 + block_size / (sizeof(value_type))]; commands_[block] = (unsigned char*)(vertexs_[block] + block_size*2); ++num_blocks_; } }; template <typename T> struct vertex_vector2 : boost::noncopyable { typedef typename T::type value_type; typedef boost::tuple<value_type,value_type,char> vertex_type; typedef typename std::vector<vertex_type>::const_iterator const_iterator; vertex_vector2() {} unsigned size() const { return cont_.size(); } void push_back (value_type x,value_type y,unsigned command) { cont_.push_back(vertex_type(x,y,command)); } unsigned get_vertex(unsigned pos,value_type* x,value_type* y) const { if (pos >= cont_.size()) return SEG_END; vertex_type const& c = cont_[pos]; *x = boost::get<0>(c); *y = boost::get<1>(c); return boost::get<2>(c); } const_iterator begin() const { return cont_.begin(); } const_iterator end() const { return cont_.end(); } void set_capacity(size_t size) { cont_.reserve(size); } private: std::vector<vertex_type> cont_; }; } #endif //VERTEX_VECTOR_HPP <commit_msg>allow vertex_vector2 to be copyable, enabling compiles on osx - needs second look #588<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // Credits: // I gratefully acknowledge the inspiring work of Maxim Shemanarev (McSeem), // author of Anti-Grain Geometry (http://www.antigrain.com). I have used // the datastructure from AGG as a template for my own. //$Id: vertex_vector.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef VERTEX_VECTOR_HPP #define VERTEX_VECTOR_HPP // mapnik #include <mapnik/vertex.hpp> #include <mapnik/ctrans.hpp> // boost #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> // stl #include <vector> #include <cstring> namespace mapnik { template <typename T> class vertex_vector : private boost::noncopyable { typedef typename T::type value_type; typedef vertex<value_type,2> vertex_type; enum block_e { block_shift = 8, block_size = 1<<block_shift, block_mask = block_size - 1, grow_by = 256 }; private: unsigned num_blocks_; unsigned max_blocks_; value_type** vertexs_; unsigned char** commands_; unsigned pos_; public: vertex_vector() : num_blocks_(0), max_blocks_(0), vertexs_(0), commands_(0), pos_(0) {} ~vertex_vector() { if ( num_blocks_ ) { value_type** vertexs=vertexs_ + num_blocks_ - 1; while ( num_blocks_-- ) { delete [] *vertexs; --vertexs; } delete [] vertexs_; } } unsigned size() const { return pos_; } void push_back (value_type x,value_type y,unsigned command) { unsigned block = pos_ >> block_shift; if (block >= num_blocks_) { allocate_block(block); } value_type* vertex = vertexs_[block] + ((pos_ & block_mask) << 1); unsigned char* cmd= commands_[block] + (pos_ & block_mask); *cmd = static_cast<unsigned char>(command); *vertex++ = x; *vertex = y; ++pos_; } unsigned get_vertex(unsigned pos,value_type* x,value_type* y) const { if (pos >= pos_) return SEG_END; unsigned block = pos >> block_shift; const value_type* vertex = vertexs_[block] + (( pos & block_mask) << 1); *x = (*vertex++); *y = (*vertex); return commands_[block] [pos & block_mask]; } void set_capacity(size_t) { //do nothing } private: void allocate_block(unsigned block) { if (block >= max_blocks_) { value_type** new_vertexs = new value_type* [(max_blocks_ + grow_by) * 2]; unsigned char** new_commands = (unsigned char**)(new_vertexs + max_blocks_ + grow_by); if (vertexs_) { std::memcpy(new_vertexs,vertexs_,max_blocks_ * sizeof(value_type*)); std::memcpy(new_commands,commands_,max_blocks_ * sizeof(unsigned char*)); delete [] vertexs_; } vertexs_ = new_vertexs; commands_ = new_commands; max_blocks_ += grow_by; } vertexs_[block] = new value_type [block_size * 2 + block_size / (sizeof(value_type))]; commands_[block] = (unsigned char*)(vertexs_[block] + block_size*2); ++num_blocks_; } }; template <typename T> struct vertex_vector2 //: boost::noncopyable { typedef typename T::type value_type; typedef boost::tuple<value_type,value_type,char> vertex_type; typedef typename std::vector<vertex_type>::const_iterator const_iterator; vertex_vector2() {} unsigned size() const { return cont_.size(); } void push_back (value_type x,value_type y,unsigned command) { cont_.push_back(vertex_type(x,y,command)); } unsigned get_vertex(unsigned pos,value_type* x,value_type* y) const { if (pos >= cont_.size()) return SEG_END; vertex_type const& c = cont_[pos]; *x = boost::get<0>(c); *y = boost::get<1>(c); return boost::get<2>(c); } const_iterator begin() const { return cont_.begin(); } const_iterator end() const { return cont_.end(); } void set_capacity(size_t size) { cont_.reserve(size); } private: std::vector<vertex_type> cont_; }; } #endif //VERTEX_VECTOR_HPP <|endoftext|>
<commit_before>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2010 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <oxt/system_calls.hpp> #include <oxt/backtrace.hpp> #include <oxt/thread.hpp> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include "../AgentBase.h" #include "../AccountsDatabase.h" #include "../Account.h" #include "../ServerInstanceDir.h" #include "LoggingServer.h" #include "../Exceptions.h" #include "../Utils.h" #include "../Utils/IOUtils.h" #include "../Utils/Base64.h" #include "../Utils/VariantMap.h" using namespace oxt; using namespace Passenger; static struct ev_loop *eventLoop; static struct ev_loop * createEventLoop() { struct ev_loop *loop; // libev doesn't like choosing epoll and kqueue because the author thinks they're broken, // so let's try to force it. loop = ev_default_loop(EVBACKEND_EPOLL); if (loop == NULL) { loop = ev_default_loop(EVBACKEND_KQUEUE); } if (loop == NULL) { loop = ev_default_loop(0); } if (loop == NULL) { throw RuntimeException("Cannot create an event loop"); } else { return loop; } } static void lowerPrivilege(const string &username, const struct passwd *user, const struct group *group) { int e; if (initgroups(username.c_str(), group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to set supplementary groups for " << "PassengerLoggingAgent: " << strerror(e) << " (" << e << ")"); } if (setgid(group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set group ID to " << group->gr_gid << ": " << strerror(e) << " (" << e << ")"); } if (setuid(user->pw_uid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set user ID: " << strerror(e) << " (" << e << ")"); } } void feedbackFdBecameReadable(ev::io &watcher, int revents) { /* This event indicates that the watchdog has been killed. * In this case we'll kill all descendant * processes and exit. There's no point in keeping this agent * running because we can't detect when the web server exits, * and because this agent doesn't own the server instance * directory. As soon as passenger-status is run, the server * instance directory will be cleaned up, making this agent's * services inaccessible. */ syscalls::killpg(getpgrp(), SIGKILL); _exit(2); // In case killpg() fails. } static string myself() { struct passwd *entry = getpwuid(geteuid()); if (entry != NULL) { return entry->pw_name; } else { throw NonExistentUserException(string("The current user, UID ") + toString(geteuid()) + ", doesn't have a corresponding " + "entry in the system's user database. Please fix your " + "system's user database first."); } } int main(int argc, char *argv[]) { VariantMap options = initializeAgent(argc, argv, "PassengerLoggingAgent"); string socketAddress = options.get("logging_agent_address"); string loggingDir = options.get("analytics_log_dir"); string password = options.get("logging_agent_password"); string username = options.get("analytics_log_user", false, myself()); string groupname = options.get("analytics_log_group", false); string permissions = options.get("analytics_log_permissions", false, DEFAULT_ANALYTICS_LOG_PERMISSIONS); string unionStationServiceAddress = options.get("union_station_service_address", false, DEFAULT_UNION_STATION_SERVICE_ADDRESS); int unionStationServicePort = options.getInt("union_station_service_port", false, DEFAULT_UNION_STATION_SERVICE_PORT); string unionStationServiceCert = options.get("union_station_service_cert", false); curl_global_init(CURL_GLOBAL_ALL); try { /********** Now begins the real initialization **********/ /* Create all the necessary objects and sockets... */ AccountsDatabasePtr accountsDatabase; FileDescriptor serverSocketFd; struct passwd *user; struct group *group; int ret; eventLoop = createEventLoop(); accountsDatabase = ptr(new AccountsDatabase()); serverSocketFd = createServer(socketAddress.c_str()); if (getSocketAddressType(socketAddress) == SAT_UNIX) { do { ret = chmod(parseUnixSocketAddress(socketAddress).c_str(), S_ISVTX | S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } while (ret == -1 && errno == EINTR); } /* Sanity check user accounts. */ user = getpwnam(username.c_str()); if (user == NULL) { throw NonExistentUserException(string("The configuration option ") + "'PassengerAnalyticsLogUser' (Apache) or " + "'passenger_analytics_log_user' (Nginx) was set to '" + username + "', but this user doesn't exist. Please fix " + "the configuration option."); } if (groupname.empty()) { group = getgrgid(user->pw_gid); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) wasn't set, " + "so PassengerLoggingAgent tried to use the default group " + "for user '" + username + "' - which is GID #" + toString(user->pw_gid) + " - as the group for the analytics " + "log dir, but this GID doesn't exist. " + "You can solve this problem by explicitly " + "setting PassengerAnalyticsLogGroup (Apache) or " + "passenger_analytics_log_group (Nginx) to a group that " + "does exist. In any case, it looks like your system's user " + "database is broken; Phusion Passenger can work fine even " + "with this broken user database, but you should still fix it."); } else { groupname = group->gr_name; } } else { group = getgrnam(groupname.c_str()); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) was set to '" + groupname + "', but this group doesn't exist. Please fix " + "the configuration option."); } } /* Create the logging directory if necessary. */ if (getFileType(loggingDir) == FT_NONEXISTANT) { if (geteuid() == 0) { makeDirTree(loggingDir, permissions, user->pw_uid, group->gr_gid); } else { makeDirTree(loggingDir, permissions); } } /* Now's a good time to lower the privilege. */ if (geteuid() == 0) { lowerPrivilege(username, user, group); } /* Now setup the actual logging server. */ accountsDatabase->add("logging", password, false); LoggingServer server(eventLoop, serverSocketFd, accountsDatabase, loggingDir, "u=rwx,g=rx,o=rx", GROUP_NOT_GIVEN, unionStationServiceAddress, unionStationServicePort, unionStationServiceCert); if (feedbackFdAvailable()) { MessageChannel feedbackChannel(FEEDBACK_FD); ev::io feedbackFdWatcher(eventLoop); feedbackFdWatcher.set<&feedbackFdBecameReadable>(); feedbackFdWatcher.start(FEEDBACK_FD, ev::READ); feedbackChannel.write("initialized", NULL); } /********** Initialized! Enter main loop... **********/ ev_loop(eventLoop, 0); return 0; } catch (const tracable_exception &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); return 1; } } <commit_msg>Logging agent: fix a potential memory corruption problem and install signal handlers that allow us to exit in a safer manner.<commit_after>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2010 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <oxt/system_calls.hpp> #include <oxt/backtrace.hpp> #include <oxt/thread.hpp> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include <signal.h> #include "../AgentBase.h" #include "../AccountsDatabase.h" #include "../Account.h" #include "../ServerInstanceDir.h" #include "LoggingServer.h" #include "../Exceptions.h" #include "../Utils.h" #include "../Utils/IOUtils.h" #include "../Utils/Base64.h" #include "../Utils/VariantMap.h" using namespace oxt; using namespace Passenger; static struct ev_loop *eventLoop; static struct ev_loop * createEventLoop() { struct ev_loop *loop; // libev doesn't like choosing epoll and kqueue because the author thinks they're broken, // so let's try to force it. loop = ev_default_loop(EVBACKEND_EPOLL); if (loop == NULL) { loop = ev_default_loop(EVBACKEND_KQUEUE); } if (loop == NULL) { loop = ev_default_loop(0); } if (loop == NULL) { throw RuntimeException("Cannot create an event loop"); } else { return loop; } } static void lowerPrivilege(const string &username, const struct passwd *user, const struct group *group) { int e; if (initgroups(username.c_str(), group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to set supplementary groups for " << "PassengerLoggingAgent: " << strerror(e) << " (" << e << ")"); } if (setgid(group->gr_gid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set group ID to " << group->gr_gid << ": " << strerror(e) << " (" << e << ")"); } if (setuid(user->pw_uid) != 0) { e = errno; P_WARN("WARNING: Unable to lower PassengerLoggingAgent's " "privilege to that of user '" << username << "': cannot set user ID: " << strerror(e) << " (" << e << ")"); } } void feedbackFdBecameReadable(ev::io &watcher, int revents) { /* This event indicates that the watchdog has been killed. * In this case we'll kill all descendant * processes and exit. There's no point in keeping this agent * running because we can't detect when the web server exits, * and because this agent doesn't own the server instance * directory. As soon as passenger-status is run, the server * instance directory will be cleaned up, making this agent's * services inaccessible. */ syscalls::killpg(getpgrp(), SIGKILL); _exit(2); // In case killpg() fails. } void caughtExitSignal(ev::sig &watcher, int revents) { P_DEBUG("Caught signal, exiting..."); ev_unloop(eventLoop, EVUNLOOP_ONE); } static string myself() { struct passwd *entry = getpwuid(geteuid()); if (entry != NULL) { return entry->pw_name; } else { throw NonExistentUserException(string("The current user, UID ") + toString(geteuid()) + ", doesn't have a corresponding " + "entry in the system's user database. Please fix your " + "system's user database first."); } } int main(int argc, char *argv[]) { VariantMap options = initializeAgent(argc, argv, "PassengerLoggingAgent"); string socketAddress = options.get("logging_agent_address"); string loggingDir = options.get("analytics_log_dir"); string password = options.get("logging_agent_password"); string username = options.get("analytics_log_user", false, myself()); string groupname = options.get("analytics_log_group", false); string permissions = options.get("analytics_log_permissions", false, DEFAULT_ANALYTICS_LOG_PERMISSIONS); string unionStationServiceAddress = options.get("union_station_service_address", false, DEFAULT_UNION_STATION_SERVICE_ADDRESS); int unionStationServicePort = options.getInt("union_station_service_port", false, DEFAULT_UNION_STATION_SERVICE_PORT); string unionStationServiceCert = options.get("union_station_service_cert", false); curl_global_init(CURL_GLOBAL_ALL); try { /********** Now begins the real initialization **********/ /* Create all the necessary objects and sockets... */ AccountsDatabasePtr accountsDatabase; FileDescriptor serverSocketFd; struct passwd *user; struct group *group; int ret; eventLoop = createEventLoop(); accountsDatabase = ptr(new AccountsDatabase()); serverSocketFd = createServer(socketAddress.c_str()); if (getSocketAddressType(socketAddress) == SAT_UNIX) { do { ret = chmod(parseUnixSocketAddress(socketAddress).c_str(), S_ISVTX | S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } while (ret == -1 && errno == EINTR); } /* Sanity check user accounts. */ user = getpwnam(username.c_str()); if (user == NULL) { throw NonExistentUserException(string("The configuration option ") + "'PassengerAnalyticsLogUser' (Apache) or " + "'passenger_analytics_log_user' (Nginx) was set to '" + username + "', but this user doesn't exist. Please fix " + "the configuration option."); } if (groupname.empty()) { group = getgrgid(user->pw_gid); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) wasn't set, " + "so PassengerLoggingAgent tried to use the default group " + "for user '" + username + "' - which is GID #" + toString(user->pw_gid) + " - as the group for the analytics " + "log dir, but this GID doesn't exist. " + "You can solve this problem by explicitly " + "setting PassengerAnalyticsLogGroup (Apache) or " + "passenger_analytics_log_group (Nginx) to a group that " + "does exist. In any case, it looks like your system's user " + "database is broken; Phusion Passenger can work fine even " + "with this broken user database, but you should still fix it."); } else { groupname = group->gr_name; } } else { group = getgrnam(groupname.c_str()); if (group == NULL) { throw NonExistentGroupException(string("The configuration option ") + "'PassengerAnalyticsLogGroup' (Apache) or " + "'passenger_analytics_log_group' (Nginx) was set to '" + groupname + "', but this group doesn't exist. Please fix " + "the configuration option."); } } /* Create the logging directory if necessary. */ if (getFileType(loggingDir) == FT_NONEXISTANT) { if (geteuid() == 0) { makeDirTree(loggingDir, permissions, user->pw_uid, group->gr_gid); } else { makeDirTree(loggingDir, permissions); } } /* Now's a good time to lower the privilege. */ if (geteuid() == 0) { lowerPrivilege(username, user, group); } /* Now setup the actual logging server. */ accountsDatabase->add("logging", password, false); LoggingServer server(eventLoop, serverSocketFd, accountsDatabase, loggingDir, "u=rwx,g=rx,o=rx", GROUP_NOT_GIVEN, unionStationServiceAddress, unionStationServicePort, unionStationServiceCert); ev::io feedbackFdWatcher(eventLoop); ev::sig sigintWatcher(eventLoop); ev::sig sigtermWatcher(eventLoop); if (feedbackFdAvailable()) { MessageChannel feedbackChannel(FEEDBACK_FD); feedbackFdWatcher.set<&feedbackFdBecameReadable>(); feedbackFdWatcher.start(FEEDBACK_FD, ev::READ); feedbackChannel.write("initialized", NULL); } sigintWatcher.set<&caughtExitSignal>(); sigintWatcher.start(SIGINT); sigtermWatcher.set<&caughtExitSignal>(); sigtermWatcher.start(SIGTERM); /********** Initialized! Enter main loop... **********/ ev_loop(eventLoop, 0); return 0; } catch (const tracable_exception &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); return 1; } } <|endoftext|>
<commit_before>#ifndef _DEFAULT_PLUGINS_H #define _DEFAULT_PLUGINS_H #include "./command-interface.hpp" #include "./bot.hpp" #include "./dynamic-loading.hpp" /* for Loader */ #include <string> #include <vector> #include <iostream> #include <stdexcept> namespace DefaultPlugins { static void strip_string(std::string& s); class Loader : protected IRC::CommandInterface { public: Loader(IRC::Bot *b) : CommandInterface("@load", "load or unload a module", b, true) {} bool triggered(const IRC::Packet& p) { if (p.type == IRC::Packet::PacketType::PRIVMSG && p.content.length() >= this->trigger_string.length()) { std::string s = p.content.substr(1 , p.content.find(" ") - 1); return s == "load" || s == "unload"; } return false; } void run(const IRC::Packet& p) { std::string command = ""; try { command = p.content.substr(1); std::string arg = command.substr(command.find(" ") + 1); if ( arg.find("-list") != std::string::npos) { std::string list_of_libs = ""; this->bot_ptr->each_dynamic_plugin([&list_of_libs](const DynamicPluginLoading::DynamicPlugin * d){ list_of_libs += d->get_name() + ", "; }); if (!list_of_libs.empty()) { list_of_libs.erase(list_of_libs.end()-2, list_of_libs.end()); } else { list_of_libs = "There are no dynamically loaded plugins at the moment."; } p.reply(list_of_libs); return; } command = command.substr(0, command.find(" ")); if (command == "load") { try { this->bot_ptr->add_dynamic_command( arg ); } catch (std::exception& e) { std::string ret = "Could not load: " + arg; p.reply( ret ); std::cerr << ret << " " << e.what() << '\n'; return; } } else if (command == "unload") { this->bot_ptr->remove_dynamic_command( arg ); } p.reply("Success."); } catch (std::exception& e) { std::string ret = "Could not load! Command passed: " + command; p.reply(ret); std::cerr << ret << " " << e.what() << '\n'; } } }; class Help : protected IRC::CommandInterface { public: Help(IRC::Bot* b, bool ra) : CommandInterface("@help", "Helps users use bot.", b, ra) {} void run(const IRC::Packet& p) { size_t first_space = p.content.find(" "); std::string content = first_space != std::string::npos ? p.content.substr(first_space) : ""; strip_string(content); std::string res = content.empty() ? do_help_general() : do_help_specific(content); p.owner->privmsg( p.sender , res ); } private: std::string do_help_general(void); std::string do_help_specific(const std::string& query); }; class Statistics : protected IRC::CommandInterface { public: Statistics(IRC::Bot* b) : CommandInterface("@stats", "does stats", b, true) {} void run(const IRC::Packet& p) { for (const auto& s : this->bot_ptr->get_stats()) { p.owner->privmsg(p.sender , s); } std::string tmp = ""; this->bot_ptr->each_command([&tmp, &p](IRC::CommandInterface* command){ tmp = command->get_stats(); if (!tmp.empty()) p.owner->privmsg(p.sender, tmp); }); } }; std::string Help::do_help_general(void) { std::string resp = "", tmp; this->bot_ptr->each_command([&resp, this, &tmp](IRC::CommandInterface* c) { if (c->trigger() != "@help" && (!c->requires_admin() || this->req_admin)) { tmp = c->trigger(); strip_string(tmp); resp += tmp + ", "; } }); /* guaranteed to have at least 2 chars because of the ", " added above.*/ if (!resp.empty()) { resp.erase(resp.end() - 2, resp.end()); } else { resp = "No commands installed!"; } return resp; } std::string Help::do_help_specific(const std::string& query) { bool found = false; this->bot_ptr->each_command([this, &query, &found](IRC::CommandInterface* c) { std::cout << c->trigger() << '\n'; if (c->trigger().find(query) != std::string::npos && (found = true) && (!c->requires_admin() || this->req_admin)) { return c->trigger() + " : " + c->desc(); } }); return found ? "" : "[ERROR] Couldn't find " + query; } static void strip_string(std::string& s) { size_t first = 0, last = s.length() - 1; while(first < s.length() && (s[first] == ' ' || s[first] == '\n' || s[first] == '\r')) first++; if (first == s.length()) { s = ""; return; } while(last >= 0 && (s[last] == ' ' || s[last] == '\n' || s[last] == '\r')) last--; s = s.substr(first, last - first + 1); } }; #endif <commit_msg>fix awkward bug in help<commit_after>#ifndef _DEFAULT_PLUGINS_H #define _DEFAULT_PLUGINS_H #include "./command-interface.hpp" #include "./bot.hpp" #include "./dynamic-loading.hpp" /* for Loader */ #include <string> #include <vector> #include <iostream> #include <stdexcept> namespace DefaultPlugins { static void strip_string(std::string& s); class Loader : protected IRC::CommandInterface { public: Loader(IRC::Bot *b) : CommandInterface("@load", "load or unload a module", b, true) {} bool triggered(const IRC::Packet& p) { if (p.type == IRC::Packet::PacketType::PRIVMSG && p.content.length() >= this->trigger_string.length()) { std::string s = p.content.substr(1 , p.content.find(" ") - 1); return s == "load" || s == "unload"; } return false; } void run(const IRC::Packet& p) { std::string command = ""; try { command = p.content.substr(1); std::string arg = command.substr(command.find(" ") + 1); if ( arg.find("-list") != std::string::npos) { std::string list_of_libs = ""; this->bot_ptr->each_dynamic_plugin([&list_of_libs](const DynamicPluginLoading::DynamicPlugin * d){ list_of_libs += d->get_name() + ", "; }); if (!list_of_libs.empty()) { list_of_libs.erase(list_of_libs.end()-2, list_of_libs.end()); } else { list_of_libs = "There are no dynamically loaded plugins at the moment."; } p.reply(list_of_libs); return; } command = command.substr(0, command.find(" ")); if (command == "load") { try { this->bot_ptr->add_dynamic_command( arg ); } catch (std::exception& e) { std::string ret = "Could not load: " + arg; p.reply( ret ); std::cerr << ret << " " << e.what() << '\n'; return; } } else if (command == "unload") { this->bot_ptr->remove_dynamic_command( arg ); } p.reply("Success."); } catch (std::exception& e) { std::string ret = "Could not load! Command passed: " + command; p.reply(ret); std::cerr << ret << " " << e.what() << '\n'; } } }; class Help : protected IRC::CommandInterface { public: Help(IRC::Bot* b, bool ra) : CommandInterface("@help", "Helps users use bot.", b, ra) {} void run(const IRC::Packet& p) { size_t first_space = p.content.find(" "); std::string content = first_space != std::string::npos ? p.content.substr(first_space) : ""; strip_string(content); std::string res = content.empty() ? do_help_general() : do_help_specific(content); p.owner->privmsg( p.sender , res ); } private: std::string do_help_general(void); std::string do_help_specific(const std::string& query); }; class Statistics : protected IRC::CommandInterface { public: Statistics(IRC::Bot* b) : CommandInterface("@stats", "does stats", b, true) {} void run(const IRC::Packet& p) { for (const auto& s : this->bot_ptr->get_stats()) { p.owner->privmsg(p.sender , s); } std::string tmp = ""; this->bot_ptr->each_command([&tmp, &p](IRC::CommandInterface* command){ tmp = command->get_stats(); if (!tmp.empty()) p.owner->privmsg(p.sender, tmp); }); } }; std::string Help::do_help_general(void) { std::string resp = "", tmp; this->bot_ptr->each_command([&resp, this, &tmp](IRC::CommandInterface* c) { if (c->trigger() != "@help" && (!c->requires_admin() || this->req_admin)) { tmp = c->trigger(); strip_string(tmp); resp += tmp + ", "; } }); /* guaranteed to have at least 2 chars because of the ", " added above.*/ if (!resp.empty()) { resp.erase(resp.end() - 2, resp.end()); } else { resp = "No commands installed!"; } return resp; } std::string Help::do_help_specific(const std::string& query) { std::string ret = "[ERROR] Couldn't find " + query; this->bot_ptr->each_command([this, &query, &ret](IRC::CommandInterface* c) { if (c->trigger().find(query) != std::string::npos && (!c->requires_admin() || this->req_admin)) { ret = c->trigger() + " : " + c->desc(); return; } }); return ret; } static void strip_string(std::string& s) { size_t first = 0, last = s.length() - 1; while(first < s.length() && (s[first] == ' ' || s[first] == '\n' || s[first] == '\r')) first++; if (first == s.length()) { s = ""; return; } while(last >= 0 && (s[last] == ' ' || s[last] == '\n' || s[last] == '\r')) last--; s = s.substr(first, last - first + 1); } }; #endif <|endoftext|>
<commit_before>//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements hierarchical time profiler. // //===----------------------------------------------------------------------===// #include "llvm/Support/TimeProfiler.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include <cassert> #include <chrono> #include <string> #include <vector> using namespace std::chrono; namespace llvm { static cl::opt<unsigned> TimeTraceGranularity( "time-trace-granularity", cl::desc( "Minimum time granularity (in microseconds) traced by time profiler"), cl::init(500)); TimeTraceProfiler *TimeTraceProfilerInstance = nullptr; static std::string escapeString(StringRef Src) { std::string OS; for (const unsigned char &C : Src) { switch (C) { case '"': case '/': case '\\': case '\b': case '\f': case '\n': case '\r': case '\t': OS += '\\'; OS += C; break; default: if (isPrint(C)) { OS += C; } } } return OS; } typedef duration<steady_clock::rep, steady_clock::period> DurationType; typedef std::pair<size_t, DurationType> CountAndDurationType; typedef std::pair<std::string, CountAndDurationType> NameAndCountAndDurationType; struct Entry { time_point<steady_clock> Start; DurationType Duration; std::string Name; std::string Detail; Entry(time_point<steady_clock> &&S, DurationType &&D, std::string &&N, std::string &&Dt) : Start(std::move(S)), Duration(std::move(D)), Name(std::move(N)), Detail(std::move(Dt)){}; }; struct TimeTraceProfiler { TimeTraceProfiler() { StartTime = steady_clock::now(); } void begin(std::string Name, llvm::function_ref<std::string()> Detail) { Stack.emplace_back(steady_clock::now(), DurationType{}, std::move(Name), Detail()); } void end() { assert(!Stack.empty() && "Must call begin() first"); auto &E = Stack.back(); E.Duration = steady_clock::now() - E.Start; // Only include sections longer than TimeTraceGranularity msec. if (duration_cast<microseconds>(E.Duration).count() > TimeTraceGranularity) Entries.emplace_back(E); // Track total time taken by each "name", but only the topmost levels of // them; e.g. if there's a template instantiation that instantiates other // templates from within, we only want to add the topmost one. "topmost" // happens to be the ones that don't have any currently open entries above // itself. if (std::find_if(++Stack.rbegin(), Stack.rend(), [&](const Entry &Val) { return Val.Name == E.Name; }) == Stack.rend()) { auto &CountAndTotal = CountAndTotalPerName[E.Name]; CountAndTotal.first++; CountAndTotal.second += E.Duration; } Stack.pop_back(); } void Write(raw_pwrite_stream &OS) { assert(Stack.empty() && "All profiler sections should be ended when calling Write"); OS << "{ \"traceEvents\": [\n"; // Emit all events for the main flame graph. for (const auto &E : Entries) { auto StartUs = duration_cast<microseconds>(E.Start - StartTime).count(); auto DurUs = duration_cast<microseconds>(E.Duration).count(); OS << "{ \"pid\":1, \"tid\":0, \"ph\":\"X\", \"ts\":" << StartUs << ", \"dur\":" << DurUs << ", \"name\":\"" << escapeString(E.Name) << "\", \"args\":{ \"detail\":\"" << escapeString(E.Detail) << "\"} },\n"; } // Emit totals by section name as additional "thread" events, sorted from // longest one. int Tid = 1; std::vector<NameAndCountAndDurationType> SortedTotals; SortedTotals.reserve(CountAndTotalPerName.size()); for (const auto &E : CountAndTotalPerName) SortedTotals.emplace_back(E.getKey(), E.getValue()); llvm::sort(SortedTotals.begin(), SortedTotals.end(), [](const NameAndCountAndDurationType &A, const NameAndCountAndDurationType &B) { return A.second.second > B.second.second; }); for (const auto &E : SortedTotals) { auto DurUs = duration_cast<microseconds>(E.second.second).count(); auto Count = CountAndTotalPerName[E.first].first; OS << "{ \"pid\":1, \"tid\":" << Tid << ", \"ph\":\"X\", \"ts\":" << 0 << ", \"dur\":" << DurUs << ", \"name\":\"Total " << escapeString(E.first) << "\", \"args\":{ \"count\":" << Count << ", \"avg ms\":" << (DurUs / Count / 1000) << "} },\n"; ++Tid; } // Emit metadata event with process name. OS << "{ \"cat\":\"\", \"pid\":1, \"tid\":0, \"ts\":0, \"ph\":\"M\", " "\"name\":\"process_name\", \"args\":{ \"name\":\"clang\" } }\n"; OS << "] }\n"; } SmallVector<Entry, 16> Stack; SmallVector<Entry, 128> Entries; StringMap<CountAndDurationType> CountAndTotalPerName; time_point<steady_clock> StartTime; }; void timeTraceProfilerInitialize() { assert(TimeTraceProfilerInstance == nullptr && "Profiler should not be initialized"); TimeTraceProfilerInstance = new TimeTraceProfiler(); } void timeTraceProfilerCleanup() { delete TimeTraceProfilerInstance; TimeTraceProfilerInstance = nullptr; } void timeTraceProfilerWrite(raw_pwrite_stream &OS) { assert(TimeTraceProfilerInstance != nullptr && "Profiler object can't be null"); TimeTraceProfilerInstance->Write(OS); } void timeTraceProfilerBegin(StringRef Name, StringRef Detail) { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->begin(Name, [&]() { return Detail; }); } void timeTraceProfilerBegin(StringRef Name, llvm::function_ref<std::string()> Detail) { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->begin(Name, Detail); } void timeTraceProfilerEnd() { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->end(); } } // namespace llvm <commit_msg>Use native llvm JSON library for time profiler output<commit_after>//===-- TimeProfiler.cpp - Hierarchical Time Profiler ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements hierarchical time profiler. // //===----------------------------------------------------------------------===// #include "llvm/Support/TimeProfiler.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/JSON.h" #include <cassert> #include <chrono> #include <string> #include <vector> using namespace std::chrono; namespace llvm { static cl::opt<unsigned> TimeTraceGranularity( "time-trace-granularity", cl::desc( "Minimum time granularity (in microseconds) traced by time profiler"), cl::init(500)); TimeTraceProfiler *TimeTraceProfilerInstance = nullptr; typedef duration<steady_clock::rep, steady_clock::period> DurationType; typedef std::pair<size_t, DurationType> CountAndDurationType; typedef std::pair<std::string, CountAndDurationType> NameAndCountAndDurationType; struct Entry { time_point<steady_clock> Start; DurationType Duration; std::string Name; std::string Detail; Entry(time_point<steady_clock> &&S, DurationType &&D, std::string &&N, std::string &&Dt) : Start(std::move(S)), Duration(std::move(D)), Name(std::move(N)), Detail(std::move(Dt)){}; }; struct TimeTraceProfiler { TimeTraceProfiler() { StartTime = steady_clock::now(); } void begin(std::string Name, llvm::function_ref<std::string()> Detail) { Stack.emplace_back(steady_clock::now(), DurationType{}, std::move(Name), Detail()); } void end() { assert(!Stack.empty() && "Must call begin() first"); auto &E = Stack.back(); E.Duration = steady_clock::now() - E.Start; // Only include sections longer than TimeTraceGranularity msec. if (duration_cast<microseconds>(E.Duration).count() > TimeTraceGranularity) Entries.emplace_back(E); // Track total time taken by each "name", but only the topmost levels of // them; e.g. if there's a template instantiation that instantiates other // templates from within, we only want to add the topmost one. "topmost" // happens to be the ones that don't have any currently open entries above // itself. if (std::find_if(++Stack.rbegin(), Stack.rend(), [&](const Entry &Val) { return Val.Name == E.Name; }) == Stack.rend()) { auto &CountAndTotal = CountAndTotalPerName[E.Name]; CountAndTotal.first++; CountAndTotal.second += E.Duration; } Stack.pop_back(); } void Write(raw_pwrite_stream &OS) { assert(Stack.empty() && "All profiler sections should be ended when calling Write"); json::Array Events; // Emit all events for the main flame graph. for (const auto &E : Entries) { auto StartUs = duration_cast<microseconds>(E.Start - StartTime).count(); auto DurUs = duration_cast<microseconds>(E.Duration).count(); Events.emplace_back(json::Object{ {"pid", 1}, {"tid", 0}, {"ph", "X"}, {"ts", StartUs}, {"dur", DurUs}, {"name", E.Name}, {"args", json::Object{{"detail", E.Detail}}}, }); } // Emit totals by section name as additional "thread" events, sorted from // longest one. int Tid = 1; std::vector<NameAndCountAndDurationType> SortedTotals; SortedTotals.reserve(CountAndTotalPerName.size()); for (const auto &E : CountAndTotalPerName) SortedTotals.emplace_back(E.getKey(), E.getValue()); llvm::sort(SortedTotals.begin(), SortedTotals.end(), [](const NameAndCountAndDurationType &A, const NameAndCountAndDurationType &B) { return A.second.second > B.second.second; }); for (const auto &E : SortedTotals) { auto DurUs = duration_cast<microseconds>(E.second.second).count(); auto Count = CountAndTotalPerName[E.first].first; Events.emplace_back(json::Object{ {"pid", 1}, {"tid", Tid}, {"ph", "X"}, {"ts", 0}, {"dur", DurUs}, {"name", "Total " + E.first}, {"args", json::Object{{"count", static_cast<int64_t>(Count)}, {"avg ms", static_cast<int64_t>(DurUs / Count / 1000)}}}, }); ++Tid; } // Emit metadata event with process name. Events.emplace_back(json::Object{ {"cat", ""}, {"pid", 1}, {"tid", 0}, {"ts", 0}, {"ph", "M"}, {"name", "process_name"}, {"args", json::Object{{"name", "clang"}}}, }); OS << formatv("{0:2}", json::Value(json::Object( {{"traceEvents", std::move(Events)}}))); } SmallVector<Entry, 16> Stack; SmallVector<Entry, 128> Entries; StringMap<CountAndDurationType> CountAndTotalPerName; time_point<steady_clock> StartTime; }; void timeTraceProfilerInitialize() { assert(TimeTraceProfilerInstance == nullptr && "Profiler should not be initialized"); TimeTraceProfilerInstance = new TimeTraceProfiler(); } void timeTraceProfilerCleanup() { delete TimeTraceProfilerInstance; TimeTraceProfilerInstance = nullptr; } void timeTraceProfilerWrite(raw_pwrite_stream &OS) { assert(TimeTraceProfilerInstance != nullptr && "Profiler object can't be null"); TimeTraceProfilerInstance->Write(OS); } void timeTraceProfilerBegin(StringRef Name, StringRef Detail) { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->begin(Name, [&]() { return Detail; }); } void timeTraceProfilerBegin(StringRef Name, llvm::function_ref<std::string()> Detail) { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->begin(Name, Detail); } void timeTraceProfilerEnd() { if (TimeTraceProfilerInstance != nullptr) TimeTraceProfilerInstance->end(); } } // namespace llvm <|endoftext|>
<commit_before><commit_msg>coverity#708214 Uninitialized scalar field<commit_after><|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // 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. // // ======================================================================== // // obj #include "RaytraceRenderer.h" #include "RaytraceMaterial.h" // ospray #include "ospray/common/Data.h" #include "ospray/lights/Light.h" //sys #include <vector> // ispc exports #include "RaytraceRenderer_ispc.h" namespace ospray { namespace raytracer { void RaytraceRenderer::commit() { Renderer::commit(); lightData = (Data*)getParamData("lights"); lightArray.clear(); if (lightData) { for (int i = 0; i < lightData->size(); i++) lightArray.push_back(((Light**)lightData->data)[i]->getIE()); } void **lightPtr = lightArray.empty() ? NULL : &lightArray[0]; vec3f bgColor; bgColor = getParam3f("bgColor", vec3f(1.f)); const bool shadowsEnabled = bool(getParam1i("shadowsEnabled", 1)); int numSamples = getParam1i("aoSamples", 4); float rayLength = getParam1f("aoRayLength", 1e20f); ispc::RaytraceRenderer_set(getIE(), (ispc::vec3f&)bgColor, shadowsEnabled, numSamples, rayLength, lightPtr, lightArray.size()); } RaytraceRenderer::RaytraceRenderer() { ispcEquivalent = ispc::RaytraceRenderer_create(this); } /*! \brief create a material of given type */ Material *RaytraceRenderer::createMaterial(const char *type) { Material *mat = new RaytraceMaterial; return mat; } OSP_REGISTER_RENDERER(RaytraceRenderer, raytracer); OSP_REGISTER_RENDERER(RaytraceRenderer, scivis); } // ::ospray::obj } // ::ospray <commit_msg>change "aoRayLength" parameter name to "aoOcclusionDistance"<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // 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. // // ======================================================================== // // obj #include "RaytraceRenderer.h" #include "RaytraceMaterial.h" // ospray #include "ospray/common/Data.h" #include "ospray/lights/Light.h" //sys #include <vector> // ispc exports #include "RaytraceRenderer_ispc.h" namespace ospray { namespace raytracer { void RaytraceRenderer::commit() { Renderer::commit(); lightData = (Data*)getParamData("lights"); lightArray.clear(); if (lightData) { for (int i = 0; i < lightData->size(); i++) lightArray.push_back(((Light**)lightData->data)[i]->getIE()); } void **lightPtr = lightArray.empty() ? NULL : &lightArray[0]; vec3f bgColor; bgColor = getParam3f("bgColor", vec3f(1.f)); const bool shadowsEnabled = bool(getParam1i("shadowsEnabled", 1)); int numSamples = getParam1i("aoSamples", 4); float rayLength = getParam1f("aoOcclusionDistance", 1e20f); ispc::RaytraceRenderer_set(getIE(), (ispc::vec3f&)bgColor, shadowsEnabled, numSamples, rayLength, lightPtr, lightArray.size()); } RaytraceRenderer::RaytraceRenderer() { ispcEquivalent = ispc::RaytraceRenderer_create(this); } /*! \brief create a material of given type */ Material *RaytraceRenderer::createMaterial(const char *type) { Material *mat = new RaytraceMaterial; return mat; } OSP_REGISTER_RENDERER(RaytraceRenderer, raytracer); OSP_REGISTER_RENDERER(RaytraceRenderer, scivis); } // ::ospray::obj } // ::ospray <|endoftext|>
<commit_before>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Vector4.hpp */ #pragma once #include <CGUL/Config.hpp> #include "../External/Defines.hpp" // Without this here you would need a human sacrifice each time you wanted to use operator<< namespace CGUL { template< typename Type > class Vector4T; template< typename Type > _CGUL_INLINE_DEFINE std::ostream& operator<<(std::ostream&, const CGUL::Vector4T< Type >&); } namespace CGUL { template< typename Type > struct Vector2T; template< typename Type > struct Vector3T; template< typename Type > struct MatrixT; /** @brief A four dimensional 32 bit floating point vector. * @todo Template this to allow 64 bit floating point or integer as well? */ template< typename Type > struct Vector4T { union { struct { Type x, y, z, w; }; Type m[4]; }; //! @brief Zero vector, defined as (0, 0, 0, 0). static const Vector4T zero; //! @brief One vector, defined as (1, 1, 1, 1). static const Vector4T one; //! @brief Unit X vector, defined as (1, 0, 0, 0). static const Vector4T unitX; //! @brief Unit Y vector, defined as (0, 1, 0, 0). static const Vector4T unitY; //! @brief Unit Y vector, defined as (0, 0, 1, 0). static const Vector4T unitZ; //! @brief Unit Y vector, defined as (0, 0, 0, 1). static const Vector4T unitW; //! @brief Initializes to (0, 0, 0, 0). _CGUL_INLINE_DEFINE Vector4T(); //! @brief Copies a vector into this vector. _CGUL_INLINE_DEFINE Vector4T(const Vector4T& copy); //! @brief Initializes all components to a given value. _CGUL_INLINE_DEFINE Vector4T(Type value); //! @brief Initializes the vector with individual component values. _CGUL_INLINE_DEFINE Vector4T(Type x, Type y, Type z, Type w); //! @brief Assigns another vector into this vector. _CGUL_INLINE_DEFINE Vector4T& operator=(const Vector4T& operand); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& operator[](UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type operator[](UInt32 index) const; //! @brief Gets the inverse of the vector. _CGUL_INLINE_DEFINE Vector4T operator-() const; //! @brief Checks if two vectors are @em exactly equal. _CGUL_INLINE_DEFINE bool operator==(const Vector4T& operand) const; //! @brief Checks if two vectors are not @em exactly equal. _CGUL_INLINE_DEFINE bool operator!=(const Vector4T& operand) const; //! @brief Performs component-based addition on two vectors. _CGUL_INLINE_DEFINE Vector4T operator+(const Vector4T& operand) const; //! @brief Adds the individual components of another vector to this vector's components. _CGUL_INLINE_DEFINE Vector4T& operator+=(const Vector4T& operand); //! @brief Performs component-based subtraction on two vectors. _CGUL_INLINE_DEFINE Vector4T operator-(const Vector4T& operand) const; //! @brief Subtracts the individual components of another vector from this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator-=(const Vector4T& operand); //! @brief Performs component-based multiplication on two vectors. _CGUL_INLINE_DEFINE Vector4T operator*(Type operand) const; //! @brief Multiplies the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator*=(Type operand); _CGUL_INLINE_DEFINE Vector4T< Type > operator*(const MatrixT< Type >& operand) const; //! @brief Performs component-based division on two vectors. _CGUL_INLINE_DEFINE Vector4T operator/(Type operand) const; //! @brief Divides the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator/=(Type operand); //! @brief An operator to output this vector on an output stream. _CGUL_INLINE_DEFINE friend std::ostream& operator<< <>(std::ostream& stream, const Vector4T< Type >& vector); template< typename OtherType > _CGUL_INLINE_DEFINE operator Vector4T< OtherType >(); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& At(UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type At(UInt32 index) const; //! @brief Sets all components to a given value. _CGUL_INLINE_DEFINE void Set(Type value); //! @brief Sets all components to the given values. _CGUL_INLINE_DEFINE void Set(Type x, Type y, Type z, Type w); //! @brief Clears the vector to (0, 0, 0, 0). _CGUL_INLINE_DEFINE void Clear(); //! @brief Performs a two dimensional swizzle. _CGUL_INLINE_DEFINE Vector2T< Type > Swizzle(UInt32 x, UInt32 y) const; //! @brief Performs a three dimensional swizzle. _CGUL_INLINE_DEFINE Vector3T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z) const; //! @brief Performs a four dimensional swizzle. _CGUL_INLINE_DEFINE Vector4T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z, UInt32 w) const; //! @brief Normalizes the vector resulting in a length of 1. _CGUL_INLINE_DEFINE void Normalize(); //! @brief Checks if the vector is normalizes within a given epsilon. _CGUL_INLINE_DEFINE Boolean IsNormalized(Type epsilon = 0.00001f) const; //! @brief Gets the magnitude of the vector. _CGUL_INLINE_DEFINE Type GetMagnitude() const; //! @brief Gets the squared magnitude of the vector. _CGUL_INLINE_DEFINE Type GetSquaredMagnitude() const; //! @brief Gets the manhattan magnitude of the vector. _CGUL_INLINE_DEFINE Type GetManhattanMagnitude() const; //! @brief Gets the distance between two vectors. _CGUL_INLINE_DEFINE Type GetDistance(const Vector4T& other) const; //! @brief Gets the squared distance between two vectors. _CGUL_INLINE_DEFINE Type GetSquaredDistance(const Vector4T& other) const; //! @brief Gets the manhattan distance between two vectors. _CGUL_INLINE_DEFINE Type GetManhattanDistance(const Vector4T& other) const; //! @brief Rounds down each component to the nearest whole number. _CGUL_INLINE_DEFINE void Floor(); //! @brief Rounds each component to the nearest whole number. _CGUL_INLINE_DEFINE void Round(); //! @brief Rounds up each component to the nearest whole number. _CGUL_INLINE_DEFINE void Ceil(); //! @brief Returns a vector with each component rounded down. _CGUL_INLINE_DEFINE Vector4T Floored() const; //! @brief Returns a vector with each component rounded. _CGUL_INLINE_DEFINE Vector4T Rounded() const; //! @brief Returns a vector with each component rounded up. _CGUL_INLINE_DEFINE Vector4T Ceiled() const; //! @brief Gets the sum of the elements. _CGUL_INLINE_DEFINE Type SumComponents() const; //! @brief Gets the product of the elements. _CGUL_INLINE_DEFINE Type MultiplyComponents() const; }; typedef Vector4T< Float32 > Vector4; typedef Vector4T< Float32 > Vector4D; typedef Vector4T< SInt16 > Rect16; typedef Vector4T< SInt32 > Rect32; typedef Vector4T< SInt64 > Rect64; typedef Vector4T< UInt16 > URect16; typedef Vector4T< UInt32 > URect32; typedef Vector4T< UInt64 > URect64; } #include "../External/Undefines.hpp" #include "Vector4_Implement.hpp" <commit_msg>Renamed RectX types to SRectX.<commit_after>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Vector4.hpp */ #pragma once #include <CGUL/Config.hpp> #include "../External/Defines.hpp" // Without this here you would need a human sacrifice each time you wanted to use operator<< namespace CGUL { template< typename Type > class Vector4T; template< typename Type > _CGUL_INLINE_DEFINE std::ostream& operator<<(std::ostream&, const CGUL::Vector4T< Type >&); } namespace CGUL { template< typename Type > struct Vector2T; template< typename Type > struct Vector3T; template< typename Type > struct MatrixT; /** @brief A four dimensional 32 bit floating point vector. * @todo Template this to allow 64 bit floating point or integer as well? */ template< typename Type > struct Vector4T { union { struct { Type x, y, z, w; }; Type m[4]; }; //! @brief Zero vector, defined as (0, 0, 0, 0). static const Vector4T zero; //! @brief One vector, defined as (1, 1, 1, 1). static const Vector4T one; //! @brief Unit X vector, defined as (1, 0, 0, 0). static const Vector4T unitX; //! @brief Unit Y vector, defined as (0, 1, 0, 0). static const Vector4T unitY; //! @brief Unit Y vector, defined as (0, 0, 1, 0). static const Vector4T unitZ; //! @brief Unit Y vector, defined as (0, 0, 0, 1). static const Vector4T unitW; //! @brief Initializes to (0, 0, 0, 0). _CGUL_INLINE_DEFINE Vector4T(); //! @brief Copies a vector into this vector. _CGUL_INLINE_DEFINE Vector4T(const Vector4T& copy); //! @brief Initializes all components to a given value. _CGUL_INLINE_DEFINE Vector4T(Type value); //! @brief Initializes the vector with individual component values. _CGUL_INLINE_DEFINE Vector4T(Type x, Type y, Type z, Type w); //! @brief Assigns another vector into this vector. _CGUL_INLINE_DEFINE Vector4T& operator=(const Vector4T& operand); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& operator[](UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type operator[](UInt32 index) const; //! @brief Gets the inverse of the vector. _CGUL_INLINE_DEFINE Vector4T operator-() const; //! @brief Checks if two vectors are @em exactly equal. _CGUL_INLINE_DEFINE bool operator==(const Vector4T& operand) const; //! @brief Checks if two vectors are not @em exactly equal. _CGUL_INLINE_DEFINE bool operator!=(const Vector4T& operand) const; //! @brief Performs component-based addition on two vectors. _CGUL_INLINE_DEFINE Vector4T operator+(const Vector4T& operand) const; //! @brief Adds the individual components of another vector to this vector's components. _CGUL_INLINE_DEFINE Vector4T& operator+=(const Vector4T& operand); //! @brief Performs component-based subtraction on two vectors. _CGUL_INLINE_DEFINE Vector4T operator-(const Vector4T& operand) const; //! @brief Subtracts the individual components of another vector from this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator-=(const Vector4T& operand); //! @brief Performs component-based multiplication on two vectors. _CGUL_INLINE_DEFINE Vector4T operator*(Type operand) const; //! @brief Multiplies the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator*=(Type operand); _CGUL_INLINE_DEFINE Vector4T< Type > operator*(const MatrixT< Type >& operand) const; //! @brief Performs component-based division on two vectors. _CGUL_INLINE_DEFINE Vector4T operator/(Type operand) const; //! @brief Divides the individual components of another vector onto this vector's //! components. _CGUL_INLINE_DEFINE Vector4T& operator/=(Type operand); //! @brief An operator to output this vector on an output stream. _CGUL_INLINE_DEFINE friend std::ostream& operator<< <>(std::ostream& stream, const Vector4T< Type >& vector); template< typename OtherType > _CGUL_INLINE_DEFINE operator Vector4T< OtherType >(); //! @brief Accesses an individual component in this vector. _CGUL_INLINE_DEFINE Type& At(UInt32 index); //! @brief Accesses an individual (constant) component in this vector. _CGUL_INLINE_DEFINE Type At(UInt32 index) const; //! @brief Sets all components to a given value. _CGUL_INLINE_DEFINE void Set(Type value); //! @brief Sets all components to the given values. _CGUL_INLINE_DEFINE void Set(Type x, Type y, Type z, Type w); //! @brief Clears the vector to (0, 0, 0, 0). _CGUL_INLINE_DEFINE void Clear(); //! @brief Performs a two dimensional swizzle. _CGUL_INLINE_DEFINE Vector2T< Type > Swizzle(UInt32 x, UInt32 y) const; //! @brief Performs a three dimensional swizzle. _CGUL_INLINE_DEFINE Vector3T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z) const; //! @brief Performs a four dimensional swizzle. _CGUL_INLINE_DEFINE Vector4T< Type > Swizzle(UInt32 x, UInt32 y, UInt32 z, UInt32 w) const; //! @brief Normalizes the vector resulting in a length of 1. _CGUL_INLINE_DEFINE void Normalize(); //! @brief Checks if the vector is normalizes within a given epsilon. _CGUL_INLINE_DEFINE Boolean IsNormalized(Type epsilon = 0.00001f) const; //! @brief Gets the magnitude of the vector. _CGUL_INLINE_DEFINE Type GetMagnitude() const; //! @brief Gets the squared magnitude of the vector. _CGUL_INLINE_DEFINE Type GetSquaredMagnitude() const; //! @brief Gets the manhattan magnitude of the vector. _CGUL_INLINE_DEFINE Type GetManhattanMagnitude() const; //! @brief Gets the distance between two vectors. _CGUL_INLINE_DEFINE Type GetDistance(const Vector4T& other) const; //! @brief Gets the squared distance between two vectors. _CGUL_INLINE_DEFINE Type GetSquaredDistance(const Vector4T& other) const; //! @brief Gets the manhattan distance between two vectors. _CGUL_INLINE_DEFINE Type GetManhattanDistance(const Vector4T& other) const; //! @brief Rounds down each component to the nearest whole number. _CGUL_INLINE_DEFINE void Floor(); //! @brief Rounds each component to the nearest whole number. _CGUL_INLINE_DEFINE void Round(); //! @brief Rounds up each component to the nearest whole number. _CGUL_INLINE_DEFINE void Ceil(); //! @brief Returns a vector with each component rounded down. _CGUL_INLINE_DEFINE Vector4T Floored() const; //! @brief Returns a vector with each component rounded. _CGUL_INLINE_DEFINE Vector4T Rounded() const; //! @brief Returns a vector with each component rounded up. _CGUL_INLINE_DEFINE Vector4T Ceiled() const; //! @brief Gets the sum of the elements. _CGUL_INLINE_DEFINE Type SumComponents() const; //! @brief Gets the product of the elements. _CGUL_INLINE_DEFINE Type MultiplyComponents() const; }; typedef Vector4T< Float32 > Vector4; typedef Vector4T< Float32 > Vector4D; typedef Vector4T< SInt16 > SRect16; typedef Vector4T< SInt32 > SRect32; typedef Vector4T< SInt64 > SRect64; typedef Vector4T< UInt16 > URect16; typedef Vector4T< UInt32 > URect32; typedef Vector4T< UInt64 > URect64; } #include "../External/Undefines.hpp" #include "Vector4_Implement.hpp" <|endoftext|>
<commit_before>/** * @file llnamelistctrl.cpp * @brief A list of names, automatically refreshed from name cache. * * $LicenseInfo:firstyear=2003&license=viewergpl$ * * Copyright (c) 2003-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnamelistctrl.h" #include <boost/tokenizer.hpp> #include "llcachename.h" #include "llfloaterreg.h" #include "llinventory.h" #include "llscrolllistitem.h" #include "llscrolllistcell.h" #include "llscrolllistcolumn.h" #include "llsdparam.h" #include "lltooltip.h" static LLDefaultChildRegistry::Register<LLNameListCtrl> r("name_list"); void LLNameListCtrl::NameTypeNames::declareValues() { declare("INDIVIDUAL", LLNameListCtrl::INDIVIDUAL); declare("GROUP", LLNameListCtrl::GROUP); declare("SPECIAL", LLNameListCtrl::SPECIAL); } LLNameListCtrl::Params::Params() : name_column(""), allow_calling_card_drop("allow_calling_card_drop", false) { name = "name_list"; } LLNameListCtrl::LLNameListCtrl(const LLNameListCtrl::Params& p) : LLScrollListCtrl(p), mNameColumnIndex(p.name_column.column_index), mNameColumn(p.name_column.column_name), mAllowCallingCardDrop(p.allow_calling_card_drop) {} // public void LLNameListCtrl::addNameItem(const LLUUID& agent_id, EAddPosition pos, BOOL enabled, std::string& suffix) { //llinfos << "LLNameListCtrl::addNameItem " << agent_id << llendl; NameItem item; item.value = agent_id; item.enabled = enabled; item.target = INDIVIDUAL; addNameItemRow(item, pos); } // virtual, public BOOL LLNameListCtrl::handleDragAndDrop( S32 x, S32 y, MASK mask, BOOL drop, EDragAndDropType cargo_type, void *cargo_data, EAcceptance *accept, std::string& tooltip_msg) { if (!mAllowCallingCardDrop) { return FALSE; } BOOL handled = FALSE; if (cargo_type == DAD_CALLINGCARD) { if (drop) { LLInventoryItem* item = (LLInventoryItem *)cargo_data; addNameItem(item->getCreatorUUID()); } *accept = ACCEPT_YES_MULTI; } else { *accept = ACCEPT_NO; if (tooltip_msg.empty()) { if (!getToolTip().empty()) { tooltip_msg = getToolTip(); } else { // backwards compatable English tooltip (should be overridden in xml) tooltip_msg.assign("Drag a calling card here\nto add a resident."); } } } handled = TRUE; lldebugst(LLERR_USER_INPUT) << "dragAndDrop handled by LLNameListCtrl " << getName() << llendl; return handled; } void LLNameListCtrl::showInspector(const LLUUID& avatar_id, bool is_group) { if (is_group) LLFloaterReg::showInstance("inspect_group", LLSD().with("group_id", avatar_id)); else LLFloaterReg::showInstance("inspect_avatar", LLSD().with("avatar_id", avatar_id)); } void LLNameListCtrl::mouseOverHighlightNthItem( S32 target_index ) { if (getHighlightedItemInx()!= target_index) { if(getHighlightedItemInx()!=-1) { LLScrollListItem* item = getItemList()[getHighlightedItemInx()]; LLScrollListText* cell = dynamic_cast<LLScrollListText*>(item->getColumn(mNameColumnIndex)); if(cell) cell->setTextWidth(cell->getTextWidth() + 16); } if(target_index != -1) { LLScrollListItem* item = getItemList()[target_index]; LLScrollListText* cell = dynamic_cast<LLScrollListText*>(item->getColumn(mNameColumnIndex)); if(cell) cell->setTextWidth(cell->getTextWidth() - 16); } } LLScrollListCtrl::mouseOverHighlightNthItem(target_index); } //virtual BOOL LLNameListCtrl::handleToolTip(S32 x, S32 y, MASK mask) { BOOL handled = FALSE; S32 column_index = getColumnIndexFromOffset(x); LLScrollListItem* hit_item = hitItem(x, y); if (hit_item && column_index == mNameColumnIndex) { // ...this is the column with the avatar name LLUUID avatar_id = hit_item->getUUID(); if (avatar_id.notNull()) { // ...valid avatar id LLScrollListCell* hit_cell = hit_item->getColumn(column_index); if (hit_cell) { S32 row_index = getItemIndex(hit_item); LLRect cell_rect = getCellRect(row_index, column_index); // Convert rect local to screen coordinates LLRect sticky_rect; localRectToScreen(cell_rect, &sticky_rect); // Spawn at right side of cell LLPointer<LLUIImage> icon = LLUI::getUIImage("Info_Small"); LLCoordGL pos( sticky_rect.mRight - 16, sticky_rect.mTop - (sticky_rect.getHeight() - icon->getHeight())/2 ); // Should we show a group or an avatar inspector? bool is_group = hit_item->getValue()["is_group"].asBoolean(); LLToolTip::Params params; params.background_visible( false ); params.click_callback( boost::bind(&LLNameListCtrl::showInspector, this, avatar_id, is_group) ); params.delay_time(0.0f); // spawn instantly on hover params.image( icon ); params.message(""); params.padding(0); params.pos(pos); params.sticky_rect(sticky_rect); LLToolTipMgr::getInstance()->show(params); handled = TRUE; } } } if (!handled) { handled = LLScrollListCtrl::handleToolTip(x, y, mask); } return handled; } // public void LLNameListCtrl::addGroupNameItem(const LLUUID& group_id, EAddPosition pos, BOOL enabled) { NameItem item; item.value = group_id; item.enabled = enabled; item.target = GROUP; addNameItemRow(item, pos); } // public void LLNameListCtrl::addGroupNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = GROUP; addNameItemRow(item, pos); } void LLNameListCtrl::addNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = INDIVIDUAL; addNameItemRow(item, pos); } LLScrollListItem* LLNameListCtrl::addElement(const LLSD& element, EAddPosition pos, void* userdata) { LLNameListCtrl::NameItem item_params; LLParamSDParser::instance().readSD(element, item_params); item_params.userdata = userdata; return addNameItemRow(item_params, pos); } LLScrollListItem* LLNameListCtrl::addNameItemRow( const LLNameListCtrl::NameItem& name_item, EAddPosition pos, std::string& suffix) { LLUUID id = name_item.value().asUUID(); LLNameListItem* item = NULL; // Store item type so that we can invoke the proper inspector. // *TODO Vadim: Is there a more proper way of storing additional item data? { LLNameListCtrl::NameItem item_p(name_item); item_p.value = LLSD().with("uuid", id).with("is_group", name_item.target() == GROUP); item = new LLNameListItem(item_p); LLScrollListCtrl::addRow(item, item_p, pos); } if (!item) return NULL; // use supplied name by default std::string fullname = name_item.name; switch(name_item.target) { case GROUP: gCacheName->getGroupName(id, fullname); // fullname will be "nobody" if group not found break; case SPECIAL: // just use supplied name break; case INDIVIDUAL: { std::string name; if (gCacheName->getFullName(id, name)) { fullname = name; } break; } default: break; } // Append optional suffix. if (!suffix.empty()) { fullname.append(suffix); } LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } dirtyColumns(); // this column is resizable LLScrollListColumn* columnp = getColumn(mNameColumnIndex); if (columnp && columnp->mHeader) { columnp->mHeader->setHasResizableElement(TRUE); } return item; } // public void LLNameListCtrl::removeNameItem(const LLUUID& agent_id) { // Find the item specified with agent_id. S32 idx = -1; for (item_list::iterator it = getItemList().begin(); it != getItemList().end(); it++) { LLScrollListItem* item = *it; if (item->getUUID() == agent_id) { idx = getItemIndex(item); break; } } // Remove it. if (idx >= 0) { selectNthItem(idx); // not sure whether this is needed, taken from previous implementation deleteSingleItem(idx); } } // public void LLNameListCtrl::refresh(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { //llinfos << "LLNameListCtrl::refresh " << id << " '" << first << " " // << last << "'" << llendl; std::string fullname; if (!is_group) { fullname = first + " " + last; } else { fullname = first; } // TODO: scan items for that ID, fix if necessary item_list::iterator iter; for (iter = getItemList().begin(); iter != getItemList().end(); iter++) { LLScrollListItem* item = *iter; if (item->getUUID() == id) { LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } } } dirtyColumns(); } // static void LLNameListCtrl::refreshAll(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { LLInstanceTrackerScopedGuard guard; LLInstanceTracker<LLNameListCtrl>::instance_iter it; for (it = guard.beginInstances(); it != guard.endInstances(); ++it) { LLNameListCtrl& ctrl = *it; ctrl.refresh(id, first, last, is_group); } } void LLNameListCtrl::updateColumns() { LLScrollListCtrl::updateColumns(); if (!mNameColumn.empty()) { LLScrollListColumn* name_column = getColumn(mNameColumn); if (name_column) { mNameColumnIndex = name_column->mIndex; } } } <commit_msg>remove hardcoded numbers<commit_after>/** * @file llnamelistctrl.cpp * @brief A list of names, automatically refreshed from name cache. * * $LicenseInfo:firstyear=2003&license=viewergpl$ * * Copyright (c) 2003-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnamelistctrl.h" #include <boost/tokenizer.hpp> #include "llcachename.h" #include "llfloaterreg.h" #include "llinventory.h" #include "llscrolllistitem.h" #include "llscrolllistcell.h" #include "llscrolllistcolumn.h" #include "llsdparam.h" #include "lltooltip.h" static LLDefaultChildRegistry::Register<LLNameListCtrl> r("name_list"); static const S32 info_icon_size = 16; void LLNameListCtrl::NameTypeNames::declareValues() { declare("INDIVIDUAL", LLNameListCtrl::INDIVIDUAL); declare("GROUP", LLNameListCtrl::GROUP); declare("SPECIAL", LLNameListCtrl::SPECIAL); } LLNameListCtrl::Params::Params() : name_column(""), allow_calling_card_drop("allow_calling_card_drop", false) { name = "name_list"; } LLNameListCtrl::LLNameListCtrl(const LLNameListCtrl::Params& p) : LLScrollListCtrl(p), mNameColumnIndex(p.name_column.column_index), mNameColumn(p.name_column.column_name), mAllowCallingCardDrop(p.allow_calling_card_drop) {} // public void LLNameListCtrl::addNameItem(const LLUUID& agent_id, EAddPosition pos, BOOL enabled, std::string& suffix) { //llinfos << "LLNameListCtrl::addNameItem " << agent_id << llendl; NameItem item; item.value = agent_id; item.enabled = enabled; item.target = INDIVIDUAL; addNameItemRow(item, pos); } // virtual, public BOOL LLNameListCtrl::handleDragAndDrop( S32 x, S32 y, MASK mask, BOOL drop, EDragAndDropType cargo_type, void *cargo_data, EAcceptance *accept, std::string& tooltip_msg) { if (!mAllowCallingCardDrop) { return FALSE; } BOOL handled = FALSE; if (cargo_type == DAD_CALLINGCARD) { if (drop) { LLInventoryItem* item = (LLInventoryItem *)cargo_data; addNameItem(item->getCreatorUUID()); } *accept = ACCEPT_YES_MULTI; } else { *accept = ACCEPT_NO; if (tooltip_msg.empty()) { if (!getToolTip().empty()) { tooltip_msg = getToolTip(); } else { // backwards compatable English tooltip (should be overridden in xml) tooltip_msg.assign("Drag a calling card here\nto add a resident."); } } } handled = TRUE; lldebugst(LLERR_USER_INPUT) << "dragAndDrop handled by LLNameListCtrl " << getName() << llendl; return handled; } void LLNameListCtrl::showInspector(const LLUUID& avatar_id, bool is_group) { if (is_group) LLFloaterReg::showInstance("inspect_group", LLSD().with("group_id", avatar_id)); else LLFloaterReg::showInstance("inspect_avatar", LLSD().with("avatar_id", avatar_id)); } void LLNameListCtrl::mouseOverHighlightNthItem( S32 target_index ) { if (getHighlightedItemInx()!= target_index) { if(getHighlightedItemInx()!=-1) { LLScrollListItem* item = getItemList()[getHighlightedItemInx()]; LLScrollListText* cell = dynamic_cast<LLScrollListText*>(item->getColumn(mNameColumnIndex)); if(cell) cell->setTextWidth(cell->getTextWidth() + info_icon_size); } if(target_index != -1) { LLScrollListItem* item = getItemList()[target_index]; LLScrollListText* cell = dynamic_cast<LLScrollListText*>(item->getColumn(mNameColumnIndex)); if(cell) cell->setTextWidth(cell->getTextWidth() - info_icon_size); } } LLScrollListCtrl::mouseOverHighlightNthItem(target_index); } //virtual BOOL LLNameListCtrl::handleToolTip(S32 x, S32 y, MASK mask) { BOOL handled = FALSE; S32 column_index = getColumnIndexFromOffset(x); LLScrollListItem* hit_item = hitItem(x, y); if (hit_item && column_index == mNameColumnIndex) { // ...this is the column with the avatar name LLUUID avatar_id = hit_item->getUUID(); if (avatar_id.notNull()) { // ...valid avatar id LLScrollListCell* hit_cell = hit_item->getColumn(column_index); if (hit_cell) { S32 row_index = getItemIndex(hit_item); LLRect cell_rect = getCellRect(row_index, column_index); // Convert rect local to screen coordinates LLRect sticky_rect; localRectToScreen(cell_rect, &sticky_rect); // Spawn at right side of cell LLPointer<LLUIImage> icon = LLUI::getUIImage("Info_Small"); LLCoordGL pos( sticky_rect.mRight - info_icon_size, sticky_rect.mTop - (sticky_rect.getHeight() - icon->getHeight())/2 ); // Should we show a group or an avatar inspector? bool is_group = hit_item->getValue()["is_group"].asBoolean(); LLToolTip::Params params; params.background_visible( false ); params.click_callback( boost::bind(&LLNameListCtrl::showInspector, this, avatar_id, is_group) ); params.delay_time(0.0f); // spawn instantly on hover params.image( icon ); params.message(""); params.padding(0); params.pos(pos); params.sticky_rect(sticky_rect); LLToolTipMgr::getInstance()->show(params); handled = TRUE; } } } if (!handled) { handled = LLScrollListCtrl::handleToolTip(x, y, mask); } return handled; } // public void LLNameListCtrl::addGroupNameItem(const LLUUID& group_id, EAddPosition pos, BOOL enabled) { NameItem item; item.value = group_id; item.enabled = enabled; item.target = GROUP; addNameItemRow(item, pos); } // public void LLNameListCtrl::addGroupNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = GROUP; addNameItemRow(item, pos); } void LLNameListCtrl::addNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = INDIVIDUAL; addNameItemRow(item, pos); } LLScrollListItem* LLNameListCtrl::addElement(const LLSD& element, EAddPosition pos, void* userdata) { LLNameListCtrl::NameItem item_params; LLParamSDParser::instance().readSD(element, item_params); item_params.userdata = userdata; return addNameItemRow(item_params, pos); } LLScrollListItem* LLNameListCtrl::addNameItemRow( const LLNameListCtrl::NameItem& name_item, EAddPosition pos, std::string& suffix) { LLUUID id = name_item.value().asUUID(); LLNameListItem* item = NULL; // Store item type so that we can invoke the proper inspector. // *TODO Vadim: Is there a more proper way of storing additional item data? { LLNameListCtrl::NameItem item_p(name_item); item_p.value = LLSD().with("uuid", id).with("is_group", name_item.target() == GROUP); item = new LLNameListItem(item_p); LLScrollListCtrl::addRow(item, item_p, pos); } if (!item) return NULL; // use supplied name by default std::string fullname = name_item.name; switch(name_item.target) { case GROUP: gCacheName->getGroupName(id, fullname); // fullname will be "nobody" if group not found break; case SPECIAL: // just use supplied name break; case INDIVIDUAL: { std::string name; if (gCacheName->getFullName(id, name)) { fullname = name; } break; } default: break; } // Append optional suffix. if (!suffix.empty()) { fullname.append(suffix); } LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } dirtyColumns(); // this column is resizable LLScrollListColumn* columnp = getColumn(mNameColumnIndex); if (columnp && columnp->mHeader) { columnp->mHeader->setHasResizableElement(TRUE); } return item; } // public void LLNameListCtrl::removeNameItem(const LLUUID& agent_id) { // Find the item specified with agent_id. S32 idx = -1; for (item_list::iterator it = getItemList().begin(); it != getItemList().end(); it++) { LLScrollListItem* item = *it; if (item->getUUID() == agent_id) { idx = getItemIndex(item); break; } } // Remove it. if (idx >= 0) { selectNthItem(idx); // not sure whether this is needed, taken from previous implementation deleteSingleItem(idx); } } // public void LLNameListCtrl::refresh(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { //llinfos << "LLNameListCtrl::refresh " << id << " '" << first << " " // << last << "'" << llendl; std::string fullname; if (!is_group) { fullname = first + " " + last; } else { fullname = first; } // TODO: scan items for that ID, fix if necessary item_list::iterator iter; for (iter = getItemList().begin(); iter != getItemList().end(); iter++) { LLScrollListItem* item = *iter; if (item->getUUID() == id) { LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } } } dirtyColumns(); } // static void LLNameListCtrl::refreshAll(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { LLInstanceTrackerScopedGuard guard; LLInstanceTracker<LLNameListCtrl>::instance_iter it; for (it = guard.beginInstances(); it != guard.endInstances(); ++it) { LLNameListCtrl& ctrl = *it; ctrl.refresh(id, first, last, is_group); } } void LLNameListCtrl::updateColumns() { LLScrollListCtrl::updateColumns(); if (!mNameColumn.empty()) { LLScrollListColumn* name_column = getColumn(mNameColumn); if (name_column) { mNameColumnIndex = name_column->mIndex; } } } <|endoftext|>
<commit_before>/*********************************************************************/ /* Copyright (c) 2013, EPFL/Blue Brain Project */ /* Raphael Dumusc <raphael.dumusc@epfl.ch> */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include "DockPixelStreamer.h" #include "Pictureflow.h" #include "Content.h" #include "ContentFactory.h" #include "ContentWindowManager.h" #include "MovieContent.h" #include "main.h" #include "PixelStreamSegmentJpegCompressor.h" #define DOCK_UNIQUE_URI "menu" namespace { QImage createSlideImage_( const QSize& size, const QString& fileName, const bool isDir, const QColor& bgcolor1, const QColor& bgcolor2 ) { QImage img( size, QImage::Format_RGB32 ); img.setText( "source", fileName ); if( isDir) img.setText( "dir", "true" ); QPainter painter( &img ); QPoint p1( img.width()*4/10, 0 ); QPoint p2( img.width()*6/10, img.height( )); QLinearGradient linearGrad( p1, p2 ); linearGrad.setColorAt( 0, bgcolor1 ); linearGrad.setColorAt( 1, bgcolor2 ); painter.setBrush(linearGrad); painter.fillRect( 0, 0, img.width(), img.height(), QBrush(linearGrad)); painter.end(); return img; } } QString DockPixelStreamer::getUniqueURI() { return QString(DOCK_UNIQUE_URI); } DockPixelStreamer::DockPixelStreamer(DisplayGroupManager *displayGroupManager) : LocalPixelStreamer(displayGroupManager, QString(DOCK_UNIQUE_URI)) , frameIndex_(0) { connect(this, SIGNAL(close(QString)), displayGroupManager, SLOT(deletePixelStream(QString))); av_register_all(); flow_ = new PictureFlow; flow_->resize( g_configuration->getTotalWidth()/8, g_configuration->getTotalHeight()/8 ); const int height = flow_->height() * .8; flow_->setSlideSize( QSize( 0.6 * height, height )); flow_->setBackgroundColor( Qt::darkGray ); connect( flow_, SIGNAL( imageUpdated( const QImage& )), this, SLOT( update( const QImage& ))); loader_ = new AsyncImageLoader(flow_->slideSize()); loader_->moveToThread( &loadThread_ ); connect( loader_, SIGNAL(imageLoaded(int, QImage)), flow_, SLOT(setSlide( int, QImage ))); connect( this, SIGNAL(renderPreview( const QString&, const int )), loader_, SLOT(loadImage( const QString&, const int ))); loadThread_.start(); changeDirectory( g_configuration->getDockStartDir( )); } DockPixelStreamer::~DockPixelStreamer() { loadThread_.quit(); loadThread_.wait(); delete flow_; delete loader_; } void DockPixelStreamer::updateInteractionState(InteractionState interactionState) { if (interactionState.type == InteractionState::EVT_CLICK) { // xPos is click position in (pixel) units inside the dock const int xPos = interactionState.mouseX * flow_->size().width(); // mid is half the width of the dock in (pixel) units const int dockHalfWidth = flow_->size().width() / 2; // SlideMid is half the slide width in pixels const int slideHalfWidth = flow_->slideSize().width() / 2; if( xPos > dockHalfWidth-slideHalfWidth && xPos < dockHalfWidth+slideHalfWidth ) { onItem(); } else { if( xPos > dockHalfWidth ) flow_->showNext(); else flow_->showPrevious(); } } else if (interactionState.type == InteractionState::EVT_MOVE || interactionState.type == InteractionState::EVT_WHEEL) { const int offs = interactionState.dx * flow_->size().width() / 4; flow_->showSlide( flow_->centerIndex() - offs ); } } void DockPixelStreamer::open() { flow_->triggerRender(); } void DockPixelStreamer::onItem() { const QImage& image = flow_->slide( flow_->centerIndex( )); const QString& source = image.text( "source" ); if( image.text( "dir" ).isEmpty( )) { const QString extension = QFileInfo(source).suffix().toLower(); if( extension == "dcx" ) { g_displayGroupManager->loadStateXMLFile( source.toStdString( )); emit(close(getUniqueURI())); } else { boost::shared_ptr< Content > c = ContentFactory::getContent( source ); if( c ) { boost::shared_ptr<ContentWindowManager> cwm(new ContentWindowManager(c)); g_displayGroupManager->addContentWindowManager( cwm ); emit(close(getUniqueURI())); } } } else { changeDirectory( source ); } } void DockPixelStreamer::update(const QImage& image) { PixelStreamSegment segment; segment.parameters = makeSegmentHeader(); // TODO remove this crappy compression when merging with Daniel's no-compression codebase computeSegmentJpeg(image, segment); ++frameIndex_; emit segmentUpdated(uri_, segment); } PixelStreamSegmentParameters DockPixelStreamer::makeSegmentHeader() { PixelStreamSegmentParameters parameters; parameters.sourceIndex = 0; parameters.frameIndex = frameIndex_; parameters.totalHeight = flow_->size().height(); parameters.totalWidth = flow_->size().width(); parameters.height = parameters.totalHeight; parameters.width = parameters.totalWidth; parameters.x = 0; parameters.y = 0; return parameters; } void DockPixelStreamer::changeDirectory( const QString& dir ) { slideIndex_[currentDir_.path()] = flow_->centerIndex(); flow_->clear(); currentDir_ = dir; currentDir_.setFilter( QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot ); QStringList filters = ContentFactory::getSupportedFilesFilter(); filters.append( "*.dcx" ); currentDir_.setNameFilters( filters ); const QFileInfoList& fileList = currentDir_.entryInfoList(); currentDir_.setFilter( QDir::Dirs | QDir::NoDotAndDotDot ); currentDir_.setNameFilters( QStringList( )); const QFileInfoList& dirList = currentDir_.entryInfoList(); QDir rootDir = dir; const bool hasRootDir = rootDir.cdUp(); if( hasRootDir) { QString upFolder = rootDir.path(); QImage img = createSlideImage_( flow_->slideSize(), upFolder, true, Qt::darkGray, Qt::lightGray ); flow_->addSlide( img, "UP: " + upFolder ); } for( int i = 0; i < fileList.size(); ++i ) { QFileInfo fileInfo = fileList.at( i ); const QString& fileName = currentDir_.absoluteFilePath( fileInfo.fileName( )); QImage img = createSlideImage_( flow_->slideSize(), fileName, false, Qt::black, Qt::white ); flow_->addSlide( img, fileInfo.fileName( )); emit renderPreview( fileName, flow_->slideCount( )); } for( int i = 0; i < dirList.size(); ++i ) { QFileInfo fileInfo = dirList.at( i ); const QString& fileName = currentDir_.absoluteFilePath( fileInfo.fileName( )); if( !fileName.endsWith( ".pyramid" )) { QImage img = createSlideImage_( flow_->slideSize(), fileName, true, Qt::black, Qt::white ); flow_->addSlide( img, fileInfo.fileName( )); } } flow_->setCenterIndex( slideIndex_[currentDir_.path()] ); } AsyncImageLoader::AsyncImageLoader(QSize defaultSize) : defaultSize_(defaultSize) { } void AsyncImageLoader::loadImage( const QString& fileName, const int index ) { const QString extension = QFileInfo(fileName).suffix().toLower(); if( extension == "dcx" ) { QImage image = createSlideImage_( defaultSize_, fileName, false, Qt::darkCyan, Qt::cyan ); emit imageLoaded(index, image); return; } if( extension == "pyr" ) { QImageReader reader( fileName + "amid/0.jpg" ); QImage image = reader.read(); image.setText( "source", fileName ); emit imageLoaded(index, image); return; } QImageReader reader( fileName ); if( reader.canRead( )) { QImage image = reader.read(); image.setText( "source", fileName ); emit imageLoaded(index, image); return; } else if( reader.error() != QImageReader::UnsupportedFormatError ) return; if( !MovieContent::getSupportedExtensions().contains( extension )) return; AVFormatContext* avFormatContext; if( avformat_open_input( &avFormatContext, fileName.toAscii(), 0, 0 ) != 0 ) return; if( avformat_find_stream_info( avFormatContext, 0 ) < 0 ) return; // find the first video stream int streamIdx = -1; for( unsigned int i = 0; i < avFormatContext->nb_streams; ++i ) { if( avFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ) { streamIdx = i; break; } } if( streamIdx == -1 ) return; AVStream* videostream = avFormatContext->streams[streamIdx]; AVCodecContext* avCodecContext = videostream->codec; AVCodec* codec = avcodec_find_decoder( avCodecContext->codec_id ); if( !codec ) return; if( avcodec_open2( avCodecContext, codec, 0 ) < 0 ) return; AVFrame* avFrame = avcodec_alloc_frame(); AVFrame* avFrameRGB = avcodec_alloc_frame(); QImage image( avCodecContext->width, avCodecContext->height, QImage::Format_RGB32 ); int numBytes = avpicture_get_size( PIX_FMT_RGB24, image.width(), image.height( )); uint8_t* buffer = (uint8_t*)av_malloc( numBytes * sizeof(uint8_t)); avpicture_fill( (AVPicture*)avFrameRGB, buffer, PIX_FMT_RGB24, image.width(), image.height( )); SwsContext* swsContext = sws_getContext( avCodecContext->width, avCodecContext->height, avCodecContext->pix_fmt, image.width(), image.height(), PIX_FMT_RGB24, SWS_FAST_BILINEAR, 0, 0, 0 ); // seek to 10% of movie time const int64_t den2 = videostream->time_base.den * videostream->r_frame_rate.den; const int64_t num2 = videostream->time_base.num * videostream->r_frame_rate.num; const int64_t num_frames = av_rescale( videostream->duration, num2, den2 ); const int64_t desiredTimestamp = videostream->start_time + av_rescale( num_frames / 10, den2, num2 ); if( avformat_seek_file( avFormatContext, streamIdx, 0, desiredTimestamp, desiredTimestamp, 0 ) != 0 ) { return; } AVPacket packet; while( av_read_frame( avFormatContext, &packet ) >= 0 ) { if( packet.stream_index != streamIdx ) continue; int frameFinished; avcodec_decode_video2( avCodecContext, avFrame, &frameFinished, &packet ); if( !frameFinished ) continue; sws_scale( swsContext, avFrame->data, avFrame->linesize, 0, avCodecContext->height, avFrameRGB->data, avFrameRGB->linesize ); unsigned char* src = (unsigned char*)avFrameRGB->data[0]; for( int y = 0; y < image.height(); ++y ) { QRgb* scanLine = (QRgb*)image.scanLine(y); for( int x = 0; x < image.width(); ++x ) scanLine[x] = qRgb(src[3*x], src[3*x+1], src[3*x+2]); src += avFrameRGB->linesize[0]; } av_free_packet( &packet ); image.setText( "source", fileName ); emit imageLoaded(index, image); break; } avformat_close_input( &avFormatContext ); sws_freeContext( swsContext ); av_free( avFrame ); av_free( avFrameRGB ); } <commit_msg>Fix initial size of items opened via Dock<commit_after>/*********************************************************************/ /* Copyright (c) 2013, EPFL/Blue Brain Project */ /* Raphael Dumusc <raphael.dumusc@epfl.ch> */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include "DockPixelStreamer.h" #include "Pictureflow.h" #include "Content.h" #include "ContentFactory.h" #include "ContentWindowManager.h" #include "MovieContent.h" #include "main.h" #include "PixelStreamSegmentJpegCompressor.h" #define DOCK_UNIQUE_URI "menu" namespace { QImage createSlideImage_( const QSize& size, const QString& fileName, const bool isDir, const QColor& bgcolor1, const QColor& bgcolor2 ) { QImage img( size, QImage::Format_RGB32 ); img.setText( "source", fileName ); if( isDir) img.setText( "dir", "true" ); QPainter painter( &img ); QPoint p1( img.width()*4/10, 0 ); QPoint p2( img.width()*6/10, img.height( )); QLinearGradient linearGrad( p1, p2 ); linearGrad.setColorAt( 0, bgcolor1 ); linearGrad.setColorAt( 1, bgcolor2 ); painter.setBrush(linearGrad); painter.fillRect( 0, 0, img.width(), img.height(), QBrush(linearGrad)); painter.end(); return img; } } QString DockPixelStreamer::getUniqueURI() { return QString(DOCK_UNIQUE_URI); } DockPixelStreamer::DockPixelStreamer(DisplayGroupManager *displayGroupManager) : LocalPixelStreamer(displayGroupManager, QString(DOCK_UNIQUE_URI)) , frameIndex_(0) { connect(this, SIGNAL(close(QString)), displayGroupManager, SLOT(deletePixelStream(QString))); av_register_all(); flow_ = new PictureFlow; flow_->resize( g_configuration->getTotalWidth()/8, g_configuration->getTotalHeight()/8 ); const int height = flow_->height() * .8; flow_->setSlideSize( QSize( 0.6 * height, height )); flow_->setBackgroundColor( Qt::darkGray ); connect( flow_, SIGNAL( imageUpdated( const QImage& )), this, SLOT( update( const QImage& ))); loader_ = new AsyncImageLoader(flow_->slideSize()); loader_->moveToThread( &loadThread_ ); connect( loader_, SIGNAL(imageLoaded(int, QImage)), flow_, SLOT(setSlide( int, QImage ))); connect( this, SIGNAL(renderPreview( const QString&, const int )), loader_, SLOT(loadImage( const QString&, const int ))); loadThread_.start(); changeDirectory( g_configuration->getDockStartDir( )); } DockPixelStreamer::~DockPixelStreamer() { loadThread_.quit(); loadThread_.wait(); delete flow_; delete loader_; } void DockPixelStreamer::updateInteractionState(InteractionState interactionState) { if (interactionState.type == InteractionState::EVT_CLICK) { // xPos is click position in (pixel) units inside the dock const int xPos = interactionState.mouseX * flow_->size().width(); // mid is half the width of the dock in (pixel) units const int dockHalfWidth = flow_->size().width() / 2; // SlideMid is half the slide width in pixels const int slideHalfWidth = flow_->slideSize().width() / 2; if( xPos > dockHalfWidth-slideHalfWidth && xPos < dockHalfWidth+slideHalfWidth ) { onItem(); } else { if( xPos > dockHalfWidth ) flow_->showNext(); else flow_->showPrevious(); } } else if (interactionState.type == InteractionState::EVT_MOVE || interactionState.type == InteractionState::EVT_WHEEL) { const int offs = interactionState.dx * flow_->size().width() / 4; flow_->showSlide( flow_->centerIndex() - offs ); } } void DockPixelStreamer::open() { flow_->triggerRender(); } void DockPixelStreamer::onItem() { const QImage& image = flow_->slide( flow_->centerIndex( )); const QString& source = image.text( "source" ); if( image.text( "dir" ).isEmpty( )) { const QString extension = QFileInfo(source).suffix().toLower(); if( extension == "dcx" ) { g_displayGroupManager->loadStateXMLFile( source.toStdString( )); emit(close(getUniqueURI())); } else { boost::shared_ptr< Content > c = ContentFactory::getContent( source ); if( c ) { boost::shared_ptr<ContentWindowManager> cwm(new ContentWindowManager(c)); g_displayGroupManager->addContentWindowManager( cwm ); cwm->adjustSize( SIZE_1TO1 ); emit(close(getUniqueURI())); } } } else { changeDirectory( source ); } } void DockPixelStreamer::update(const QImage& image) { PixelStreamSegment segment; segment.parameters = makeSegmentHeader(); // TODO remove this crappy compression when merging with Daniel's no-compression codebase computeSegmentJpeg(image, segment); ++frameIndex_; emit segmentUpdated(uri_, segment); } PixelStreamSegmentParameters DockPixelStreamer::makeSegmentHeader() { PixelStreamSegmentParameters parameters; parameters.sourceIndex = 0; parameters.frameIndex = frameIndex_; parameters.totalHeight = flow_->size().height(); parameters.totalWidth = flow_->size().width(); parameters.height = parameters.totalHeight; parameters.width = parameters.totalWidth; parameters.x = 0; parameters.y = 0; return parameters; } void DockPixelStreamer::changeDirectory( const QString& dir ) { slideIndex_[currentDir_.path()] = flow_->centerIndex(); flow_->clear(); currentDir_ = dir; currentDir_.setFilter( QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot ); QStringList filters = ContentFactory::getSupportedFilesFilter(); filters.append( "*.dcx" ); currentDir_.setNameFilters( filters ); const QFileInfoList& fileList = currentDir_.entryInfoList(); currentDir_.setFilter( QDir::Dirs | QDir::NoDotAndDotDot ); currentDir_.setNameFilters( QStringList( )); const QFileInfoList& dirList = currentDir_.entryInfoList(); QDir rootDir = dir; const bool hasRootDir = rootDir.cdUp(); if( hasRootDir) { QString upFolder = rootDir.path(); QImage img = createSlideImage_( flow_->slideSize(), upFolder, true, Qt::darkGray, Qt::lightGray ); flow_->addSlide( img, "UP: " + upFolder ); } for( int i = 0; i < fileList.size(); ++i ) { QFileInfo fileInfo = fileList.at( i ); const QString& fileName = currentDir_.absoluteFilePath( fileInfo.fileName( )); QImage img = createSlideImage_( flow_->slideSize(), fileName, false, Qt::black, Qt::white ); flow_->addSlide( img, fileInfo.fileName( )); emit renderPreview( fileName, flow_->slideCount( )); } for( int i = 0; i < dirList.size(); ++i ) { QFileInfo fileInfo = dirList.at( i ); const QString& fileName = currentDir_.absoluteFilePath( fileInfo.fileName( )); if( !fileName.endsWith( ".pyramid" )) { QImage img = createSlideImage_( flow_->slideSize(), fileName, true, Qt::black, Qt::white ); flow_->addSlide( img, fileInfo.fileName( )); } } flow_->setCenterIndex( slideIndex_[currentDir_.path()] ); } AsyncImageLoader::AsyncImageLoader(QSize defaultSize) : defaultSize_(defaultSize) { } void AsyncImageLoader::loadImage( const QString& fileName, const int index ) { const QString extension = QFileInfo(fileName).suffix().toLower(); if( extension == "dcx" ) { QImage image = createSlideImage_( defaultSize_, fileName, false, Qt::darkCyan, Qt::cyan ); emit imageLoaded(index, image); return; } if( extension == "pyr" ) { QImageReader reader( fileName + "amid/0.jpg" ); QImage image = reader.read(); image.setText( "source", fileName ); emit imageLoaded(index, image); return; } QImageReader reader( fileName ); if( reader.canRead( )) { QImage image = reader.read(); image.setText( "source", fileName ); emit imageLoaded(index, image); return; } else if( reader.error() != QImageReader::UnsupportedFormatError ) return; if( !MovieContent::getSupportedExtensions().contains( extension )) return; AVFormatContext* avFormatContext; if( avformat_open_input( &avFormatContext, fileName.toAscii(), 0, 0 ) != 0 ) return; if( avformat_find_stream_info( avFormatContext, 0 ) < 0 ) return; // find the first video stream int streamIdx = -1; for( unsigned int i = 0; i < avFormatContext->nb_streams; ++i ) { if( avFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ) { streamIdx = i; break; } } if( streamIdx == -1 ) return; AVStream* videostream = avFormatContext->streams[streamIdx]; AVCodecContext* avCodecContext = videostream->codec; AVCodec* codec = avcodec_find_decoder( avCodecContext->codec_id ); if( !codec ) return; if( avcodec_open2( avCodecContext, codec, 0 ) < 0 ) return; AVFrame* avFrame = avcodec_alloc_frame(); AVFrame* avFrameRGB = avcodec_alloc_frame(); QImage image( avCodecContext->width, avCodecContext->height, QImage::Format_RGB32 ); int numBytes = avpicture_get_size( PIX_FMT_RGB24, image.width(), image.height( )); uint8_t* buffer = (uint8_t*)av_malloc( numBytes * sizeof(uint8_t)); avpicture_fill( (AVPicture*)avFrameRGB, buffer, PIX_FMT_RGB24, image.width(), image.height( )); SwsContext* swsContext = sws_getContext( avCodecContext->width, avCodecContext->height, avCodecContext->pix_fmt, image.width(), image.height(), PIX_FMT_RGB24, SWS_FAST_BILINEAR, 0, 0, 0 ); // seek to 10% of movie time const int64_t den2 = videostream->time_base.den * videostream->r_frame_rate.den; const int64_t num2 = videostream->time_base.num * videostream->r_frame_rate.num; const int64_t num_frames = av_rescale( videostream->duration, num2, den2 ); const int64_t desiredTimestamp = videostream->start_time + av_rescale( num_frames / 10, den2, num2 ); if( avformat_seek_file( avFormatContext, streamIdx, 0, desiredTimestamp, desiredTimestamp, 0 ) != 0 ) { return; } AVPacket packet; while( av_read_frame( avFormatContext, &packet ) >= 0 ) { if( packet.stream_index != streamIdx ) continue; int frameFinished; avcodec_decode_video2( avCodecContext, avFrame, &frameFinished, &packet ); if( !frameFinished ) continue; sws_scale( swsContext, avFrame->data, avFrame->linesize, 0, avCodecContext->height, avFrameRGB->data, avFrameRGB->linesize ); unsigned char* src = (unsigned char*)avFrameRGB->data[0]; for( int y = 0; y < image.height(); ++y ) { QRgb* scanLine = (QRgb*)image.scanLine(y); for( int x = 0; x < image.width(); ++x ) scanLine[x] = qRgb(src[3*x], src[3*x+1], src[3*x+2]); src += avFrameRGB->linesize[0]; } av_free_packet( &packet ); image.setText( "source", fileName ); emit imageLoaded(index, image); break; } avformat_close_input( &avFormatContext ); sws_freeContext( swsContext ); av_free( avFrame ); av_free( avFrameRGB ); } <|endoftext|>
<commit_before>#include "NodeStyle.h" #if defined(Q_OS_WIN) static QString FontName = "Segoe UI"; #else static QString FontName = "DejaVu Sans"; #endif // Scene NodeStyle QColor NodeStyle::SceneBackground = QColor(64, 64, 64); QColor NodeStyle::SceneBlockedBackground = QColor(34, 34, 34); // Link NodeStyle QPen NodeStyle::LinkPen = QPen(QColor(222, 222, 222), 2.0, Qt::SolidLine); // TemporaryLink NodeStyle QPen NodeStyle::TemporaryLinkPen = QPen(QColor(244, 98, 0), 2.0, Qt::SolidLine); // Node NodeStyle QFont NodeStyle::NodeTitleFont = QFont(FontName, 11, QFont::Bold); QBrush NodeStyle::NodeTitleFontBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::NodeTitleBrush = QBrush(QColor(62, 62, 62)); QFont NodeStyle::NodeTypeNameFont = QFont(FontName, 8, QFont::Normal, true); QBrush NodeStyle::NodeTypeNameFontBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::NodeBrush = QBrush(QColor(37, 37, 37)); QPen NodeStyle::NodeBorderPen = QPen(QColor(88, 88, 88), 1.0, Qt::SolidLine); QPen NodeStyle::NodeBorderSelectedPen = QPen(QColor(128, 128, 128), 2.5, Qt::SolidLine); QPen NodeStyle::NodeBorderPreviewSelectedPen = QPen(QColor(119, 189, 255), 2.5, Qt::SolidLine); int NodeStyle::NodeRoundArc = 15; float NodeStyle::NodeTitleSize = 5.0; float NodeStyle::NodeTitleHorizontalMargin = 20.0; float NodeStyle::NodeTypeNameHorizontalMargin = 8.0; float NodeStyle::NodeSocketHorizontalMargin = -7.5; float NodeStyle::NodeSocketVerticalMargin = 8.0; float NodeStyle::NodeSocketsMargin = 20.0; QFont NodeStyle::NodeTimeInfoFont = QFont("Arial", 10); QBrush NodeStyle::NodeTimeInfoFontBrush = QBrush(QColor(204, 204, 204)); // Socket NodeStyle QBrush NodeStyle::SocketTitleBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::SocketTitleInactiveBrush = QBrush(QColor(119, 119, 119)); QFont NodeStyle::SocketFont = QFont(FontName, 9); // Connector NodeStyle QColor NodeStyle::SocketGradientStart1 = QColor(193, 171, 60); QColor NodeStyle::SocketGradientStop1 = QColor(99, 88, 34); QColor NodeStyle::SocketGradientStart2 = QColor(141, 139, 169); QColor NodeStyle::SocketGradientStop2 = QColor(61, 61, 108); QColor NodeStyle::SocketGradientStart3 = QColor(93, 93, 93); QColor NodeStyle::SocketGradientStop3 = QColor(57, 57, 57); QColor NodeStyle::SocketGradientStart4 = QColor(82, 165, 98); QColor NodeStyle::SocketGradientStop4 = QColor(40, 81, 47); QColor NodeStyle::SocketGradientStart5 = QColor(142, 84, 123); QColor NodeStyle::SocketGradientStop5 = QColor(84, 50, 73); QFont NodeStyle::SocketAnnotationFont = QFont("Segoe UI", 8, QFont::Light); QBrush NodeStyle::SocketAnnotationBrush = QBrush(QColor(244, 244, 224)); QPen NodeStyle::SocketPen = QPen(QColor(180, 180, 180), 1.0, Qt::SolidLine); QRect NodeStyle::SocketSize = QRect(0, 0, 15, 15); float NodeStyle::NodeSocketPenWidth = 1.0f; float NodeStyle::NodeSocketPenWidthHovered = 2.0f; int NodeStyle::ZValueNode = 100; int NodeStyle::ZValueNodeHovered = 200; int NodeStyle::ZValueLink = 0; int NodeStyle::ZValueTemporaryLink = 400; <commit_msg>lighten up scene background<commit_after>#include "NodeStyle.h" #if defined(Q_OS_WIN) static QString FontName = "Segoe UI"; #else static QString FontName = "DejaVu Sans"; #endif // Scene NodeStyle QColor NodeStyle::SceneBackground = QColor(104, 104, 104); QColor NodeStyle::SceneBlockedBackground = QColor(34, 34, 34); // Link NodeStyle QPen NodeStyle::LinkPen = QPen(QColor(222, 222, 222), 2.0, Qt::SolidLine); // TemporaryLink NodeStyle QPen NodeStyle::TemporaryLinkPen = QPen(QColor(244, 98, 0), 2.0, Qt::SolidLine); // Node NodeStyle QFont NodeStyle::NodeTitleFont = QFont(FontName, 11, QFont::Bold); QBrush NodeStyle::NodeTitleFontBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::NodeTitleBrush = QBrush(QColor(62, 62, 62)); QFont NodeStyle::NodeTypeNameFont = QFont(FontName, 8, QFont::Normal, true); QBrush NodeStyle::NodeTypeNameFontBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::NodeBrush = QBrush(QColor(37, 37, 37)); QPen NodeStyle::NodeBorderPen = QPen(QColor(88, 88, 88), 1.0, Qt::SolidLine); QPen NodeStyle::NodeBorderSelectedPen = QPen(QColor(128, 128, 128), 2.5, Qt::SolidLine); QPen NodeStyle::NodeBorderPreviewSelectedPen = QPen(QColor(119, 189, 255), 2.5, Qt::SolidLine); int NodeStyle::NodeRoundArc = 15; float NodeStyle::NodeTitleSize = 5.0; float NodeStyle::NodeTitleHorizontalMargin = 20.0; float NodeStyle::NodeTypeNameHorizontalMargin = 8.0; float NodeStyle::NodeSocketHorizontalMargin = -7.5; float NodeStyle::NodeSocketVerticalMargin = 8.0; float NodeStyle::NodeSocketsMargin = 20.0; QFont NodeStyle::NodeTimeInfoFont = QFont("Arial", 10); QBrush NodeStyle::NodeTimeInfoFontBrush = QBrush(QColor(204, 204, 204)); // Socket NodeStyle QBrush NodeStyle::SocketTitleBrush = QBrush(QColor(180, 180, 180)); QBrush NodeStyle::SocketTitleInactiveBrush = QBrush(QColor(119, 119, 119)); QFont NodeStyle::SocketFont = QFont(FontName, 9); // Connector NodeStyle QColor NodeStyle::SocketGradientStart1 = QColor(193, 171, 60); QColor NodeStyle::SocketGradientStop1 = QColor(99, 88, 34); QColor NodeStyle::SocketGradientStart2 = QColor(141, 139, 169); QColor NodeStyle::SocketGradientStop2 = QColor(61, 61, 108); QColor NodeStyle::SocketGradientStart3 = QColor(93, 93, 93); QColor NodeStyle::SocketGradientStop3 = QColor(57, 57, 57); QColor NodeStyle::SocketGradientStart4 = QColor(82, 165, 98); QColor NodeStyle::SocketGradientStop4 = QColor(40, 81, 47); QColor NodeStyle::SocketGradientStart5 = QColor(142, 84, 123); QColor NodeStyle::SocketGradientStop5 = QColor(84, 50, 73); QFont NodeStyle::SocketAnnotationFont = QFont("Segoe UI", 8, QFont::Light); QBrush NodeStyle::SocketAnnotationBrush = QBrush(QColor(244, 244, 224)); QPen NodeStyle::SocketPen = QPen(QColor(180, 180, 180), 1.0, Qt::SolidLine); QRect NodeStyle::SocketSize = QRect(0, 0, 15, 15); float NodeStyle::NodeSocketPenWidth = 1.0f; float NodeStyle::NodeSocketPenWidthHovered = 2.0f; int NodeStyle::ZValueNode = 100; int NodeStyle::ZValueNodeHovered = 200; int NodeStyle::ZValueLink = 0; int NodeStyle::ZValueTemporaryLink = 400; <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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, see <http://www.gnu.org/licenses/>. * */ #include "ContentList.h" #include "FilesystemContentLister.h" #include <QMimeDatabase> #include "BalooContentLister.h" struct ContentEntry { QString filename; QVariantHash metadata; }; class ContentList::Private { public: Private() : actualContentList(0) {} QList<ContentEntry*> entries; ContentListerBase* actualContentList; }; ContentList::ContentList(QObject* parent) : QAbstractListModel(parent) , d(new Private) { BalooContentLister* baloo = new BalooContentLister(this); if(baloo->balooEnabled()) { d->actualContentList = baloo; } else { baloo->deleteLater(); d->actualContentList = new FilesystemContentLister(this); } connect(d->actualContentList, SIGNAL(fileFound(QString,QVariantHash)), this, SLOT(fileFound(QString,QVariantHash))); connect(d->actualContentList, SIGNAL(searchCompleted()), this, SIGNAL(searchCompleted())); } ContentList::~ContentList() { delete d; } QString ContentList::getMimetype(QString filePath) { QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(filePath); return mime.name(); } void ContentList::addLocation(QString path) { d->actualContentList->addLocation(path); } void ContentList::addMimetype(QString mimetype) { d->actualContentList->addMimetype(mimetype); } void ContentList::setSearchString(const QString& searchString) { d->actualContentList->setSearchString(searchString); } void ContentList::startSearch() { d->actualContentList->startSearch(); } void ContentList::fileFound(const QString& filePath, const QVariantHash& metadata) { ContentEntry* entry = new ContentEntry(); entry->filename = filePath; entry->metadata = metadata; int newRow = d->entries.count(); beginInsertRows(QModelIndex(), newRow, newRow); d->entries.append(entry); endInsertRows(); } QHash<int, QByteArray> ContentList::roleNames() const { QHash<int, QByteArray> roles; roles[FilenameRole] = "filename"; roles[MetadataRole] = "metadata"; return roles; } QVariant ContentList::data(const QModelIndex& index, int role) const { QVariant result; if(index.isValid() && index.row() > -1 && index.row() < d->entries.count()) { const ContentEntry* entry = d->entries[index.row()]; switch(role) { case FilenameRole: result.setValue(entry->filename); break; case MetadataRole: result.setValue(entry->metadata); break; default: result.setValue(QString("Unknown role")); break; } } return result; } int ContentList::rowCount(const QModelIndex& parent) const { if(parent.isValid()) return 0; return d->entries.count(); } <commit_msg>Get a bit of debug on whether or not we use Baloo<commit_after>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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, see <http://www.gnu.org/licenses/>. * */ #include "ContentList.h" #include "FilesystemContentLister.h" #include "BalooContentLister.h" #include <QMimeDatabase> #include <QDebug> struct ContentEntry { QString filename; QVariantHash metadata; }; class ContentList::Private { public: Private() : actualContentList(0) {} QList<ContentEntry*> entries; ContentListerBase* actualContentList; }; ContentList::ContentList(QObject* parent) : QAbstractListModel(parent) , d(new Private) { BalooContentLister* baloo = new BalooContentLister(this); if(baloo->balooEnabled()) { d->actualContentList = baloo; qDebug() << "Baloo support enabled"; } else { baloo->deleteLater(); d->actualContentList = new FilesystemContentLister(this); qDebug() << "Baloo is disabled for the system, use the filesystem scraper"; } connect(d->actualContentList, SIGNAL(fileFound(QString,QVariantHash)), this, SLOT(fileFound(QString,QVariantHash))); connect(d->actualContentList, SIGNAL(searchCompleted()), this, SIGNAL(searchCompleted())); } ContentList::~ContentList() { delete d; } QString ContentList::getMimetype(QString filePath) { QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(filePath); return mime.name(); } void ContentList::addLocation(QString path) { d->actualContentList->addLocation(path); } void ContentList::addMimetype(QString mimetype) { d->actualContentList->addMimetype(mimetype); } void ContentList::setSearchString(const QString& searchString) { d->actualContentList->setSearchString(searchString); } void ContentList::startSearch() { d->actualContentList->startSearch(); } void ContentList::fileFound(const QString& filePath, const QVariantHash& metadata) { ContentEntry* entry = new ContentEntry(); entry->filename = filePath; entry->metadata = metadata; int newRow = d->entries.count(); beginInsertRows(QModelIndex(), newRow, newRow); d->entries.append(entry); endInsertRows(); } QHash<int, QByteArray> ContentList::roleNames() const { QHash<int, QByteArray> roles; roles[FilenameRole] = "filename"; roles[MetadataRole] = "metadata"; return roles; } QVariant ContentList::data(const QModelIndex& index, int role) const { QVariant result; if(index.isValid() && index.row() > -1 && index.row() < d->entries.count()) { const ContentEntry* entry = d->entries[index.row()]; switch(role) { case FilenameRole: result.setValue(entry->filename); break; case MetadataRole: result.setValue(entry->metadata); break; default: result.setValue(QString("Unknown role")); break; } } return result; } int ContentList::rowCount(const QModelIndex& parent) const { if(parent.isValid()) return 0; return d->entries.count(); } <|endoftext|>
<commit_before>#include "About.hpp" #include <QHBoxLayout> #include <QVBoxLayout> #include <QLabel> #include <QDialogButtonBox> #include <QEvent> #include <QPixmap> namespace GUI { namespace Dialogs { /** * Creates a new about dialog. * * @param parent Parent widget, the dialog will be centered above this widget if parent is * not null. */ About::About(QWidget *parent) : QDialog(parent) { this->verticalLayout = new QVBoxLayout(this); this->horizontalLayout = new QHBoxLayout; this->horizontalLayout->setSpacing(20); this->verticalLayout->addLayout(this->horizontalLayout); this->iconLabel = new QLabel(this); this->iconLabel->setPixmap(QPixmap(":/icons/fourinaline/128x128/application_icon.png")); this->horizontalLayout->addWidget(this->iconLabel); this->textLabel = new QLabel(this); this->textLabel->setWordWrap(true); this->textLabel->setOpenExternalLinks(true); this->horizontalLayout->addWidget(this->textLabel); this->buttonBox = new QDialogButtonBox(this); this->buttonBox->setOrientation(Qt::Horizontal); this->buttonBox->setStandardButtons(QDialogButtonBox::Close); this->verticalLayout->addWidget(this->buttonBox); this->connect(this->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); this->retranslateUI(); } /** * Frees all used resources. */ About::~About() { } /** * Retranslates all strings. */ void About::retranslateUI() { this->setWindowTitle(tr("About four in a line")); this->textLabel->setText(this->tr( "<h1>Four in a line</h1>" "<b>Copyright (c) 2014 David Greisler und Simon Mühlichen.</b>" "<p>Four in a line is a two-player game in which two players first select a color and then take turns dropping a token " "of their color from the top into a grid. The token falls straight down, occupying the " "lowest free cell in the grid. The first player who has four tokens in a row, either " "horizontally/vertically or diagonally, wins the game.</p>" "<p>It is possible to play the game with two human players, either locally or over the network, or with " "one human player playing against a computer player. When playing over the network, the players can " "communicate using an in-game chat. The number of won/lost/drawn games of each player are stored in " "a highscore list.</p>" "<p>The program was created within the scope of an assignment for the " "course MM-EMS.</p>" "<hr />" "Four in a line is free software and is distributed under the terms of the " "<a href=\"http://opensource.org/licenses/MIT\">MIT License</a>.</p>" "<p>This program uses some of the " "<a href=\"http://www.fatcow.com/free-icons\">Farm-Fresh Web Icons</a> " "from FatCow. " "They are licensed under a <a href=\"http://creativecommons.org/licenses/by/3.0/us/\">" "Creative Commons Attribution 3.0 License</a>. " "Some icons were modified.</p>" "<p>For more information see the README.md file.</p>" )); } /** * Retranslates strings when the application's language has been changed. * * @param event Change event. */ void About::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { this->retranslateUI(); } QDialog::changeEvent(event); } } } <commit_msg>Little fix.<commit_after>#include "About.hpp" #include <QHBoxLayout> #include <QVBoxLayout> #include <QLabel> #include <QDialogButtonBox> #include <QEvent> #include <QPixmap> namespace GUI { namespace Dialogs { /** * Creates a new about dialog. * * @param parent Parent widget, the dialog will be centered above this widget if parent is * not null. */ About::About(QWidget *parent) : QDialog(parent) { this->verticalLayout = new QVBoxLayout(this); this->horizontalLayout = new QHBoxLayout; this->horizontalLayout->setSpacing(20); this->verticalLayout->addLayout(this->horizontalLayout); this->iconLabel = new QLabel(this); this->iconLabel->setPixmap(QPixmap(":/icons/fourinaline/128x128/application_icon.png")); this->horizontalLayout->addWidget(this->iconLabel); this->textLabel = new QLabel(this); this->textLabel->setWordWrap(true); this->textLabel->setOpenExternalLinks(true); this->horizontalLayout->addWidget(this->textLabel); this->buttonBox = new QDialogButtonBox(this); this->buttonBox->setOrientation(Qt::Horizontal); this->buttonBox->setStandardButtons(QDialogButtonBox::Close); this->verticalLayout->addWidget(this->buttonBox); this->connect(this->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); this->retranslateUI(); } /** * Frees all used resources. */ About::~About() { } /** * Retranslates all strings. */ void About::retranslateUI() { this->setWindowTitle(this->tr("About four in a line")); this->textLabel->setText(this->tr( "<h1>Four in a line</h1>" "<b>Copyright (c) 2014 David Greisler und Simon Mühlichen.</b>" "<p>Four in a line is a two-player game in which two players first select a color and then take turns dropping a token " "of their color from the top into a grid. The token falls straight down, occupying the " "lowest free cell in the grid. The first player who has four tokens in a row, either " "horizontally/vertically or diagonally, wins the game.</p>" "<p>It is possible to play the game with two human players, either locally or over the network, or with " "one human player playing against a computer player. When playing over the network, the players can " "communicate using an in-game chat. The number of won/lost/drawn games of each player are stored in " "a highscore list.</p>" "<p>The program was created within the scope of an assignment for the " "course MM-EMS.</p>" "<hr />" "Four in a line is free software and is distributed under the terms of the " "<a href=\"http://opensource.org/licenses/MIT\">MIT License</a>.</p>" "<p>This program uses some of the " "<a href=\"http://www.fatcow.com/free-icons\">Farm-Fresh Web Icons</a> " "from FatCow. " "They are licensed under a <a href=\"http://creativecommons.org/licenses/by/3.0/us/\">" "Creative Commons Attribution 3.0 License</a>. " "Some icons were modified.</p>" "<p>For more information see the README.md file.</p>" )); } /** * Retranslates strings when the application's language has been changed. * * @param event Change event. */ void About::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { this->retranslateUI(); } QDialog::changeEvent(event); } } } <|endoftext|>
<commit_before> #include "CPipelineState.h" #include <GL/glew.h> namespace ion { namespace Graphics { namespace GL { void CPipelineState::SetProgram(IShaderProgram * inShaderProgram) { ShaderProgram = dynamic_cast<CShaderProgram *>(inShaderProgram); Loaded = false; } void CPipelineState::SetVertexBuffer(IVertexBuffer * inVertexBuffer) { VertexBuffer = dynamic_cast<CVertexBuffer *>(inVertexBuffer); // Bound VBOs are not part of VAO state Loaded = false; } void CPipelineState::SetIndexBuffer(IIndexBuffer * inIndexBuffer) { IndexBuffer = dynamic_cast<CIndexBuffer *>(inIndexBuffer); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer->Handle)); CheckedGLCall(glBindVertexArray(0)); Loaded = false; } void CPipelineState::Load() { if (! ShaderProgram->Linked) { ShaderProgram->Link(); } CheckedGLCall(glUseProgram(ShaderProgram->Handle)); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer->Handle)); size_t CurrentOffset = 0; for (auto & InputLayoutElement : ShaderProgram->InputLayout) { int AttributeLocation = -1; CheckedGLCall(AttributeLocation = glGetAttribLocation(ShaderProgram->Handle, InputLayoutElement.Name.c_str())); // BUGBUG Get this through reflection? CheckedGLCall(glEnableVertexAttribArray(AttributeLocation)); CheckedGLCall(glVertexAttribPointer(AttributeLocation, InputLayoutElement.Components, GL_FLOAT, GL_FALSE, 0, (void *) CurrentOffset)); CurrentOffset += sizeof(float) * InputLayoutElement.Components; } CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); // Remember, VBOs are not part of VAO state CheckedGLCall(glBindVertexArray(0)); CheckedGLCall(glUseProgram(0)); Loaded = true; } } } } <commit_msg>Calculate VBO offsets properly<commit_after> #include "CPipelineState.h" #include <GL/glew.h> namespace ion { namespace Graphics { namespace GL { void CPipelineState::SetProgram(IShaderProgram * inShaderProgram) { ShaderProgram = dynamic_cast<CShaderProgram *>(inShaderProgram); Loaded = false; } void CPipelineState::SetVertexBuffer(IVertexBuffer * inVertexBuffer) { VertexBuffer = dynamic_cast<CVertexBuffer *>(inVertexBuffer); // Bound VBOs are not part of VAO state Loaded = false; } void CPipelineState::SetIndexBuffer(IIndexBuffer * inIndexBuffer) { IndexBuffer = dynamic_cast<CIndexBuffer *>(inIndexBuffer); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer->Handle)); CheckedGLCall(glBindVertexArray(0)); Loaded = false; } void CPipelineState::Load() { if (! ShaderProgram->Linked) { ShaderProgram->Link(); } CheckedGLCall(glUseProgram(ShaderProgram->Handle)); CheckedGLCall(glBindVertexArray(VertexArrayHandle)); CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer->Handle)); size_t TotalStride = 0; for (auto & InputLayoutElement : ShaderProgram->InputLayout) { TotalStride += GetValueTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } size_t CurrentOffset = 0; for (auto & InputLayoutElement : ShaderProgram->InputLayout) { int AttributeLocation = -1; CheckedGLCall(AttributeLocation = glGetAttribLocation(ShaderProgram->Handle, InputLayoutElement.Name.c_str())); // BUGBUG Get this through reflection? CheckedGLCall(glEnableVertexAttribArray(AttributeLocation)); CheckedGLCall(glVertexAttribPointer( AttributeLocation, InputLayoutElement.Components, GetValueTypeOpenGLEnum(InputLayoutElement.Type), GL_FALSE, (int) TotalStride, (void *) CurrentOffset)); CurrentOffset += GetValueTypeSize(InputLayoutElement.Type) * InputLayoutElement.Components; } CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); // Remember, VBOs are not part of VAO state CheckedGLCall(glBindVertexArray(0)); CheckedGLCall(glUseProgram(0)); Loaded = true; } } } } <|endoftext|>
<commit_before>// system includes #include <stdexcept> #include <cassert> #include <iomanip> #include <cstdio> // stl includes #include <iostream> #include <sstream> #include <iterator> // Qt includes #include <QResource> #include <QDateTime> // hyperion util includes #include "hyperion/ImageProcessorFactory.h" #include "hyperion/ImageProcessor.h" #include "utils/ColorRgb.h" // project includes #include "BoblightClientConnection.h" BoblightClientConnection::BoblightClientConnection(QTcpSocket *socket, Hyperion * hyperion) : QObject(), _locale(QLocale::C), _socket(socket), _imageProcessor(ImageProcessorFactory::getInstance().newImageProcessor()), _hyperion(hyperion), _receiveBuffer(), _priority(255), _ledColors(hyperion->getLedCount(), ColorRgb::BLACK) { // initalize the locale. Start with the default C-locale _locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator); // connect internal signals and slots connect(_socket, SIGNAL(disconnected()), this, SLOT(socketClosed())); connect(_socket, SIGNAL(readyRead()), this, SLOT(readData())); } BoblightClientConnection::~BoblightClientConnection() { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); _priority = 255; } delete _socket; } void BoblightClientConnection::readData() { _receiveBuffer += _socket->readAll(); int bytes = _receiveBuffer.indexOf('\n') + 1; while(bytes > 0) { // create message string (strip the newline) QString message = QString::fromAscii(_receiveBuffer.data(), bytes-1); // remove message data from buffer _receiveBuffer = _receiveBuffer.mid(bytes); // handle message handleMessage(message); // drop messages if the buffer is too full if (_receiveBuffer.size() > 100*1024) { std::cout << "Boblight server drops messages" << std::endl; _receiveBuffer.clear(); } // try too look up '\n' again bytes = _receiveBuffer.indexOf('\n') + 1; } } void BoblightClientConnection::socketClosed() { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); _priority = 255; } emit connectionClosed(this); } void BoblightClientConnection::handleMessage(const QString & message) { //std::cout << "boblight message: " << message.toStdString() << std::endl; QStringList messageParts = message.split(" ", QString::SkipEmptyParts); if (messageParts.size() > 0) { if (messageParts[0] == "hello") { sendMessage("hello\n"); return; } else if (messageParts[0] == "ping") { sendMessage("ping 1\n"); return; } else if (messageParts[0] == "get" && messageParts.size() > 1) { if (messageParts[1] == "version") { sendMessage("version 5\n"); return; } else if (messageParts[1] == "lights") { sendLightMessage(); return; } } else if (messageParts[0] == "set" && messageParts.size() > 2) { if (messageParts.size() > 3 && messageParts[1] == "light") { bool rc; unsigned ledIndex = messageParts[2].toUInt(&rc); if (rc && ledIndex < _ledColors.size()) { if (messageParts[3] == "rgb" && messageParts.size() == 7) { bool rc1, rc2, rc3; uint8_t red = qMax(0, qMin(255, int(255 * messageParts[4].toFloat(&rc1)))); if (!rc1) { // maybe a locale issue. switch to a locale with a comma instead of a dot as decimal seperator (or vice versa) _locale = QLocale((_locale.decimalPoint() == QChar('.')) ? QLocale::Dutch : QLocale::C); _locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator); // try again red = qMax(0, qMin(255, int(255 * messageParts[4].toFloat(&rc1)))); } uint8_t green = qMax(0, qMin(255, int(255 * messageParts[5].toFloat(&rc2)))); uint8_t blue = qMax(0, qMin(255, int(255 * messageParts[6].toFloat(&rc3)))); if (rc1 && rc2 && rc3) { ColorRgb & rgb = _ledColors[ledIndex]; rgb.red = red; rgb.green = green; rgb.blue = blue; // send current color values to hyperion if this is the last led assuming leds values are send in order of id if ((ledIndex == _ledColors.size() -1) && _priority < 255) { _hyperion->setColors(_priority, _ledColors, -1); } return; } } else if(messageParts[3] == "speed" || messageParts[3] == "interpolation" || messageParts[3] == "use" || messageParts[3] == "singlechange") { // these message are ignored by Hyperion return; } } } else if (messageParts.size() == 3 && messageParts[1] == "priority") { bool rc; int prio = messageParts[2].toInt(&rc); if (rc && prio != _priority) { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); } _priority = prio; return; } } } else if (messageParts[0] == "sync") { // send current color values to hyperion if (_priority < 255) { _hyperion->setColors(_priority, _ledColors, -1); } return; } } std::cout << "unknown boblight message: " << message.toStdString() << std::endl; } void BoblightClientConnection::sendMessage(const std::string & message) { //std::cout << "send boblight message: " << message; _socket->write(message.c_str(), message.size()); } void BoblightClientConnection::sendMessage(const char * message, int size) { //std::cout << "send boblight message: " << std::string(message, size); _socket->write(message, size); } void BoblightClientConnection::sendLightMessage() { char buffer[256]; int n = snprintf(buffer, sizeof(buffer), "lights %d\n", _hyperion->getLedCount()); sendMessage(buffer, n); for (unsigned i = 0; i < _hyperion->getLedCount(); ++i) { double h0, h1, v0, v1; _imageProcessor->getScanParameters(i, h0, h1, v0, v1); n = snprintf(buffer, sizeof(buffer), "light %03d scan %f %f %f %f\n", i, 100*v0, 100*v1, 100*h0, 100*h1); sendMessage(buffer, n); } } <commit_msg>always work with trimmed messages<commit_after>// system includes #include <stdexcept> #include <cassert> #include <iomanip> #include <cstdio> // stl includes #include <iostream> #include <sstream> #include <iterator> // Qt includes #include <QResource> #include <QDateTime> // hyperion util includes #include "hyperion/ImageProcessorFactory.h" #include "hyperion/ImageProcessor.h" #include "utils/ColorRgb.h" // project includes #include "BoblightClientConnection.h" BoblightClientConnection::BoblightClientConnection(QTcpSocket *socket, Hyperion * hyperion) : QObject(), _locale(QLocale::C), _socket(socket), _imageProcessor(ImageProcessorFactory::getInstance().newImageProcessor()), _hyperion(hyperion), _receiveBuffer(), _priority(255), _ledColors(hyperion->getLedCount(), ColorRgb::BLACK) { // initalize the locale. Start with the default C-locale _locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator); // connect internal signals and slots connect(_socket, SIGNAL(disconnected()), this, SLOT(socketClosed())); connect(_socket, SIGNAL(readyRead()), this, SLOT(readData())); } BoblightClientConnection::~BoblightClientConnection() { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); _priority = 255; } delete _socket; } void BoblightClientConnection::readData() { _receiveBuffer += _socket->readAll(); int bytes = _receiveBuffer.indexOf('\n') + 1; while(bytes > 0) { // create message string (strip the newline) QString message = QString::fromAscii(_receiveBuffer.data(), bytes-1); // remove message data from buffer _receiveBuffer = _receiveBuffer.mid(bytes); // handle trimmed message handleMessage(message.trimmed()); // drop messages if the buffer is too full if (_receiveBuffer.size() > 100*1024) { std::cout << "Boblight server drops messages" << std::endl; _receiveBuffer.clear(); } // try too look up '\n' again bytes = _receiveBuffer.indexOf('\n') + 1; } } void BoblightClientConnection::socketClosed() { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); _priority = 255; } emit connectionClosed(this); } void BoblightClientConnection::handleMessage(const QString & message) { //std::cout << "boblight message: " << message.toStdString() << std::endl; QStringList messageParts = message.split(" ", QString::SkipEmptyParts); if (messageParts.size() > 0) { if (messageParts[0] == "hello") { sendMessage("hello\n"); return; } else if (messageParts[0] == "ping") { sendMessage("ping 1\n"); return; } else if (messageParts[0] == "get" && messageParts.size() > 1) { if (messageParts[1] == "version") { sendMessage("version 5\n"); return; } else if (messageParts[1] == "lights") { sendLightMessage(); return; } } else if (messageParts[0] == "set" && messageParts.size() > 2) { if (messageParts.size() > 3 && messageParts[1] == "light") { bool rc; unsigned ledIndex = messageParts[2].toUInt(&rc); if (rc && ledIndex < _ledColors.size()) { if (messageParts[3] == "rgb" && messageParts.size() == 7) { bool rc1, rc2, rc3; uint8_t red = qMax(0, qMin(255, int(255 * messageParts[4].toFloat(&rc1)))); if (!rc1) { // maybe a locale issue. switch to a locale with a comma instead of a dot as decimal seperator (or vice versa) _locale = QLocale((_locale.decimalPoint() == QChar('.')) ? QLocale::Dutch : QLocale::C); _locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator); // try again red = qMax(0, qMin(255, int(255 * messageParts[4].toFloat(&rc1)))); } uint8_t green = qMax(0, qMin(255, int(255 * messageParts[5].toFloat(&rc2)))); uint8_t blue = qMax(0, qMin(255, int(255 * messageParts[6].toFloat(&rc3)))); if (rc1 && rc2 && rc3) { ColorRgb & rgb = _ledColors[ledIndex]; rgb.red = red; rgb.green = green; rgb.blue = blue; // send current color values to hyperion if this is the last led assuming leds values are send in order of id if ((ledIndex == _ledColors.size() -1) && _priority < 255) { _hyperion->setColors(_priority, _ledColors, -1); } return; } } else if(messageParts[3] == "speed" || messageParts[3] == "interpolation" || messageParts[3] == "use" || messageParts[3] == "singlechange") { // these message are ignored by Hyperion return; } } } else if (messageParts.size() == 3 && messageParts[1] == "priority") { bool rc; int prio = messageParts[2].toInt(&rc); if (rc && prio != _priority) { if (_priority < 255) { // clear the current channel _hyperion->clear(_priority); } _priority = prio; return; } } } else if (messageParts[0] == "sync") { // send current color values to hyperion if (_priority < 255) { _hyperion->setColors(_priority, _ledColors, -1); } return; } } std::cout << "unknown boblight message: " << message.toStdString() << std::endl; } void BoblightClientConnection::sendMessage(const std::string & message) { //std::cout << "send boblight message: " << message; _socket->write(message.c_str(), message.size()); } void BoblightClientConnection::sendMessage(const char * message, int size) { //std::cout << "send boblight message: " << std::string(message, size); _socket->write(message, size); } void BoblightClientConnection::sendLightMessage() { char buffer[256]; int n = snprintf(buffer, sizeof(buffer), "lights %d\n", _hyperion->getLedCount()); sendMessage(buffer, n); for (unsigned i = 0; i < _hyperion->getLedCount(); ++i) { double h0, h1, v0, v1; _imageProcessor->getScanParameters(i, h0, h1, v0, v1); n = snprintf(buffer, sizeof(buffer), "light %03d scan %f %f %f %f\n", i, 100*v0, 100*v1, 100*h0, 100*h1); sendMessage(buffer, n); } } <|endoftext|>
<commit_before>#ifdef WIN32 #include "Socket.hpp" int Socket::socket(int domain, int type, int protocol) { return (socket(domain, type, protocol)); } int Socket::connect(int sockfd, const void *addr, int addrlen) { return (connect(sockfd, addr, addrlen)); } int Socket::send(int sockfd, const void *buf, int len, int flags) { return (send(sockfd, (const char *)buf, len, flags)); } int Socket::receive(int sockfd, void *buf, int len, int flags) { return (receive(sockfd, (char *)buf, len, flags)); } int Socket::bind(int sockfd, const void *addr, int addrlen) { return (bind(sockfd, addr, addrlen)); } int Socket::listen(int sockfd, int backlog) { return (listen(sockfd, backlog)); } int Socket::accept(int sockfd, void *addr, int *addrlen) { return (accept(sockfd, addr, addrlen)); } int Socket::close(int sockfd) { return (close(sockfd)); } #endif<commit_msg>Socket Win commit<commit_after>#ifdef WIN32 #include "Socket.hpp" int Socket::socket(int domain, int type, int protocol) { return (socket(domain, type, protocol)); } int Socket::connect(int sockfd, const void *addr, int addrlen) { return (connect(sockfd, addr, addrlen)); } int Socket::send(int sockfd, const void *buf, int len, int flags) { return (send(sockfd, (const char *)buf, len, flags)); } int Socket::receive(int sockfd, void *buf, int len, int flags) { return (receive(sockfd, (char *)buf, len, flags)); } int Socket::bind(int sockfd, const void *addr, int addrlen) { return (bind(sockfd, addr, addrlen)); } int Socket::listen(int sockfd, int backlog) { return (listen(sockfd, backlog)); } int Socket::accept(int sockfd, void *addr, int *addrlen) { return (accept(sockfd, addr, addrlen)); } int Socket::close(int sockfd) { return (close(sockfd)); } #endif <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QString> #include <QStringList> #include <QByteArray> #include <QVariant> #include <MDebug> #include "mgconfitem.h" #include <gconf/gconf-value.h> #include <gconf/gconf-client.h> struct MGConfItemPrivate { QString key; QVariant value; guint notify_id; bool have_gconf; static void notify_trampoline(GConfClient *, guint, GConfEntry *, gpointer); }; /* We get the default client and never release it, on purpose, to avoid disconnecting from the GConf daemon when a program happens to not have any GConfItems for short periods of time. */ static GConfClient * get_gconf_client () { static bool initialized = false; static GConfClient *client; if (initialized) return client; g_type_init (); client = gconf_client_get_default(); initialized = true; return client; } #define withClient(c) for (GConfClient *c = get_gconf_client (); c; c = NULL) static QByteArray convertKey(const QString &key) { if (key.startsWith('/')) return key.toUtf8(); else { QString replaced = key; replaced.replace('.', '/'); mWarning("mgconfitem.cpp") << "Using dot-separated key names with MGConfItem is deprecated."; mWarning("mgconfitem.cpp") << "Please use" << '/' + replaced << "instead of" << key; return '/' + replaced.toUtf8(); } } static QString convertKey(const char *key) { return QString::fromUtf8(key); } static QVariant convertValue(GConfValue *src) { if (!src) { return QVariant(); } else { switch (src->type) { case GCONF_VALUE_INVALID: return QVariant(QVariant::Invalid); case GCONF_VALUE_BOOL: return QVariant((bool)gconf_value_get_bool(src)); case GCONF_VALUE_INT: return QVariant(gconf_value_get_int(src)); case GCONF_VALUE_FLOAT: return QVariant(gconf_value_get_float(src)); case GCONF_VALUE_STRING: return QVariant(QString::fromUtf8(gconf_value_get_string(src))); case GCONF_VALUE_LIST: switch (gconf_value_get_list_type(src)) { case GCONF_VALUE_STRING: { QStringList result; for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next) result.append(QString::fromUtf8(gconf_value_get_string((GConfValue *)elts->data))); return QVariant(result); } default: { QList<QVariant> result; for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next) result.append(convertValue((GConfValue *)elts->data)); return QVariant(result); } } case GCONF_VALUE_SCHEMA: default: return QVariant(); } } } static GConfValue *convertString(const QString &str) { GConfValue *v = gconf_value_new(GCONF_VALUE_STRING); gconf_value_set_string(v, str.toUtf8().data()); return v; } static GConfValueType primitiveType(const QVariant &elt) { switch (elt.type()) { case QVariant::String: return GCONF_VALUE_STRING; case QVariant::Int: return GCONF_VALUE_INT; case QVariant::Double: return GCONF_VALUE_FLOAT; case QVariant::Bool: return GCONF_VALUE_BOOL; default: return GCONF_VALUE_INVALID; } } static GConfValueType uniformType(const QList<QVariant> &list) { GConfValueType result = GCONF_VALUE_INVALID; foreach(const QVariant & elt, list) { GConfValueType elt_type = primitiveType(elt); if (elt_type == GCONF_VALUE_INVALID) return GCONF_VALUE_INVALID; if (result == GCONF_VALUE_INVALID) result = elt_type; else if (result != elt_type) return GCONF_VALUE_INVALID; } if (result == GCONF_VALUE_INVALID) return GCONF_VALUE_STRING; // empty list. else return result; } static int convertValue(const QVariant &src, GConfValue **valp) { GConfValue *v; switch (src.type()) { case QVariant::Invalid: v = NULL; break; case QVariant::Bool: v = gconf_value_new(GCONF_VALUE_BOOL); gconf_value_set_bool(v, src.toBool()); break; case QVariant::Int: v = gconf_value_new(GCONF_VALUE_INT); gconf_value_set_int(v, src.toInt()); break; case QVariant::Double: v = gconf_value_new(GCONF_VALUE_FLOAT); gconf_value_set_float(v, src.toDouble()); break; case QVariant::String: v = convertString(src.toString()); break; case QVariant::StringList: { GSList *elts = NULL; v = gconf_value_new(GCONF_VALUE_LIST); gconf_value_set_list_type(v, GCONF_VALUE_STRING); foreach(const QString & str, src.toStringList()) elts = g_slist_prepend(elts, convertString(str)); gconf_value_set_list_nocopy(v, g_slist_reverse(elts)); break; } case QVariant::List: { GConfValueType elt_type = uniformType(src.toList()); if (elt_type == GCONF_VALUE_INVALID) v = NULL; else { GSList *elts = NULL; v = gconf_value_new(GCONF_VALUE_LIST); gconf_value_set_list_type(v, elt_type); foreach(const QVariant & elt, src.toList()) { GConfValue *val = NULL; convertValue(elt, &val); // guaranteed to succeed. elts = g_slist_prepend(elts, val); } gconf_value_set_list_nocopy(v, g_slist_reverse(elts)); } break; } default: return 0; } *valp = v; return 1; } void MGConfItemPrivate::notify_trampoline(GConfClient *, guint, GConfEntry *, gpointer data) { MGConfItem *item = (MGConfItem *)data; item->update_value(true); } void MGConfItem::update_value(bool emit_signal) { QVariant new_value; withClient(client) { GError *error = NULL; QByteArray k = convertKey(priv->key); GConfValue *v = gconf_client_get(client, k.data(), &error); if (error) { mWarning("MGConfItem") << error->message; g_error_free(error); new_value = priv->value; } else { new_value = convertValue(v); if (v) gconf_value_free(v); } } if (new_value != priv->value) { priv->value = new_value; if (emit_signal) emit valueChanged(); } } QString MGConfItem::key() const { return priv->key; } QVariant MGConfItem::value() const { return priv->value; } QVariant MGConfItem::value(const QVariant &def) const { if (priv->value.isNull()) return def; else return priv->value; } void MGConfItem::set(const QVariant &val) { withClient(client) { QByteArray k = convertKey(priv->key); GConfValue *v; if (convertValue(val, &v)) { GError *error = NULL; if (v) { gconf_client_set(client, k.data(), v, &error); gconf_value_free(v); } else { gconf_client_unset(client, k.data(), &error); } if (error) { mWarning("MGConfItem") << error->message; g_error_free(error); } else if (priv->value != val) { priv->value = val; emit valueChanged(); } } else mWarning("MGConfItem") << "Can't store a" << val.typeName(); } } void MGConfItem::unset() { set(QVariant()); } QList<QString> MGConfItem::listDirs() const { QList<QString> children; withClient(client) { QByteArray k = convertKey(priv->key); GError *error = NULL; GSList *dirs = gconf_client_all_dirs(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return children; } for (GSList *d = dirs; d; d = d->next) { children.append(convertKey((char *)d->data)); g_free(d->data); } g_slist_free(dirs); } return children; } QList<QString> MGConfItem::listEntries() const { QList<QString> children; withClient(client) { QByteArray k = convertKey(priv->key); GError *error = NULL; GSList *entries = gconf_client_all_entries(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return children; } for (GSList *e = entries; e; e = e->next) { children.append(convertKey(((GConfEntry *)e->data)->key)); gconf_entry_free((GConfEntry *)e->data); } g_slist_free(entries); } return children; } MGConfItem::MGConfItem(const QString &key, QObject *parent) : QObject(parent) { priv = new MGConfItemPrivate; priv->key = key; priv->notify_id = 0; withClient(client) { update_value(false); QByteArray k = convertKey(priv->key); GError *error = NULL; gconf_client_add_dir(client, k.data(), GCONF_CLIENT_PRELOAD_ONELEVEL, &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); priv->have_gconf = false; return; } priv->notify_id = gconf_client_notify_add(client, k.data(), MGConfItemPrivate::notify_trampoline, this, NULL, &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); priv->have_gconf = false; return; } } priv->have_gconf = true; } MGConfItem::~MGConfItem() { if(priv->have_gconf) { withClient(client) { QByteArray k = convertKey(priv->key); gconf_client_notify_remove(client, priv->notify_id); GError *error = NULL; gconf_client_remove_dir(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return; } } } delete priv; } <commit_msg>Fixes: NB#172648 - Slow startup performance when using MGConfItem<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QString> #include <QStringList> #include <QByteArray> #include <QVariant> #include <MDebug> #include "mgconfitem.h" #include <gconf/gconf-value.h> #include <gconf/gconf-client.h> struct MGConfItemPrivate { MGConfItemPrivate() : notify_id(0), have_gconf(false) {} QString key; QVariant value; guint notify_id; bool have_gconf; static void notify_trampoline(GConfClient *, guint, GConfEntry *, gpointer); }; /* We get the default client and never release it, on purpose, to avoid disconnecting from the GConf daemon when a program happens to not have any GConfItems for short periods of time. */ static GConfClient * get_gconf_client () { static bool initialized = false; static GConfClient *client; if (initialized) return client; g_type_init (); client = gconf_client_get_default(); initialized = true; return client; } #define withClient(c) for (GConfClient *c = get_gconf_client (); c; c = NULL) static QByteArray convertKey(const QString &key) { if (key.startsWith('/')) return key.toUtf8(); else { QString replaced = key; replaced.replace('.', '/'); mWarning("mgconfitem.cpp") << "Using dot-separated key names with MGConfItem is deprecated."; mWarning("mgconfitem.cpp") << "Please use" << '/' + replaced << "instead of" << key; return '/' + replaced.toUtf8(); } } static QString convertKey(const char *key) { return QString::fromUtf8(key); } static QVariant convertValue(GConfValue *src) { if (!src) { return QVariant(); } else { switch (src->type) { case GCONF_VALUE_INVALID: return QVariant(QVariant::Invalid); case GCONF_VALUE_BOOL: return QVariant((bool)gconf_value_get_bool(src)); case GCONF_VALUE_INT: return QVariant(gconf_value_get_int(src)); case GCONF_VALUE_FLOAT: return QVariant(gconf_value_get_float(src)); case GCONF_VALUE_STRING: return QVariant(QString::fromUtf8(gconf_value_get_string(src))); case GCONF_VALUE_LIST: switch (gconf_value_get_list_type(src)) { case GCONF_VALUE_STRING: { QStringList result; for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next) result.append(QString::fromUtf8(gconf_value_get_string((GConfValue *)elts->data))); return QVariant(result); } default: { QList<QVariant> result; for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next) result.append(convertValue((GConfValue *)elts->data)); return QVariant(result); } } case GCONF_VALUE_SCHEMA: default: return QVariant(); } } } static GConfValue *convertString(const QString &str) { GConfValue *v = gconf_value_new(GCONF_VALUE_STRING); gconf_value_set_string(v, str.toUtf8().data()); return v; } static GConfValueType primitiveType(const QVariant &elt) { switch (elt.type()) { case QVariant::String: return GCONF_VALUE_STRING; case QVariant::Int: return GCONF_VALUE_INT; case QVariant::Double: return GCONF_VALUE_FLOAT; case QVariant::Bool: return GCONF_VALUE_BOOL; default: return GCONF_VALUE_INVALID; } } static GConfValueType uniformType(const QList<QVariant> &list) { GConfValueType result = GCONF_VALUE_INVALID; foreach(const QVariant & elt, list) { GConfValueType elt_type = primitiveType(elt); if (elt_type == GCONF_VALUE_INVALID) return GCONF_VALUE_INVALID; if (result == GCONF_VALUE_INVALID) result = elt_type; else if (result != elt_type) return GCONF_VALUE_INVALID; } if (result == GCONF_VALUE_INVALID) return GCONF_VALUE_STRING; // empty list. else return result; } static int convertValue(const QVariant &src, GConfValue **valp) { GConfValue *v; switch (src.type()) { case QVariant::Invalid: v = NULL; break; case QVariant::Bool: v = gconf_value_new(GCONF_VALUE_BOOL); gconf_value_set_bool(v, src.toBool()); break; case QVariant::Int: v = gconf_value_new(GCONF_VALUE_INT); gconf_value_set_int(v, src.toInt()); break; case QVariant::Double: v = gconf_value_new(GCONF_VALUE_FLOAT); gconf_value_set_float(v, src.toDouble()); break; case QVariant::String: v = convertString(src.toString()); break; case QVariant::StringList: { GSList *elts = NULL; v = gconf_value_new(GCONF_VALUE_LIST); gconf_value_set_list_type(v, GCONF_VALUE_STRING); foreach(const QString & str, src.toStringList()) elts = g_slist_prepend(elts, convertString(str)); gconf_value_set_list_nocopy(v, g_slist_reverse(elts)); break; } case QVariant::List: { GConfValueType elt_type = uniformType(src.toList()); if (elt_type == GCONF_VALUE_INVALID) v = NULL; else { GSList *elts = NULL; v = gconf_value_new(GCONF_VALUE_LIST); gconf_value_set_list_type(v, elt_type); foreach(const QVariant & elt, src.toList()) { GConfValue *val = NULL; convertValue(elt, &val); // guaranteed to succeed. elts = g_slist_prepend(elts, val); } gconf_value_set_list_nocopy(v, g_slist_reverse(elts)); } break; } default: return 0; } *valp = v; return 1; } void MGConfItemPrivate::notify_trampoline(GConfClient *, guint, GConfEntry *, gpointer data) { MGConfItem *item = (MGConfItem *)data; item->update_value(true); } void MGConfItem::update_value(bool emit_signal) { QVariant new_value; withClient(client) { GError *error = NULL; QByteArray k = convertKey(priv->key); GConfValue *v = gconf_client_get(client, k.data(), &error); if (error) { mWarning("MGConfItem") << error->message; g_error_free(error); new_value = priv->value; } else { new_value = convertValue(v); if (v) gconf_value_free(v); } } if (new_value != priv->value) { priv->value = new_value; if (emit_signal) emit valueChanged(); } } QString MGConfItem::key() const { return priv->key; } QVariant MGConfItem::value() const { return priv->value; } QVariant MGConfItem::value(const QVariant &def) const { if (priv->value.isNull()) return def; else return priv->value; } void MGConfItem::set(const QVariant &val) { withClient(client) { QByteArray k = convertKey(priv->key); GConfValue *v; if (convertValue(val, &v)) { GError *error = NULL; if (v) { gconf_client_set(client, k.data(), v, &error); gconf_value_free(v); } else { gconf_client_unset(client, k.data(), &error); } if (error) { mWarning("MGConfItem") << error->message; g_error_free(error); } else if (priv->value != val) { priv->value = val; emit valueChanged(); } } else mWarning("MGConfItem") << "Can't store a" << val.typeName(); } } void MGConfItem::unset() { set(QVariant()); } QList<QString> MGConfItem::listDirs() const { QList<QString> children; withClient(client) { QByteArray k = convertKey(priv->key); GError *error = NULL; GSList *dirs = gconf_client_all_dirs(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return children; } for (GSList *d = dirs; d; d = d->next) { children.append(convertKey((char *)d->data)); g_free(d->data); } g_slist_free(dirs); } return children; } QList<QString> MGConfItem::listEntries() const { QList<QString> children; withClient(client) { QByteArray k = convertKey(priv->key); GError *error = NULL; GSList *entries = gconf_client_all_entries(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return children; } for (GSList *e = entries; e; e = e->next) { children.append(convertKey(((GConfEntry *)e->data)->key)); gconf_entry_free((GConfEntry *)e->data); } g_slist_free(entries); } return children; } MGConfItem::MGConfItem(const QString &key, QObject *parent) : QObject(parent) { priv = new MGConfItemPrivate; priv->key = key; withClient(client) { QByteArray k = convertKey(priv->key); GError *error = NULL; int index = k.lastIndexOf('/'); if (index > 0) { QByteArray dir = k.left(index); gconf_client_add_dir(client, dir.data(), GCONF_CLIENT_PRELOAD_ONELEVEL, &error); } else { gconf_client_add_dir(client, k.data(), GCONF_CLIENT_PRELOAD_NONE, &error); } if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return; } priv->notify_id = gconf_client_notify_add(client, k.data(), MGConfItemPrivate::notify_trampoline, this, NULL, &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); priv->have_gconf = false; return; } update_value(false); } priv->have_gconf = true; } MGConfItem::~MGConfItem() { if(priv->have_gconf) { withClient(client) { QByteArray k = convertKey(priv->key); gconf_client_notify_remove(client, priv->notify_id); GError *error = NULL; gconf_client_remove_dir(client, k.data(), &error); if(error) { mWarning("MGConfItem") << error->message; g_error_free(error); return; } } } delete priv; } <|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. */ #include <libtorrent/enum_net.hpp> #include <libtorrent/socket.hpp> #include <libtorrent/broadcast_socket.hpp> #include <vector> #include <iomanip> #include <iostream> using namespace libtorrent; int main() { io_service ios; error_code ec; address local = guess_local_address(ios); std::cout << "Local address: " << local << std::endl; address def_gw = get_default_gateway(ios, ec); if (ec) { std::cerr << ec.message() << std::endl; return 1; } std::cout << "Default gateway: " << def_gw << std::endl; std::cout << "=========== Routes ===========\n"; std::vector<ip_route> routes = enum_routes(ios, ec); if (ec) { std::cerr << ec.message() << std::endl; return 1; } std::cout << std::setiosflags(std::ios::left) << std::setw(18) << "destination" << std::setw(18) << "netmask" << std::setw(35) << "gateway" << "interface name" << std::endl; for (std::vector<ip_route>::const_iterator i = routes.begin() , end(routes.end()); i != end; ++i) { std::cout << std::setiosflags(std::ios::left) << std::setw(18) << i->destination << std::setw(18) << i->netmask << std::setw(35) << i->gateway << i->name << std::endl; } std::cout << "========= Interfaces =========\n"; std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) { std::cerr << ec.message() << std::endl; return 1; } std::cout << std::setiosflags(std::ios::left) << std::setw(35) << "address" << std::setw(18) << "netmask" << std::setw(18) << "name" << "flags" << std::endl; for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { std::cout << std::setiosflags(std::ios::left) << std::setw(35) << i->interface_address << std::setw(18) << i->netmask << std::setw(18) << i->name << (is_multicast(i->interface_address)?"multicast ":"") << (is_local(i->interface_address)?"local ":"") << (is_loopback(i->interface_address)?"loopback ":"") << std::endl; } } <commit_msg>replaced iostream in example<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. */ #include <stdio.h> #include <libtorrent/enum_net.hpp> #include <libtorrent/socket.hpp> #include <libtorrent/broadcast_socket.hpp> using namespace libtorrent; int main() { io_service ios; error_code ec; address local = guess_local_address(ios); printf("Local address: %s\n", local.to_string(ec).c_str()); address def_gw = get_default_gateway(ios, ec); if (ec) { fprintf(stderr, "%s\n", ec.message().c_str()); return 1; } printf("Default gateway: %s\n", def_gw.to_string(ec).c_str()); printf("=========== Routes ===========\n"); std::vector<ip_route> routes = enum_routes(ios, ec); if (ec) { printf("%s\n", ec.message().c_str()); return 1; } printf("%-18s%-18s%-35sinterface name\n", "destination", "network", "gateway"); for (std::vector<ip_route>::const_iterator i = routes.begin() , end(routes.end()); i != end; ++i) { printf("%-18s%-18s%-35s%s\n" , i->destination.to_string(ec).c_str() , i->netmask.to_string(ec).c_str() , i->gateway.to_string(ec).c_str() , i->name); } printf("========= Interfaces =========\n"); std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); if (ec) { printf("%s\n", ec.message().c_str()); return 1; } printf("%-18s%-18s%-35sflags\n", "address", "netmask", "name"); for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { printf("%-18s%-18s%-35s%s%s%s\n" , i->interface_address.to_string(ec).c_str() , i->netmask.to_string(ec).c_str() , i->name , (is_multicast(i->interface_address)?"multicast ":"") , (is_local(i->interface_address)?"local ":"") , (is_loopback(i->interface_address)?"loopback ":"") ); } } <|endoftext|>
<commit_before>#pragma once // only included in case there's a C++11 compiler out there that doesn't support `#pragma once` #ifndef DKM_KMEANS_H #define DKM_KMEANS_H #include <algorithm> #include <array> #include <cassert> #include <cstddef> #include <cstdint> #include <random> #include <tuple> #include <type_traits> #include <vector> /* DKM - A k-means implementation that is generic across variable data dimensions. */ namespace dkm { /* These functions are all private implementation details and shouldn't be referenced outside of this file. */ namespace details { /* Calculate the square of the distance between two points. */ template <typename T, size_t N> T distance_squared(const std::array<T, N>& point_a, const std::array<T, N>& point_b) { T d_squared = T(); for (typename std::array<T, N>::size_type i = 0; i < N; ++i) { auto delta = point_a[i] - point_b[i]; d_squared += delta * delta; } return d_squared; } template <typename T, size_t N> T distance(const std::array<T, N>& point_a, const std::array<T, N>& point_b) { return std::sqrt(distance_squared(point_a, point_b)); } /* Calculate the smallest distance between each of the data points and any of the input means. */ template <typename T, size_t N> std::vector<T> closest_distance( const std::vector<std::array<T, N>>& means, const std::vector<std::array<T, N>>& data) { std::vector<T> distances; distances.reserve(data.size()); for (auto& d : data) { T closest = distance_squared(d, means[0]); for (auto& m : means) { T distance = distance_squared(d, m); if (distance < closest) closest = distance; } distances.push_back(closest); } return distances; } /* This is an alternate initialization method based on the [kmeans++](https://en.wikipedia.org/wiki/K-means%2B%2B) initialization algorithm. */ template <typename T, size_t N> std::vector<std::array<T, N>> random_plusplus(const std::vector<std::array<T, N>>& data, uint32_t k, uint64_t seed) { assert(k > 0); assert(data.size() > 0); using input_size_t = typename std::array<T, N>::size_type; std::vector<std::array<T, N>> means; // Using a very simple PRBS generator, parameters selected according to // https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use std::linear_congruential_engine<uint64_t, 6364136223846793005, 1442695040888963407, UINT64_MAX> rand_engine(seed); // Select first mean at random from the set { std::uniform_int_distribution<input_size_t> uniform_generator(0, data.size() - 1); means.push_back(data[uniform_generator(rand_engine)]); } for (uint32_t count = 1; count < k; ++count) { // Calculate the distance to the closest mean for each data point auto distances = details::closest_distance(means, data); // Pick a random point weighted by the distance from existing means // TODO: This might convert floating point weights to ints, distorting the distribution for small weights #if !defined(_MSC_VER) || _MSC_VER >= 1900 std::discrete_distribution<input_size_t> generator(distances.begin(), distances.end()); #else // MSVC++ older than 14.0 input_size_t i = 0; std::discrete_distribution<input_size_t> generator(distances.size(), 0.0, 0.0, [&distances, &i](double) { return distances[i++]; }); #endif means.push_back(data[generator(rand_engine)]); } return means; } /* Calculate the index of the mean a particular data point is closest to (euclidean distance) */ template <typename T, size_t N> uint32_t closest_mean(const std::array<T, N>& point, const std::vector<std::array<T, N>>& means) { assert(!means.empty()); T smallest_distance = distance_squared(point, means[0]); typename std::array<T, N>::size_type index = 0; T distance; for (size_t i = 1; i < means.size(); ++i) { distance = distance_squared(point, means[i]); if (distance < smallest_distance) { smallest_distance = distance; index = i; } } return index; } /* Calculate the index of the mean each data point is closest to (euclidean distance). */ template <typename T, size_t N> std::vector<uint32_t> calculate_clusters( const std::vector<std::array<T, N>>& data, const std::vector<std::array<T, N>>& means) { std::vector<uint32_t> clusters; for (auto& point : data) { clusters.push_back(closest_mean(point, means)); } return clusters; } /* Calculate means based on data points and their cluster assignments. */ template <typename T, size_t N> std::vector<std::array<T, N>> calculate_means(const std::vector<std::array<T, N>>& data, const std::vector<uint32_t>& clusters, const std::vector<std::array<T, N>>& old_means, uint32_t k) { std::vector<std::array<T, N>> means(k); std::vector<T> count(k, T()); for (size_t i = 0; i < std::min(clusters.size(), data.size()); ++i) { auto& mean = means[clusters[i]]; count[clusters[i]] += 1; for (size_t j = 0; j < std::min(data[i].size(), mean.size()); ++j) { mean[j] += data[i][j]; } } for (size_t i = 0; i < k; ++i) { if (count[i] == 0) { means[i] = old_means[i]; } else { for (size_t j = 0; j < means[i].size(); ++j) { means[i][j] /= count[i]; } } } return means; } template <typename T, size_t N> std::vector<T> deltas( const std::vector<std::array<T, N>>& old_means, const std::vector<std::array<T, N>>& means) { std::vector<T> distances; distances.reserve(means.size()); assert(old_means.size() == means.size()); for (size_t i = 0; i < means.size(); ++i) { distances.push_back(distance(means[i], old_means[i])); } return distances; } template <typename T> bool deltas_below_limit(const std::vector<T>& deltas, T min_delta) { for (T d : deltas) { if (d > min_delta) { return true; } } return false; } } // namespace details /* clustering_parameters is the configuration used for running the kmeans_lloyd algorithm. It requires a k value for initialization, and can subsequently be configured with your choice of optional parameters, including: * Maximum iteration count; the algorithm will terminate if it reaches this iteration count before converging on a solution. The results returned are the means and cluster assignments calculated in the last iteration before termination. * Minimum delta; the algorithm will terminate if the change in position of all means is smaller than the specified distance. * Random seed; if present, this will be used in place of `std::random_device` for kmeans++ initialization. This can be used to ensure reproducible/deterministic behavior. */ template <typename T> class clustering_parameters { public: explicit clustering_parameters(uint32_t k) : _k(k), _has_max_iter(false), _max_iter(), _has_min_delta(false), _min_delta(), _has_rand_seed(false), _rand_seed() {} void set_max_iteration(uint64_t max_iter) { _max_iter = max_iter; _has_max_iter = true; } void set_min_delta(T min_delta) { _min_delta = min_delta; _has_min_delta = true; } void set_random_seed(uint64_t rand_seed) { _rand_seed = rand_seed; _has_rand_seed = true; } bool has_max_iteration() const { return _has_max_iter; } bool has_min_delta() const { return _has_min_delta; } bool has_random_seed() const { return _has_rand_seed; } uint32_t get_k() const { return _k; }; uint64_t get_max_iteration() const { return _max_iter; } T get_min_delta() const { return _min_delta; } uint64_t get_random_seed() const { return _has_rand_seed; } private: uint32_t _k; bool _has_max_iter; uint64_t _max_iter; bool _has_min_delta; T _min_delta; bool _has_rand_seed; uint64_t _rand_seed; }; /* Implementation of k-means generic across the data type and the dimension of each data item. Expects the data to be a vector of fixed-size arrays. Generic parameters are the type of the base data (T) and the dimensionality of each data point (N). All points must have the same dimensionality. e.g. points of the form (X, Y, Z) would be N = 3. Takes a `clustering_parameters` struct for algorithm configuration. See the comments for the `clustering_parameters` struct for more information about the configuration values and how they affect the algorithm. Returns a std::tuple containing: 0: A vector holding the means for each cluster from 0 to k-1. 1: A vector containing the cluster number (0 to k-1) for each corresponding element of the input data vector. Implementation details: This implementation of k-means uses [Lloyd's Algorithm](https://en.wikipedia.org/wiki/Lloyd%27s_algorithm) with the [kmeans++](https://en.wikipedia.org/wiki/K-means%2B%2B) used for initializing the means. */ template <typename T, size_t N> std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>> kmeans_lloyd( const std::vector<std::array<T, N>>& data, const clustering_parameters<T>& parameters) { static_assert(std::is_arithmetic<T>::value && std::is_signed<T>::value, "kmeans_lloyd requires the template parameter T to be a signed arithmetic type (e.g. float, double, int)"); assert(parameters.get_k() > 0); // k must be greater than zero assert(data.size() >= parameters.get_k()); // there must be at least k data points std::random_device rand_device; uint64_t seed = parameters.has_random_seed() ? parameters.get_random_seed() : rand_device(); std::vector<std::array<T, N>> means = details::random_plusplus(data, parameters.get_k(), seed); std::vector<std::array<T, N>> old_means; std::vector<std::array<T, N>> old_old_means; std::vector<uint32_t> clusters; // Calculate new means until convergence is reached or we hit the maximum iteration count uint64_t count = 0; do { clusters = details::calculate_clusters(data, means); old_old_means = old_means; old_means = means; means = details::calculate_means(data, clusters, old_means, parameters.get_k()); ++count; } while ((means != old_means && means != old_old_means) || (parameters.has_max_iteration() && count == parameters.get_max_iteration()) || (parameters.has_min_delta() && !details::deltas_below_limit(details::deltas(old_means, means), parameters.get_min_delta()))); return std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>>(means, clusters); } /* This overload exists to support legacy code which uses this signature of the kmeans_lloyd function. Any code still using this signature should move to the version of this function that uses a `clustering_parameters` struct for configuration. */ template <typename T, size_t N> std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>> kmeans_lloyd( const std::vector<std::array<T, N>>& data, uint32_t k, uint64_t max_iter = 0, T min_delta = -1.0) { clustering_parameters<T> parameters(k); if (max_iter != 0) { parameters.set_max_iteration(max_iter); } if (min_delta != 0) { parameters.set_min_delta(min_delta); } return kmeans_lloyd(data, parameters); } } // namespace dkm #endif /* DKM_KMEANS_H */ <commit_msg>Fixes get_random_seed() function to return _rand_seed, not bool _has_rand_seed.<commit_after>#pragma once // only included in case there's a C++11 compiler out there that doesn't support `#pragma once` #ifndef DKM_KMEANS_H #define DKM_KMEANS_H #include <algorithm> #include <array> #include <cassert> #include <cstddef> #include <cstdint> #include <random> #include <tuple> #include <type_traits> #include <vector> /* DKM - A k-means implementation that is generic across variable data dimensions. */ namespace dkm { /* These functions are all private implementation details and shouldn't be referenced outside of this file. */ namespace details { /* Calculate the square of the distance between two points. */ template <typename T, size_t N> T distance_squared(const std::array<T, N>& point_a, const std::array<T, N>& point_b) { T d_squared = T(); for (typename std::array<T, N>::size_type i = 0; i < N; ++i) { auto delta = point_a[i] - point_b[i]; d_squared += delta * delta; } return d_squared; } template <typename T, size_t N> T distance(const std::array<T, N>& point_a, const std::array<T, N>& point_b) { return std::sqrt(distance_squared(point_a, point_b)); } /* Calculate the smallest distance between each of the data points and any of the input means. */ template <typename T, size_t N> std::vector<T> closest_distance( const std::vector<std::array<T, N>>& means, const std::vector<std::array<T, N>>& data) { std::vector<T> distances; distances.reserve(data.size()); for (auto& d : data) { T closest = distance_squared(d, means[0]); for (auto& m : means) { T distance = distance_squared(d, m); if (distance < closest) closest = distance; } distances.push_back(closest); } return distances; } /* This is an alternate initialization method based on the [kmeans++](https://en.wikipedia.org/wiki/K-means%2B%2B) initialization algorithm. */ template <typename T, size_t N> std::vector<std::array<T, N>> random_plusplus(const std::vector<std::array<T, N>>& data, uint32_t k, uint64_t seed) { assert(k > 0); assert(data.size() > 0); using input_size_t = typename std::array<T, N>::size_type; std::vector<std::array<T, N>> means; // Using a very simple PRBS generator, parameters selected according to // https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use std::linear_congruential_engine<uint64_t, 6364136223846793005, 1442695040888963407, UINT64_MAX> rand_engine(seed); // Select first mean at random from the set { std::uniform_int_distribution<input_size_t> uniform_generator(0, data.size() - 1); means.push_back(data[uniform_generator(rand_engine)]); } for (uint32_t count = 1; count < k; ++count) { // Calculate the distance to the closest mean for each data point auto distances = details::closest_distance(means, data); // Pick a random point weighted by the distance from existing means // TODO: This might convert floating point weights to ints, distorting the distribution for small weights #if !defined(_MSC_VER) || _MSC_VER >= 1900 std::discrete_distribution<input_size_t> generator(distances.begin(), distances.end()); #else // MSVC++ older than 14.0 input_size_t i = 0; std::discrete_distribution<input_size_t> generator(distances.size(), 0.0, 0.0, [&distances, &i](double) { return distances[i++]; }); #endif means.push_back(data[generator(rand_engine)]); } return means; } /* Calculate the index of the mean a particular data point is closest to (euclidean distance) */ template <typename T, size_t N> uint32_t closest_mean(const std::array<T, N>& point, const std::vector<std::array<T, N>>& means) { assert(!means.empty()); T smallest_distance = distance_squared(point, means[0]); typename std::array<T, N>::size_type index = 0; T distance; for (size_t i = 1; i < means.size(); ++i) { distance = distance_squared(point, means[i]); if (distance < smallest_distance) { smallest_distance = distance; index = i; } } return index; } /* Calculate the index of the mean each data point is closest to (euclidean distance). */ template <typename T, size_t N> std::vector<uint32_t> calculate_clusters( const std::vector<std::array<T, N>>& data, const std::vector<std::array<T, N>>& means) { std::vector<uint32_t> clusters; for (auto& point : data) { clusters.push_back(closest_mean(point, means)); } return clusters; } /* Calculate means based on data points and their cluster assignments. */ template <typename T, size_t N> std::vector<std::array<T, N>> calculate_means(const std::vector<std::array<T, N>>& data, const std::vector<uint32_t>& clusters, const std::vector<std::array<T, N>>& old_means, uint32_t k) { std::vector<std::array<T, N>> means(k); std::vector<T> count(k, T()); for (size_t i = 0; i < std::min(clusters.size(), data.size()); ++i) { auto& mean = means[clusters[i]]; count[clusters[i]] += 1; for (size_t j = 0; j < std::min(data[i].size(), mean.size()); ++j) { mean[j] += data[i][j]; } } for (size_t i = 0; i < k; ++i) { if (count[i] == 0) { means[i] = old_means[i]; } else { for (size_t j = 0; j < means[i].size(); ++j) { means[i][j] /= count[i]; } } } return means; } template <typename T, size_t N> std::vector<T> deltas( const std::vector<std::array<T, N>>& old_means, const std::vector<std::array<T, N>>& means) { std::vector<T> distances; distances.reserve(means.size()); assert(old_means.size() == means.size()); for (size_t i = 0; i < means.size(); ++i) { distances.push_back(distance(means[i], old_means[i])); } return distances; } template <typename T> bool deltas_below_limit(const std::vector<T>& deltas, T min_delta) { for (T d : deltas) { if (d > min_delta) { return true; } } return false; } } // namespace details /* clustering_parameters is the configuration used for running the kmeans_lloyd algorithm. It requires a k value for initialization, and can subsequently be configured with your choice of optional parameters, including: * Maximum iteration count; the algorithm will terminate if it reaches this iteration count before converging on a solution. The results returned are the means and cluster assignments calculated in the last iteration before termination. * Minimum delta; the algorithm will terminate if the change in position of all means is smaller than the specified distance. * Random seed; if present, this will be used in place of `std::random_device` for kmeans++ initialization. This can be used to ensure reproducible/deterministic behavior. */ template <typename T> class clustering_parameters { public: explicit clustering_parameters(uint32_t k) : _k(k), _has_max_iter(false), _max_iter(), _has_min_delta(false), _min_delta(), _has_rand_seed(false), _rand_seed() {} void set_max_iteration(uint64_t max_iter) { _max_iter = max_iter; _has_max_iter = true; } void set_min_delta(T min_delta) { _min_delta = min_delta; _has_min_delta = true; } void set_random_seed(uint64_t rand_seed) { _rand_seed = rand_seed; _has_rand_seed = true; } bool has_max_iteration() const { return _has_max_iter; } bool has_min_delta() const { return _has_min_delta; } bool has_random_seed() const { return _has_rand_seed; } uint32_t get_k() const { return _k; }; uint64_t get_max_iteration() const { return _max_iter; } T get_min_delta() const { return _min_delta; } uint64_t get_random_seed() const { return _rand_seed; } private: uint32_t _k; bool _has_max_iter; uint64_t _max_iter; bool _has_min_delta; T _min_delta; bool _has_rand_seed; uint64_t _rand_seed; }; /* Implementation of k-means generic across the data type and the dimension of each data item. Expects the data to be a vector of fixed-size arrays. Generic parameters are the type of the base data (T) and the dimensionality of each data point (N). All points must have the same dimensionality. e.g. points of the form (X, Y, Z) would be N = 3. Takes a `clustering_parameters` struct for algorithm configuration. See the comments for the `clustering_parameters` struct for more information about the configuration values and how they affect the algorithm. Returns a std::tuple containing: 0: A vector holding the means for each cluster from 0 to k-1. 1: A vector containing the cluster number (0 to k-1) for each corresponding element of the input data vector. Implementation details: This implementation of k-means uses [Lloyd's Algorithm](https://en.wikipedia.org/wiki/Lloyd%27s_algorithm) with the [kmeans++](https://en.wikipedia.org/wiki/K-means%2B%2B) used for initializing the means. */ template <typename T, size_t N> std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>> kmeans_lloyd( const std::vector<std::array<T, N>>& data, const clustering_parameters<T>& parameters) { static_assert(std::is_arithmetic<T>::value && std::is_signed<T>::value, "kmeans_lloyd requires the template parameter T to be a signed arithmetic type (e.g. float, double, int)"); assert(parameters.get_k() > 0); // k must be greater than zero assert(data.size() >= parameters.get_k()); // there must be at least k data points std::random_device rand_device; uint64_t seed = parameters.has_random_seed() ? parameters.get_random_seed() : rand_device(); std::vector<std::array<T, N>> means = details::random_plusplus(data, parameters.get_k(), seed); std::vector<std::array<T, N>> old_means; std::vector<std::array<T, N>> old_old_means; std::vector<uint32_t> clusters; // Calculate new means until convergence is reached or we hit the maximum iteration count uint64_t count = 0; do { clusters = details::calculate_clusters(data, means); old_old_means = old_means; old_means = means; means = details::calculate_means(data, clusters, old_means, parameters.get_k()); ++count; } while ((means != old_means && means != old_old_means) || (parameters.has_max_iteration() && count == parameters.get_max_iteration()) || (parameters.has_min_delta() && !details::deltas_below_limit(details::deltas(old_means, means), parameters.get_min_delta()))); return std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>>(means, clusters); } /* This overload exists to support legacy code which uses this signature of the kmeans_lloyd function. Any code still using this signature should move to the version of this function that uses a `clustering_parameters` struct for configuration. */ template <typename T, size_t N> std::tuple<std::vector<std::array<T, N>>, std::vector<uint32_t>> kmeans_lloyd( const std::vector<std::array<T, N>>& data, uint32_t k, uint64_t max_iter = 0, T min_delta = -1.0) { clustering_parameters<T> parameters(k); if (max_iter != 0) { parameters.set_max_iteration(max_iter); } if (min_delta != 0) { parameters.set_min_delta(min_delta); } return kmeans_lloyd(data, parameters); } } // namespace dkm #endif /* DKM_KMEANS_H */ <|endoftext|>
<commit_before>// GenericRepositoryTests.cpp #include <gtest/gtest.h> #include <dlfcn.h> #include "GenericRepository.h" #include "GenericRepositoryTests.h" #include "XMLQueryEngine.h" #include "Timer.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::SetUp(){ // initialize ordinary objects x_ = 10; y_ = 10; z_ = 10; dx_ = 1; dy_ = 1; dz_ = 1; adv_vel_ = .000631; capacity_ = 100; in_commod_ = "in_commod"; inventory_size_ = 70000; lifetime_ = 3000000; start_op_yr_ = 1; start_op_mo_ = 1; cname_ = "component"; innerradius_ = 0; outerradius_ = 100; componenttype_ = "FF"; src_facility = initSrcFacility(); initWorld(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::TearDown() { delete src_facility; delete incommod_market; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GenericRepository* GenericRepositoryTest::initSrcFacility(){ stringstream st(""); st << " <thermalmodel>" << " <StubThermal/>" << " </thermalmodel>"; stringstream sn(""); sn << " <nuclidemodel>" << " <StubNuclide/>" << " </nuclidemodel>"; stringstream cs(""); cs << " <component>" << " <name>" << cname_ << "</name>" << " <innerradius>" << innerradius_ << "</innerradius>" << " <outerradius>" << outerradius_ << "</outerradius>" << " <componenttype>" << componenttype_ << "</componenttype>" << st << sn << " </component>"; stringstream ss(""); ss << "<start>" << " <x>" << x_ << "</x>" << " <y>" << y_ << "</y>" << " <z>" << z_ << "</z>" << " <dx>" << dx_ << "</dx>" << " <dy>" << dy_ << "</dy>" << " <dz>" << dz_ << "</dz>" << " <advective_velocity>" << adv_vel_ << "</advective_velocity>" << " <capacity>" << capacity_ << "</capacity>" << " <incommodity>" << in_commod_ << "</incommodity>" << " <inventorysize>" << inventory_size_ << "</inventorysize>" << " <lifetime>" << lifetime_ << "</lifetime>" << " <startOperMonth>" << start_op_mo_ << "</startOperMonth>" << " <startOperYear>" << start_op_yr_ << "</startOperYear>" << cs << "</start>"; XMLParser parser(ss); XMLQueryEngine* engine = new XMLQueryEngine(parser); src_facility = new GenericRepository(); src_facility->initModuleMembers(engine); delete engine; return src_facility; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::initWorld(){ incommod_market = new TestMarket(); incommod_market->setCommodity(in_commod_); MarketModel::registerMarket(incommod_market); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(GenericRepositoryTest, initial_state) { EXPECT_EQ(capacity_, src_facility->getCapacity(in_commod_)); EXPECT_EQ(adv_vel_, src_facility->adv_vel()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INSTANTIATE_TEST_CASE_P(GenericRepositoryFac, FacilityModelTests, Values(&GenericRepositoryFacilityConstructor)); INSTANTIATE_TEST_CASE_P(GenericRepositoryFac, ModelTests, Values(&GenericRepositoryModelConstructor)); <commit_msg>adds basic thermal test ideas.<commit_after>// GenericRepositoryTests.cpp #include <gtest/gtest.h> #include <dlfcn.h> #include "GenericRepository.h" #include "GenericRepositoryTests.h" #include "XMLQueryEngine.h" #include "Timer.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::SetUp(){ // initialize ordinary objects x_ = 10; y_ = 10; z_ = 10; dx_ = 1; dy_ = 1; dz_ = 1; adv_vel_ = .000631; capacity_ = 100; in_commod_ = "in_commod"; inventory_size_ = 70000; lifetime_ = 3000000; start_op_yr_ = 1; start_op_mo_ = 1; cname_ = "component"; innerradius_ = 0; outerradius_ = 100; componenttype_ = "FF"; src_facility = initSrcFacility(); initWorld(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::TearDown() { delete src_facility; delete incommod_market; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GenericRepository* GenericRepositoryTest::initSrcFacility(){ stringstream st(""); st << " <thermalmodel>" << " <StubThermal/>" << " </thermalmodel>"; stringstream sn(""); sn << " <nuclidemodel>" << " <StubNuclide/>" << " </nuclidemodel>"; stringstream cs(""); cs << " <component>" << " <name>" << cname_ << "</name>" << " <innerradius>" << innerradius_ << "</innerradius>" << " <outerradius>" << outerradius_ << "</outerradius>" << " <componenttype>" << componenttype_ << "</componenttype>" << st << sn << " </component>"; stringstream ss(""); ss << "<start>" << " <x>" << x_ << "</x>" << " <y>" << y_ << "</y>" << " <z>" << z_ << "</z>" << " <dx>" << dx_ << "</dx>" << " <dy>" << dy_ << "</dy>" << " <dz>" << dz_ << "</dz>" << " <advective_velocity>" << adv_vel_ << "</advective_velocity>" << " <capacity>" << capacity_ << "</capacity>" << " <incommodity>" << in_commod_ << "</incommodity>" << " <inventorysize>" << inventory_size_ << "</inventorysize>" << " <lifetime>" << lifetime_ << "</lifetime>" << " <startOperMonth>" << start_op_mo_ << "</startOperMonth>" << " <startOperYear>" << start_op_yr_ << "</startOperYear>" << cs << "</start>"; XMLParser parser(ss); XMLQueryEngine* engine = new XMLQueryEngine(parser); src_facility = new GenericRepository(); src_facility->initModuleMembers(engine); delete engine; return src_facility; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GenericRepositoryTest::initWorld(){ incommod_market = new TestMarket(); incommod_market->setCommodity(in_commod_); MarketModel::registerMarket(incommod_market); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(GenericRepositoryTest, initial_state) { EXPECT_EQ(capacity_, src_facility->getCapacity(in_commod_)); EXPECT_EQ(adv_vel_, src_facility->adv_vel()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(GenericRepositoryTest, assess_capacity_crude){ // after stuff is absorbed, the capacity should be lower than before. EXPECT_NO_THROW(src_facility->emplaceWaste()); EXPECT_NO_THROW(src_facility->handleTick(time)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(GenericRepositoryTest, reject_hot_mat){ EXPECT_EQ(false, src_facility->mat_acceptable(hot_mat)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(GenericRepositoryTest, accept_cold_mat){ EXPECT_EQ(true, src_facility->mat_acceptable()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INSTANTIATE_TEST_CASE_P(GenericRepositoryFac, FacilityModelTests, Values(&GenericRepositoryFacilityConstructor)); INSTANTIATE_TEST_CASE_P(GenericRepositoryFac, ModelTests, Values(&GenericRepositoryModelConstructor)); <|endoftext|>
<commit_before>#include "Arduino.h" #include "custom_joystick.h" int custom_joystick::normalize(int value) { /* * a wrapper for map built-in function * * @param value: is within analogRead boundries * @return: normalize value within normalize boundries */ // https://www.arduino.cc/en/Reference/Map // map(value, fromLow, fromHigh, toLow, toHigh) return map(value, ANALOG_READ_LOW, ANALOG_READ_HIGH, this->lowerBound, this->higherBound); } void custom_joystick::attach_pin_x(short pin) { this->pinX = pin; } void custom_joystick::attach_pin_y(short pin) { this->pinY = pin; } void custom_joystick::set_lower_bound(int value) { this->lowerBound = value; } void custom_joystick::set_higher_bound(int value) { this->higherBound = value; } void custom_joystick::colibrate() { this->originX = analogRead(this->pinX); this->originY = analogRead(this->pinY); this->normalizedOriginX = this->normalize(this->originX); this->normalizedOriginY = this->normalize(this->originY); } void custom_joystick::set_threshold(int value) { this->threshold = value; } bool custom_joystick::checkBoundry(int &value) { /* * check if value is between normalized boudries or reset it to a boundry * * @param value: to check * @return: true if value is valid or false otherwise */ if(value > this->higherBound){ value = this->higherBound; return false; } else if(value < this->lowerBound){ value = this->lowerBound; return false; } return true; } int custom_joystick::get_origin_x() { return this->originX; } int custom_joystick::get_origin_y() { return this->originY; } int custom_joystick::get_normalized_origin_x() { return this->normalize(this->originX); } int custom_joystick::get_normalized_origin_y() { return this->normalize(this->originY); } int custom_joystick::get_x() { return analogRead(this->pinX); } int custom_joystick::get_y() { return analogRead(this->pinX); } int custom_joystick::get_normalized_x() { return this->normalize(this->get_x()); } int custom_joystick::get_normalized_y() { return this->normalize(this->get_y()); } <commit_msg>add docstring<commit_after>/******************************************************************* * Custom joystick class for to work with joystick * * * * Note: YOU MUST ALWAYS COLIBRATE BEFORE FIRST USAGE * * * * @author: Navid Kalaei <navidkalaei@gmail.com> * * @license: MIT * *******************************************************************/ #include "Arduino.h" #include "custom_joystick.h" int custom_joystick::normalize(int value) { /* * a wrapper for map built-in function * * @param value: is within analogRead boundries * @return: normalize value within normalize boundries */ // https://www.arduino.cc/en/Reference/Map // map(value, fromLow, fromHigh, toLow, toHigh) return map(value, ANALOG_READ_LOW, ANALOG_READ_HIGH, this->lowerBound, this->higherBound); } void custom_joystick::attach_pin_x(short pin) { this->pinX = pin; } void custom_joystick::attach_pin_y(short pin) { this->pinY = pin; } void custom_joystick::set_lower_bound(int value) { this->lowerBound = value; } void custom_joystick::set_higher_bound(int value) { this->higherBound = value; } void custom_joystick::colibrate() { this->originX = analogRead(this->pinX); this->originY = analogRead(this->pinY); this->normalizedOriginX = this->normalize(this->originX); this->normalizedOriginY = this->normalize(this->originY); } void custom_joystick::set_threshold(int value) { this->threshold = value; } bool custom_joystick::checkBoundry(int &value) { /* * check if value is between normalized boudries or reset it to a boundry * * @param value: to check * @return: true if value is valid or false otherwise */ if(value > this->higherBound){ value = this->higherBound; return false; } else if(value < this->lowerBound){ value = this->lowerBound; return false; } return true; } int custom_joystick::get_origin_x() { return this->originX; } int custom_joystick::get_origin_y() { return this->originY; } int custom_joystick::get_normalized_origin_x() { return this->normalize(this->originX); } int custom_joystick::get_normalized_origin_y() { return this->normalize(this->originY); } int custom_joystick::get_x() { return analogRead(this->pinX); } int custom_joystick::get_y() { return analogRead(this->pinX); } int custom_joystick::get_normalized_x() { return this->normalize(this->get_x()); } int custom_joystick::get_normalized_y() { return this->normalize(this->get_y()); } <|endoftext|>
<commit_before>#ifdef USE_GECODE #include "CPSpaceALG.hh" #include "alg/ContextALG.hh" #include "dtoout/SolutionDtoout.hh" #include "bo/ProcessBO.hh" #include "bo/MachineBO.hh" #include "tools/Checker.hh" #include "tools/Log.hh" #include <algorithm> #include <gecode/search.hh> using namespace Gecode; CPSpaceALG::CPSpaceALG() : pGecodeSpace_m(0) { } CPSpaceALG::CPSpaceALG(const CPSpaceALG &that) : SpaceALG(that), pGecodeSpace_m(0) { copy(that); } CPSpaceALG::~CPSpaceALG() { delete pGecodeSpace_m; } CPSpaceALG &CPSpaceALG::operator=(const CPSpaceALG &that) { if (this != &that) { SpaceALG::operator=(that); copy(that); } return *this; } void CPSpaceALG::copy(const CPSpaceALG &that) { delete pGecodeSpace_m; pGecodeSpace_m = 0; perm_m = that.perm_m; if (that.pGecodeSpace_m != 0) pGecodeSpace_m = that.pGecodeSpace_m->safeClone(); } SpaceALG * CPSpaceALG::clone() { return new CPSpaceALG(*this); } bool CPSpaceALG::isSolution() const { return pGecodeSpace_m == 0 || pGecodeSpace_m->isSolution(); } CPSpaceALG::DecisionsPool CPSpaceALG::generateDecisions() const { if (!pGecodeSpace_m) return DecisionsPool(); else return pGecodeSpace_m->generateDecisions(); } void CPSpaceALG::addDecision(DecisionALG *pDecision_p) { assert(dynamic_cast<const CPDecisionALG*>(pDecision_p)); if (pGecodeSpace_m) { const CPDecisionALG *pCPD_l = static_cast<const CPDecisionALG*>(pDecision_p); pGecodeSpace_m->addDecision(pCPD_l); } } struct Comp { Comp(const vector<double> &v_p) : size_m(v_p) {} const vector<double> &size_m; bool operator()(int i_p, int j_p) { return size_m[i_p] < size_m[j_p]; } }; std::vector<int> permutation(const ContextBO *pContext_p) { int nbProc_l = pContext_p->getNbProcesses(); int nbRes_l = pContext_p->getNbRessources(); int nbMach_l = pContext_p->getNbMachines(); vector<double> resScale_l(nbRes_l); vector<double> size_l(nbProc_l); vector<int> perm_l(nbProc_l); for (int mach_l = 0; mach_l < nbMach_l; ++mach_l) { MachineBO *pMach_l = pContext_p->getMachine(mach_l); for (int res_l = 0; res_l < nbRes_l; ++res_l) resScale_l[res_l] += pMach_l->getCapa(res_l); } for (int proc_l = 0; proc_l < nbProc_l; ++proc_l) { ProcessBO *pProc_l = pContext_p->getProcess(proc_l); perm_l[proc_l] = proc_l; for (int res_l = 0; res_l < nbRes_l; ++res_l) size_l[proc_l] += (double) pProc_l->getRequirement(res_l) / resScale_l[res_l]; } Comp comp_l(size_l); sort(perm_l.begin(), perm_l.end(), comp_l); return perm_l; } void CPSpaceALG::setpContext(ContextALG *pContext_p) { SpaceALG::setpContext(pContext_p); delete pGecodeSpace_m; perm_m = permutation(pContext_p->getContextBO()); pGecodeSpace_m = new GecodeSpace(pContext_p->getContextBO(), perm_m); } double CPSpaceALG::evaluate() const { double res_l = 0.; // si on a pas de Gecode, le pb est FAILED if (! pGecodeSpace_m || pGecodeSpace_m->status() == SS_FAILED) return res_l; // Montecarlo: on demande une solution à Gecode Search::FailStop stop_l(100); Search::Options options_l; options_l.stop = &stop_l; options_l.clone = false; //options_l.c_d = 1000; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); pSpace_l->postBranching(GecodeSpace::MC); DFS<GecodeSpace> search_l(pSpace_l, options_l); GecodeSpace *pSol_l = search_l.next(); // Gecode a pas trouvé de solution réalisable if (! pSol_l) { if (search_l.stopped()) { LOG(INFO) << "Search stopped." << endl; } return res_l; } // on récupère la solution std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; uint64_t eval_l = localsearch(sol_l); res_l = (double) origEval_m / ((double) origEval_m + eval_l); return res_l; } uint64_t CPSpaceALG::localsearch(std::vector<int> bestSol_p) const { bool foundBetter_l = true; int nbProc_l = pContext_m->getContextBO()->getNbProcesses(); int lastImprovedProc_l = 0; int aProc_l = nbProc_l - 1; Checker checker_l(pContext_m->getContextBO(), bestSol_p); assert(checker_l.isValid()); uint64_t bestEval_l = checker_l.computeScore(); Search::MemoryStop stop_l(256 * 1024 * 1024); Search::Options options_l; options_l.stop = &stop_l; options_l.c_d = 1; options_l.clone = false; while (foundBetter_l) { foundBetter_l = false; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); // Nombre de mouvement possible = 1 pSpace_l->restrictNbMove(1, bestSol_p, perm_m); pSpace_l->postBranching(GecodeSpace::LS); do { int proc_l = perm_m[aProc_l]; GecodeSpace *pCurSpace_l = pSpace_l->safeClone(); pCurSpace_l->restrictExceptProc(proc_l, bestSol_p, perm_m); DFS<GecodeSpace> search_l(pCurSpace_l, options_l); GecodeSpace *pSol_l = 0; while ((pSol_l = search_l.next()) != 0) { std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; Checker checker_l(pContext_m->getContextBO(), sol_l); assert(checker_l.isValid()); uint64_t eval_l = checker_l.computeScore(); if (eval_l < bestEval_l) { bestEval_l = eval_l; bestSol_p = sol_l; foundBetter_l = true; lastImprovedProc_l = aProc_l; if (SolutionDtoout::writeSol(bestSol_p, bestEval_l)) { LOG(INFO) << "Better solution: " << bestEval_l << endl; } } } if (--aProc_l < 0) { aProc_l = nbProc_l - 1; } } while (!foundBetter_l && aProc_l != lastImprovedProc_l); delete pSpace_l; } return bestEval_l; } uint64_t CPSpaceALG::localsearch2(std::vector<int> bestSol_p) const { bool foundBetter_l = true; int nbProc_l = pContext_m->getContextBO()->getNbProcesses(); int maxIter_l = 100; int lastImprovedProc_l = 0; int aProc_l = nbProc_l - 1; Checker checker_l(pContext_m->getContextBO(), bestSol_p); assert(checker_l.isValid()); uint64_t bestEval_l = checker_l.computeScore(); Search::MemoryStop stop_l(256 * 1024 * 1024); Search::Options options_l; options_l.stop = &stop_l; options_l.c_d = 1; options_l.clone = false; while (foundBetter_l) { foundBetter_l = false; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); pSpace_l->postBranching(GecodeSpace::LS); do { // // PARTIE EVALUATION DU NOMBRE DE PROCS A RECALCULER // vector<int> vProcFree_l; int proc1_l = perm_m[aProc_l]; vProcFree_l.push_back(proc1_l); GecodeSpace *pCurSpace_l = pSpace_l->safeClone(); pCurSpace_l->restrictExceptProcs(vProcFree_l, bestSol_p, perm_m); int nbPossibilities_l = pCurSpace_l->nbPossibilitiesForProc(proc1_l, perm_m); if( nbPossibilities_l <= maxIter_l ) { int idxProcToAdd_l = aProc_l-1; while(idxProcToAdd_l >= 0) { GecodeSpace *pCurSpace2_l = pSpace_l->safeClone(); int procToAdd_l = perm_m[idxProcToAdd_l]; vProcFree_l.push_back(procToAdd_l); pCurSpace2_l->restrictExceptProcs(vProcFree_l, bestSol_p, perm_m); // recalcule de la borne max du nombre de mouvements possibles nbPossibilities_l = 1; for(int idxProc=vProcFree_l.size();--idxProc>=0;) { int nbCurrentPoss_l = pCurSpace2_l->nbPossibilitiesForProc(vProcFree_l[idxProc], perm_m); if( nbCurrentPoss_l > 1 ) { nbPossibilities_l *= nbCurrentPoss_l; } } if( nbPossibilities_l > maxIter_l ) { // on depasse la combinatoire toleree, on va resoudre avec ca deja delete pCurSpace2_l; break; } // sinon on continue de chercher delete pCurSpace_l; pCurSpace_l = pCurSpace2_l; --idxProcToAdd_l; } aProc_l = idxProcToAdd_l+1; } // // FIN PARTIE EVALUATION DU NOMBRE DE PROCS A RECALCULER // DFS<GecodeSpace> search_l(pCurSpace_l, options_l); // enlevage du premier mouvement quand on ne met pas de contrainte sur le nombre // de mouvement que doit avoir la solution par rapport a la meilleure solution // => le premier mouvement est la solution initiale search_l.next(); GecodeSpace *pSol_l = 0; while ((pSol_l = search_l.next()) != 0 ) { std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; Checker checker_l(pContext_m->getContextBO(), sol_l); assert(checker_l.isValid()); uint64_t eval_l = checker_l.computeScore(); if (eval_l < bestEval_l) { bestEval_l = eval_l; bestSol_p = sol_l; foundBetter_l = true; lastImprovedProc_l = aProc_l; if (SolutionDtoout::writeSol(bestSol_p, bestEval_l)) { LOG(INFO) << "Better solution: " << bestEval_l << endl; } } } if (--aProc_l < 0) { aProc_l = nbProc_l - 1; } } while (!foundBetter_l && aProc_l != lastImprovedProc_l); delete pSpace_l; } return bestEval_l; } #endif //USE_GECODE <commit_msg>bugfix du LS de floco (et reindentation)<commit_after>#ifdef USE_GECODE #include "CPSpaceALG.hh" #include "alg/ContextALG.hh" #include "dtoout/SolutionDtoout.hh" #include "bo/ProcessBO.hh" #include "bo/MachineBO.hh" #include "tools/Checker.hh" #include "tools/Log.hh" #include <algorithm> #include <gecode/search.hh> using namespace Gecode; CPSpaceALG::CPSpaceALG() : pGecodeSpace_m(0) { } CPSpaceALG::CPSpaceALG(const CPSpaceALG &that) : SpaceALG(that), pGecodeSpace_m(0) { copy(that); } CPSpaceALG::~CPSpaceALG() { delete pGecodeSpace_m; } CPSpaceALG &CPSpaceALG::operator=(const CPSpaceALG &that) { if (this != &that) { SpaceALG::operator=(that); copy(that); } return *this; } void CPSpaceALG::copy(const CPSpaceALG &that) { delete pGecodeSpace_m; pGecodeSpace_m = 0; perm_m = that.perm_m; if (that.pGecodeSpace_m != 0) pGecodeSpace_m = that.pGecodeSpace_m->safeClone(); } SpaceALG * CPSpaceALG::clone() { return new CPSpaceALG(*this); } bool CPSpaceALG::isSolution() const { return pGecodeSpace_m == 0 || pGecodeSpace_m->isSolution(); } CPSpaceALG::DecisionsPool CPSpaceALG::generateDecisions() const { if (!pGecodeSpace_m) return DecisionsPool(); else return pGecodeSpace_m->generateDecisions(); } void CPSpaceALG::addDecision(DecisionALG *pDecision_p) { assert(dynamic_cast<const CPDecisionALG*>(pDecision_p)); if (pGecodeSpace_m) { const CPDecisionALG *pCPD_l = static_cast<const CPDecisionALG*>(pDecision_p); pGecodeSpace_m->addDecision(pCPD_l); } } struct Comp { Comp(const vector<double> &v_p) : size_m(v_p) {} const vector<double> &size_m; bool operator()(int i_p, int j_p) { return size_m[i_p] < size_m[j_p]; } }; std::vector<int> permutation(const ContextBO *pContext_p) { int nbProc_l = pContext_p->getNbProcesses(); int nbRes_l = pContext_p->getNbRessources(); int nbMach_l = pContext_p->getNbMachines(); vector<double> resScale_l(nbRes_l); vector<double> size_l(nbProc_l); vector<int> perm_l(nbProc_l); for (int mach_l = 0; mach_l < nbMach_l; ++mach_l) { MachineBO *pMach_l = pContext_p->getMachine(mach_l); for (int res_l = 0; res_l < nbRes_l; ++res_l) resScale_l[res_l] += pMach_l->getCapa(res_l); } for (int proc_l = 0; proc_l < nbProc_l; ++proc_l) { ProcessBO *pProc_l = pContext_p->getProcess(proc_l); perm_l[proc_l] = proc_l; for (int res_l = 0; res_l < nbRes_l; ++res_l) size_l[proc_l] += (double) pProc_l->getRequirement(res_l) / resScale_l[res_l]; } Comp comp_l(size_l); sort(perm_l.begin(), perm_l.end(), comp_l); return perm_l; } void CPSpaceALG::setpContext(ContextALG *pContext_p) { SpaceALG::setpContext(pContext_p); delete pGecodeSpace_m; perm_m = permutation(pContext_p->getContextBO()); pGecodeSpace_m = new GecodeSpace(pContext_p->getContextBO(), perm_m); } double CPSpaceALG::evaluate() const { double res_l = 0.; // si on a pas de Gecode, le pb est FAILED if (! pGecodeSpace_m || pGecodeSpace_m->status() == SS_FAILED) return res_l; // Montecarlo: on demande une solution à Gecode Search::FailStop stop_l(100); Search::Options options_l; options_l.stop = &stop_l; options_l.clone = false; //options_l.c_d = 1000; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); pSpace_l->postBranching(GecodeSpace::MC); DFS<GecodeSpace> search_l(pSpace_l, options_l); GecodeSpace *pSol_l = search_l.next(); // Gecode a pas trouvé de solution réalisable if (! pSol_l) { if (search_l.stopped()) { LOG(INFO) << "Search stopped." << endl; } return res_l; } // on récupère la solution std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; uint64_t eval_l = localsearch(sol_l); res_l = (double) origEval_m / ((double) origEval_m + eval_l); return res_l; } uint64_t CPSpaceALG::localsearch(std::vector<int> bestSol_p) const { bool foundBetter_l = true; int nbProc_l = pContext_m->getContextBO()->getNbProcesses(); int lastImprovedProc_l = 0; int aProc_l = nbProc_l - 1; Checker checker_l(pContext_m->getContextBO(), bestSol_p); assert(checker_l.isValid()); uint64_t bestEval_l = checker_l.computeScore(); Search::MemoryStop stop_l(256 * 1024 * 1024); Search::Options options_l; options_l.stop = &stop_l; options_l.c_d = 1; options_l.clone = false; while (foundBetter_l) { foundBetter_l = false; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); // Nombre de mouvement possible = 1 pSpace_l->restrictNbMove(1, bestSol_p, perm_m); pSpace_l->postBranching(GecodeSpace::LS); do { int proc_l = perm_m[aProc_l]; GecodeSpace *pCurSpace_l = pSpace_l->safeClone(); pCurSpace_l->restrictExceptProc(proc_l, bestSol_p, perm_m); DFS<GecodeSpace> search_l(pCurSpace_l, options_l); GecodeSpace *pSol_l = 0; while ((pSol_l = search_l.next()) != 0) { std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; Checker checker_l(pContext_m->getContextBO(), sol_l); assert(checker_l.isValid()); uint64_t eval_l = checker_l.computeScore(); if (eval_l < bestEval_l) { bestEval_l = eval_l; bestSol_p = sol_l; foundBetter_l = true; lastImprovedProc_l = aProc_l; if (SolutionDtoout::writeSol(bestSol_p, bestEval_l)) { LOG(INFO) << "Better solution: " << bestEval_l << endl; } } } if (--aProc_l < 0) { aProc_l = nbProc_l - 1; } } while (!foundBetter_l && aProc_l != lastImprovedProc_l); delete pSpace_l; } return bestEval_l; } uint64_t CPSpaceALG::localsearch2(std::vector<int> bestSol_p) const { bool foundBetter_l = true; int nbProc_l = pContext_m->getContextBO()->getNbProcesses(); int maxIter_l = 100; int lastImprovedProc_l = 0; int aProc_l = nbProc_l - 1; Checker checker_l(pContext_m->getContextBO(), bestSol_p); assert(checker_l.isValid()); uint64_t bestEval_l = checker_l.computeScore(); Search::MemoryStop stop_l(256 * 1024 * 1024); Search::Options options_l; options_l.stop = &stop_l; options_l.c_d = 1; options_l.clone = false; while (foundBetter_l) { foundBetter_l = false; GecodeSpace *pSpace_l = pGecodeSpace_m->safeClone(); pSpace_l->postBranching(GecodeSpace::LS); do { // // PARTIE EVALUATION DU NOMBRE DE PROCS A RECALCULER // vector<int> vProcFree_l; int proc1_l = perm_m[aProc_l]; vProcFree_l.push_back(proc1_l); GecodeSpace *pCurSpace_l = pSpace_l->safeClone(); pCurSpace_l->restrictExceptProcs(vProcFree_l, bestSol_p, perm_m); int nbPossibilities_l = pCurSpace_l->nbPossibilitiesForProc(proc1_l, perm_m); if( nbPossibilities_l <= maxIter_l ) { int idxProcToAdd_l = aProc_l-1; while(idxProcToAdd_l >= 0) { GecodeSpace *pCurSpace2_l = pSpace_l->safeClone(); int procToAdd_l = perm_m[idxProcToAdd_l]; vProcFree_l.push_back(procToAdd_l); pCurSpace2_l->restrictExceptProcs(vProcFree_l, bestSol_p, perm_m); // recalcule de la borne max du nombre de mouvements possibles nbPossibilities_l = 1; for(int idxProc=vProcFree_l.size();--idxProc>=0;) { int nbCurrentPoss_l = pCurSpace2_l->nbPossibilitiesForProc(vProcFree_l[idxProc], perm_m); if( nbCurrentPoss_l > 1 ) { nbPossibilities_l *= nbCurrentPoss_l; } } if( nbPossibilities_l > maxIter_l ) { // on depasse la combinatoire toleree, on va resoudre avec ca deja delete pCurSpace2_l; break; } // sinon on continue de chercher delete pCurSpace_l; pCurSpace_l = pCurSpace2_l; --idxProcToAdd_l; } aProc_l = idxProcToAdd_l+1; } // // FIN PARTIE EVALUATION DU NOMBRE DE PROCS A RECALCULER // DFS<GecodeSpace> search_l(pCurSpace_l, options_l); // enlevage du premier mouvement quand on ne met pas de contrainte sur le nombre // de mouvement que doit avoir la solution par rapport a la meilleure solution // => le premier mouvement est la solution initiale delete search_l.next(); GecodeSpace *pSol_l = 0; while ((pSol_l = search_l.next()) != 0 ) { std::vector<int> sol_l = pSol_l->solution(perm_m); delete pSol_l; Checker checker_l(pContext_m->getContextBO(), sol_l); assert(checker_l.isValid()); uint64_t eval_l = checker_l.computeScore(); if (eval_l < bestEval_l) { bestEval_l = eval_l; bestSol_p = sol_l; foundBetter_l = true; lastImprovedProc_l = aProc_l; if (SolutionDtoout::writeSol(bestSol_p, bestEval_l)) { LOG(INFO) << "Better solution: " << bestEval_l << endl; } } } if (--aProc_l < 0) { break;// la condition d'arrêt a l'air de merder alors je force un tour aProc_l = nbProc_l - 1; } } while (!foundBetter_l && aProc_l != lastImprovedProc_l); delete pSpace_l; } return bestEval_l; } #endif //USE_GECODE <|endoftext|>
<commit_before>/*********************************** Copyright 2017 Ravishankar Mathur 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 <OpenFrames/OpenVRDevice.hpp> #include <OpenFrames/ReferenceFrame.hpp> #include <osg/Matrixd> #include <osg/Notify> #include <osg/MatrixTransform> // Assume 3 stub tracked devices here: HMD + 2 base stations const unsigned int numTrackedDevices = 3; namespace OpenFrames{ /*************************************************************/ OpenVRDevice::OpenVRDevice(float worldUnitsPerMeter, float userHeight) : _worldUnitsPerMeter(worldUnitsPerMeter), _userHeight(userHeight), _width(0), _height(0), _isInitialized(false), _vrSystem(nullptr), _vrRenderModels(nullptr), _ipd(-1.0) { // Allocate render data for each possible tracked device // The render data struct is a light wrapper, so there is no size concern here _deviceIDToModel.resize(numTrackedDevices); // Set up a camera for the device render models // These models exist in local space (the room), so their view matrix should have // the World->Local transform removed. This is done by premultiplying by the inverse // of the World->Local transform. OpenVRTrackball automatically sets this inverse // as the view matrix for the render model Camera, so we just need to specify the // pre-multiply transform order here. _deviceModels = new osg::Camera(); _deviceModels->setTransformOrder(osg::Camera::PRE_MULTIPLY); // Make sure to render device models in the same context/viewport as parent camera _deviceModels->setRenderOrder(osg::Camera::NESTED_RENDER); // We will scale device models according to the provided WorldUnit/Meter ratio, so // make sure that model normals are rescaled by OpenGL _deviceModels->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL, osg::StateAttribute::ON); } OpenVRDevice::~OpenVRDevice() { shutdownVR(); } /*************************************************************/ bool OpenVRDevice::initVR() { osg::notify(osg::NOTICE) << "Using OpenVR stub" << std::endl; // Set texture size similar to what OpenVR would return _width = 1512; // 1.4*1080 _height = 1680; // 1.4*1200 osg::notify(osg::NOTICE) << "VR eye texture width = " << _width << ", height = " << _height << std::endl; // Update the per-eye projection matrices // The view offset matrices will be computed per-frame since IPD can change updateProjectionMatrices(); // Get render models for controllers and other devices updateDeviceRenderModels(); return (_isInitialized = true); } /*************************************************************/ void OpenVRDevice::shutdownVR() { _deviceNameToData.clear(); _deviceIDToModel.clear(); _deviceModels->removeChildren(0, _deviceModels->getNumChildren()); _isInitialized = false; } /*************************************************************/ void OpenVRDevice::updateDeviceRenderModels() { // Loop through all possible tracked devices except the HMD (already loaded) for(unsigned int deviceID = 1; deviceID < numTrackedDevices; ++deviceID) { // Set up device render model setupRenderModelForTrackedDevice(deviceID); } } /*************************************************************/ void OpenVRDevice::setupRenderModelForTrackedDevice(uint32_t deviceID) { // Get name of tracked device std::string deviceName; if(deviceID == 0) deviceName = "HMD_Stub"; else deviceName = "BaseStation_Stub"; // Find device data by name DeviceDataMap::iterator i = _deviceNameToData.find(deviceName); // If not found, then create device data if(i == _deviceNameToData.end()) { osg::notify(osg::NOTICE) << "OpenFrames::OpenVRDeviceStub: Setting up render data for device " << deviceName << std::endl; DeviceData newDevice; // Empty device data since this is a stub _deviceNameToData[deviceName] = newDevice; } // Set up device model if needed if(_deviceIDToModel[deviceID]._data == NULL) { osg::notify(osg::NOTICE) << "OpenFrames::OpenVRDeviceStub: Setting up render model for device " << deviceName << deviceID << std::endl; // Set data for current device model _deviceIDToModel[deviceID]._data = &_deviceNameToData[deviceName]; float radius = 0.1f; float height = 0.2f; // Create device model's render model and add it to the render group osg::Geode *geode = new osg::Geode; geode->addDrawable(new osg::ShapeDrawable(new osg::Capsule(osg::Vec3(),radius, height))); osg::MatrixTransform *xform = new osg::MatrixTransform; xform->addChild(geode); _deviceIDToModel[deviceID]._renderModel = xform; _deviceModels->addChild(xform); } } /*************************************************************/ void OpenVRDevice::updateProjectionMatrices() { // Create right/left/center projection matrices. Using unit depth minimizes // precision losses in the projection matrix _rightProj.makePerspective(110.0, (float)_width/(float)_height, 1.0, 2.0); _leftProj.makePerspective(110.0, (float)_width/(float)_height, 1.0, 2.0); // Center projection is average of right and left _centerProj = (_rightProj + _leftProj)*0.5; } /*************************************************************/ void OpenVRDevice::updateViewOffsets() { // Get right eye view osg::Vec3f rightVec(0.03, 0, 0); // Get left eye view osg::Vec3f leftVec(-0.03, 0, 0); // If IPD has changed, then recompute offset matrices float ipd = (rightVec - leftVec).length(); if (ipd != _ipd) { osg::notify(osg::ALWAYS) << "VR Interpupillary Distance: " << ipd * 1000.0f << "mm" << std::endl; // Scale offsets according to world unit scale rightVec *= -_worldUnitsPerMeter; // Flip direction since we want Head to Eye transform for OSG leftVec *= -_worldUnitsPerMeter; osg::Vec3f centerVec = (rightVec + leftVec)*0.5; _rightViewOffset.makeTranslate(rightVec); _leftViewOffset.makeTranslate(leftVec); _centerViewOffset.makeTranslate(centerVec); _ipd = ipd; } } /*************************************************************/ void OpenVRDevice::waitGetPoses() { osg::Matrixf matDeviceToWorld; // Device to World transform // Simulate HMD pose in meters matDeviceToWorld.makeIdentity(); // Look at scene head-on from the OpenVR origin matDeviceToWorld(3, 1) = 1.6764; // 5'6" user height in meters // The OpenVR HMD units are in meters, so we need to convert its position // to world units. Here we also subtract the user's height from Y component. // Note that the OpenVR world frame is Y-up matDeviceToWorld(3, 0) *= _worldUnitsPerMeter; matDeviceToWorld(3, 1) = (matDeviceToWorld(3, 1) - _userHeight)*_worldUnitsPerMeter; matDeviceToWorld(3, 2) *= _worldUnitsPerMeter; // Invert since we want World to HMD transform _hmdPose.invert(matDeviceToWorld); // Simulate pose for base stations for(unsigned int i = 1; i < numTrackedDevices; ++i) { _deviceIDToModel[i]._valid = true; // Always valid // Set simulated base station pose in meters if(i == 1) { matDeviceToWorld.makeRotate(osg::Quat(10.0, osg::Vec3d(1, 0, 0))); matDeviceToWorld.postMultTranslate(osg::Vec3d(-3, 3, -3)); } else if(i == 2) { matDeviceToWorld.makeRotate(osg::Quat(10.0, osg::Vec3d(0, 1, 0))); matDeviceToWorld.postMultTranslate(osg::Vec3d(2, 3, -2)); } // Apply world unit translation, and subtract user's height from Y component // Note that the OpenVR world frame is Y-up matDeviceToWorld(3, 0) *= _worldUnitsPerMeter; matDeviceToWorld(3, 1) = (matDeviceToWorld(3, 1) - _userHeight)*_worldUnitsPerMeter; matDeviceToWorld(3, 2) *= _worldUnitsPerMeter; // Since the device model is assumed in meters, we need to scale it to world units // The normals will need to be rescaled, which is done by the containing Camera matDeviceToWorld.preMultScale(osg::Vec3d(_worldUnitsPerMeter, _worldUnitsPerMeter, _worldUnitsPerMeter)); // Set base station model's location from its pose osg::MatrixTransform *xform = static_cast<osg::MatrixTransform*>(_deviceIDToModel[i]._renderModel.get()); xform->setMatrix(matDeviceToWorld); } } /*************************************************************/ void OpenVRDevice::submitFrame(GLuint rightEyeTexName, GLuint leftEyeTexName) { // Nothing to do here } } // !namespace OpenFrames <commit_msg>Update Stub VR implementation<commit_after>/*********************************** Copyright 2017 Ravishankar Mathur 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 <OpenFrames/OpenVRDevice.hpp> #include <OpenFrames/ReferenceFrame.hpp> #include <osg/Matrixd> #include <osg/Notify> #include <osg/MatrixTransform> // Assume 3 stub tracked devices here: HMD + 2 base stations const unsigned int numTrackedDevices = 3; namespace OpenFrames{ /*************************************************************/ OpenVREvent::VREvent::VREvent() : _ovrEvent(NULL), _controllerState(NULL) {} /*************************************************************/ OpenVREvent::VREvent::~VREvent() {} /*************************************************************/ OpenVRDevice::OpenVRDevice(float worldUnitsPerMeter, float userHeight) : _worldUnitsPerMeter(worldUnitsPerMeter), _userHeight(userHeight), _width(0), _height(0), _isInitialized(false), _vrSystem(nullptr), _vrRenderModels(nullptr), _ipd(-1.0) { // Allocate render data for each possible tracked device // The render data struct is a light wrapper, so there is no size concern here _deviceIDToModel.resize(numTrackedDevices); // Set up a camera for the device render models // These models exist in local space (the room), so their view matrix should have // the World->Local transform removed. This is done by premultiplying by the inverse // of the World->Local transform. OpenVRTrackball automatically sets this inverse // as the view matrix for the render model Camera, so we just need to specify the // pre-multiply transform order here. _deviceModels = new osg::Camera(); _deviceModels->setTransformOrder(osg::Camera::PRE_MULTIPLY); // Make sure to render device models in the same context/viewport as parent camera _deviceModels->setRenderOrder(osg::Camera::NESTED_RENDER); // We will scale device models according to the provided WorldUnit/Meter ratio, so // make sure that model normals are rescaled by OpenGL _deviceModels->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL, osg::StateAttribute::ON); } OpenVRDevice::~OpenVRDevice() { shutdownVR(); } /*************************************************************/ bool OpenVRDevice::initVR() { osg::notify(osg::NOTICE) << "Using OpenVR stub" << std::endl; // Set texture size similar to what OpenVR would return _width = 1512; // 1.4*1080 _height = 1680; // 1.4*1200 osg::notify(osg::NOTICE) << "VR eye texture width = " << _width << ", height = " << _height << std::endl; // Update the per-eye projection matrices // The view offset matrices will be computed per-frame since IPD can change updateProjectionMatrices(); // Get render models for controllers and other devices updateDeviceRenderModels(); return (_isInitialized = true); } /*************************************************************/ void OpenVRDevice::shutdownVR() { _deviceNameToModel.clear(); _deviceIDToModel.clear(); _deviceModels->removeChildren(0, _deviceModels->getNumChildren()); _isInitialized = false; } /*************************************************************/ void OpenVRDevice::updateDeviceRenderModels() { // Loop through all possible tracked devices except the HMD (already loaded) for(unsigned int deviceID = 1; deviceID < numTrackedDevices; ++deviceID) { // Set up device render model setupRenderModelForTrackedDevice(deviceID); } } /*************************************************************/ void OpenVRDevice::setupRenderModelForTrackedDevice(uint32_t deviceID) { // Get name of tracked device std::string deviceName; if(deviceID == 0) deviceName = "HMD_Stub"; else deviceName = "BaseStation_Stub"; // Find device data by name DeviceModelMap::iterator i = _deviceNameToModel.find(deviceName); // If not found, then load device data if(i == _deviceNameToModel.end()) { osg::notify(osg::NOTICE) << "OpenFrames::OpenVRDeviceStub: Setting up render data for device " << deviceName << std::endl; float radius = 0.1f; float height = 0.2f; // Create device model's render model and add it to the render group osg::Geode *geode = new osg::Geode; geode->addDrawable(new osg::ShapeDrawable(new osg::Capsule(osg::Vec3(),radius, height))); _deviceNameToModel[deviceName] = geode; } // Set up device model if needed if(_deviceIDToModel[deviceID]._modelTransform == NULL) { osg::notify(osg::NOTICE) << "OpenFrames::OpenVRDeviceStub: Setting up render model for device " << deviceName << deviceID << std::endl; // Create device model's transform and add it to the group of all devices osg::MatrixTransform *xform = new osg::MatrixTransform; xform->addChild(_deviceNameToModel[deviceName]); _deviceIDToModel[deviceID]._modelTransform = xform; _deviceIDToModel[deviceID]._class = NONE; _deviceModels->addChild(xform); } } /*************************************************************/ void OpenVRDevice::updateProjectionMatrices() { // Create right/left/center projection matrices. Using unit depth minimizes // precision losses in the projection matrix _rightProj.makePerspective(110.0, (float)_width/(float)_height, 1.0, 2.0); _leftProj.makePerspective(110.0, (float)_width/(float)_height, 1.0, 2.0); // Center projection is average of right and left // OSG doesn't have a matrix addition for Matrixd (facepalm) osg::Matrixf rightProjf = _rightProj; osg::Matrixf leftProjf = _leftProj; _centerProj = (rightProjf + leftProjf)*0.5; } /*************************************************************/ void OpenVRDevice::updateViewOffsets() { // Get right eye view osg::Vec3f rightVec(0.03, 0, 0); // Get left eye view osg::Vec3f leftVec(-0.03, 0, 0); // If IPD has changed, then recompute offset matrices float ipd = (rightVec - leftVec).length(); if (ipd != _ipd) { osg::notify(osg::ALWAYS) << "VR Interpupillary Distance: " << ipd * 1000.0f << "mm" << std::endl; // Scale offsets according to world unit scale rightVec *= -_worldUnitsPerMeter; // Flip direction since we want Head to Eye transform for OSG leftVec *= -_worldUnitsPerMeter; osg::Vec3f centerVec = (rightVec + leftVec)*0.5; _rightViewOffset.makeTranslate(rightVec); _leftViewOffset.makeTranslate(leftVec); _centerViewOffset.makeTranslate(centerVec); _ipd = ipd; } } /*************************************************************/ void OpenVRDevice::waitGetPoses() { osg::Matrixf matDeviceToWorld; // Device to World transform // Simulate HMD pose in meters matDeviceToWorld.makeIdentity(); // Look at scene head-on from the OpenVR origin matDeviceToWorld(3, 1) = 1.6764; // 5'6" user height in meters // The OpenVR HMD units are in meters, so we need to convert its position // to world units. Here we also subtract the user's height from Y component. // Note that the OpenVR world frame is Y-up matDeviceToWorld(3, 0) *= _worldUnitsPerMeter; matDeviceToWorld(3, 1) = (matDeviceToWorld(3, 1) - _userHeight)*_worldUnitsPerMeter; matDeviceToWorld(3, 2) *= _worldUnitsPerMeter; // Invert since we want World to HMD transform _hmdPose.invert(matDeviceToWorld); // Simulate pose for base stations for(unsigned int i = 1; i < numTrackedDevices; ++i) { _deviceIDToModel[i]._valid = true; // Always valid // Set simulated base station pose in meters if(i == 1) { matDeviceToWorld.makeRotate(osg::Quat(10.0, osg::Vec3d(1, 0, 0))); matDeviceToWorld.postMultTranslate(osg::Vec3d(-3, 3, -3)); } else if(i == 2) { matDeviceToWorld.makeRotate(osg::Quat(10.0, osg::Vec3d(0, 1, 0))); matDeviceToWorld.postMultTranslate(osg::Vec3d(2, 3, -2)); } // Apply world unit translation, and subtract user's height from Y component // Note that the OpenVR world frame is Y-up matDeviceToWorld(3, 0) *= _worldUnitsPerMeter; matDeviceToWorld(3, 1) = (matDeviceToWorld(3, 1) - _userHeight)*_worldUnitsPerMeter; matDeviceToWorld(3, 2) *= _worldUnitsPerMeter; // Since the device model is assumed in meters, we need to scale it to world units // The normals will need to be rescaled, which is done by the containing Camera matDeviceToWorld.preMultScale(osg::Vec3d(_worldUnitsPerMeter, _worldUnitsPerMeter, _worldUnitsPerMeter)); // Set base station model's location from its pose _deviceIDToModel[i]._modelTransform->setMatrix(matDeviceToWorld); } } /*************************************************************/ void OpenVRDevice::submitFrame(GLuint rightEyeTexName, GLuint leftEyeTexName) { // Nothing to do here } /*************************************************************/ bool OpenVRDevice::pollNextEvent(OpenVREvent *event) { // Nothing to do here return false; } /*************************************************************/ bool OpenVREventDevice::checkEvents() { // Nothing to do here return false; } /*************************************************************/ OpenVRTrackball::OpenVRTrackball(OpenVRDevice *ovrDevice) : _ovrDevice(ovrDevice) { // Nothing to do here } /*************************************************************/ bool OpenVRTrackball::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us) { return FollowingTrackball::handle(ea, us); } /*************************************************************/ void OpenVRTrackball::updateCamera(osg::Camera& camera) { camera.setViewMatrix(getInverseMatrix()); } /*************************************************************/ void OpenVRTrackball::saveCurrentMotionData() { } } // !namespace OpenFrames <|endoftext|>
<commit_before>#ifndef ELEKTRA_KEY_EXCEPT_HPP #define ELEKTRA_KEY_EXCEPT_HPP #ifndef USER_DEFINED_EXCEPTIONS namespace kdb { class Exception : public std::exception { public: virtual const char* what() const throw() { return "Exception thrown by Elektra"; } }; class KeyException : public Exception { public: virtual const char* what() const throw() { return "Exception thrown by a Key, typically " "because you called a method on a null key. " "Make sure to check this with !key first"; } }; class KeyTypeMismatch: public KeyException { public: virtual const char* what() const throw() { return "Binary/String key mismatch, use proper " "getString()/getBinary() or use getValue() to get both."; } }; class KeyTypeConversion : public KeyException { public: virtual const char* what() const throw() { return "Could not convert data to requested type." "get(Meta)<std::string> or use getMeta<const Key>." "or specialise these template methods"; } }; class KeyInvalidName : public KeyException { public: virtual const char* what() const throw() { return "Invalid Keyname: keyname needs to start with user/ or system/ " "or maybe you tried to change a key that is already in a KeySet."; } }; } #endif #endif <commit_msg>improve error message in exception<commit_after>#ifndef ELEKTRA_KEY_EXCEPT_HPP #define ELEKTRA_KEY_EXCEPT_HPP #ifndef USER_DEFINED_EXCEPTIONS namespace kdb { class Exception : public std::exception { public: virtual const char* what() const throw() { return "Exception thrown by Elektra"; } }; class KeyException : public Exception { public: virtual const char* what() const throw() { return "Exception thrown by a Key, typically " "because you called a method on a null key. " "Make sure to check this with !key first"; } }; class KeyTypeMismatch: public KeyException { public: virtual const char* what() const throw() { return "Binary/String key mismatch, use proper " "getString()/getBinary() or use getValue() to get both."; } }; class KeyTypeConversion : public KeyException { public: virtual const char* what() const throw() { return "Could not convert data to requested type. " "Use get(Meta)<std::string> respectively get(Meta)<const Key> for more generic access " "or specialize the template methods with your type."; } }; class KeyInvalidName : public KeyException { public: virtual const char* what() const throw() { return "Invalid Keyname: keyname needs to start with user/ or system/ " "or maybe you tried to change a key that is already in a KeySet."; } }; } #endif #endif <|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * 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 <cmsis-plus/diag/trace.h> #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/iso/system_error> #include <cstdlib> #include <cstring> #if defined(__EXCEPTIONS) #include <string> #include <system_error> #endif // ---------------------------------------------------------------------------- namespace os { namespace estd { // ====================================================================== using namespace os; #if defined(__EXCEPTIONS) struct system_error_category : public std::error_category { virtual const char* name () const noexcept { return "system"; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" virtual std::string message (int i) const { #if defined(DEBUG) return std::string (strerror (i)); #else return std::string (""); #endif } #pragma GCC diagnostic pop }; struct cmsis_error_category : public std::error_category { virtual const char* name () const noexcept { return "cmsis"; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" virtual std::string message (int i) const { #if defined(DEBUG) return std::string (strerror (i)); #else return std::string (""); #endif } #pragma GCC diagnostic pop }; #endif void __throw_system_error (int ev, const char* what_arg) { #if defined(__EXCEPTIONS) throw std::system_error ( std::error_code (ev, system_error_category ()), what_arg); #else trace_printf ("system_error(%d, %s)\n", ev, what_arg); std::abort (); #endif } void __throw_cmsis_error (int ev, const char* what_arg) { #if defined(__EXCEPTIONS) throw std::system_error ( std::error_code (ev, cmsis_error_category ()), what_arg); #else trace_printf ("system_error(%d, %s)\n", ev, what_arg); std::abort (); #endif } // ------------------------------------------------------------------------ } /* namespace estd */ } /* namespace os */ // ---------------------------------------------------------------------------- <commit_msg>rtos/system-error.cpp: change from inline<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * 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 <cmsis-plus/diag/trace.h> #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/iso/system_error> #include <cstdlib> #include <cstring> #if defined(__EXCEPTIONS) #include <string> #include <system_error> #endif // ---------------------------------------------------------------------------- namespace os { namespace estd { // ====================================================================== using namespace os; #if defined(__EXCEPTIONS) struct system_error_category : public std::error_category { virtual const char* name () const noexcept; virtual std::string message (int i) const; }; const char* system_error_category::name () const noexcept { return "system"; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" std::string system_error_category::message (int i) const { #if defined(DEBUG) return std::string (strerror (i)); #else return std::string (""); #endif } struct cmsis_error_category : public std::error_category { virtual const char* name () const noexcept; virtual std::string message (int i) const; }; const char* cmsis_error_category::name () const noexcept { return "cmsis"; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" std::string cmsis_error_category::message (int i) const { #if defined(DEBUG) return std::string (strerror (i)); #else return std::string (""); #endif } #pragma GCC diagnostic pop #endif void __throw_system_error (int ev, const char* what_arg) { #if defined(__EXCEPTIONS) throw std::system_error (std::error_code (ev, system_error_category ()), what_arg); #else trace_printf ("system_error(%d, %s)\n", ev, what_arg); std::abort (); #endif } void __throw_cmsis_error (int ev, const char* what_arg) { #if defined(__EXCEPTIONS) throw std::system_error (std::error_code (ev, cmsis_error_category ()), what_arg); #else trace_printf ("system_error(%d, %s)\n", ev, what_arg); std::abort (); #endif } // ------------------------------------------------------------------------ } /* namespace estd */ } /* namespace os */ // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> 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 "FreeTypeFont.h" #include <algorithm> #include <ft2build.h> #include FT_FREETYPE_H #include <Utility/Unicode.h> #include "Extensions.h" #include "Image.h" #include "TextureTools/Atlas.h" #include "TextureTools/DistanceField.h" namespace Magnum { namespace Text { namespace { class FreeTypeLayouter: public AbstractLayouter { public: explicit FreeTypeLayouter(FreeTypeFont& font, const Float size, const std::string& text); std::tuple<Rectangle, Rectangle, Vector2> renderGlyph(const Vector2& cursorPosition, const UnsignedInt i) override; private: FreeTypeFont& font; std::vector<FT_UInt> glyphs; const Float size; }; } FreeTypeFontRenderer::FreeTypeFontRenderer() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Init_FreeType(&_library) == 0); } FreeTypeFontRenderer::~FreeTypeFontRenderer() { FT_Done_FreeType(_library); } FreeTypeFont::FreeTypeFont(FreeTypeFontRenderer& renderer, const std::string& fontFile, Float size): _size(size) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_New_Face(renderer.library(), fontFile.c_str(), 0, &_ftFont) == 0); finishConstruction(); } FreeTypeFont::FreeTypeFont(FreeTypeFontRenderer& renderer, const unsigned char* data, std::size_t dataSize, Float size): _size(size) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_New_Memory_Face(renderer.library(), data, dataSize, 0, &_ftFont) == 0); finishConstruction(); } void FreeTypeFont::finishConstruction() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Set_Char_Size(_ftFont, 0, _size*64, 100, 100) == 0); #ifndef MAGNUM_TARGET_GLES MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_rg); #else MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::EXT::texture_rg); #endif /* Set up the texture */ _texture.setWrapping(Texture2D::Wrapping::ClampToEdge) ->setMinificationFilter(Texture2D::Filter::Linear) ->setMagnificationFilter(Texture2D::Filter::Linear); } void FreeTypeFont::prerenderInternal(const std::string& characters, const Vector2i& atlasSize, const Int radius, Texture2D* output) { glyphs.clear(); /** @bug Crash when atlas is too small */ /* Get glyph codes from characters */ std::vector<FT_UInt> charIndices; charIndices.reserve(characters.size()+1); charIndices.push_back(0); for(std::size_t i = 0; i != characters.size(); ) { UnsignedInt codepoint; std::tie(codepoint, i) = Corrade::Utility::Unicode::nextChar(characters, i); charIndices.push_back(FT_Get_Char_Index(_ftFont, codepoint)); } /* Remove duplicates (e.g. uppercase and lowercase mapped to same glyph) */ std::sort(charIndices.begin(), charIndices.end()); charIndices.erase(std::unique(charIndices.begin(), charIndices.end()), charIndices.end()); /* Sizes of all characters */ const Vector2i padding = Vector2i(radius); std::vector<Vector2i> charSizes; charSizes.reserve(charIndices.size()); for(FT_UInt c: charIndices) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(_ftFont, c, FT_LOAD_DEFAULT) == 0); charSizes.push_back(Vector2i(_ftFont->glyph->metrics.width, _ftFont->glyph->metrics.height)/64); } /* Create texture atlas */ const std::vector<Rectanglei> charPositions = TextureTools::atlas(atlasSize, charSizes, padding); /* Render all characters to the atlas and create character map */ glyphs.reserve(charPositions.size()); unsigned char* pixmap = new unsigned char[atlasSize.product()](); Image2D image(atlasSize, Image2D::Format::Red, Image2D::Type::UnsignedByte, pixmap); for(std::size_t i = 0; i != charPositions.size(); ++i) { /* Load and render glyph */ /** @todo B&W only if radius != 0 */ FT_GlyphSlot glyph = _ftFont->glyph; CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(_ftFont, charIndices[i], FT_LOAD_DEFAULT) == 0); CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL) == 0); /* Copy rendered bitmap to texture image */ const FT_Bitmap& bitmap = glyph->bitmap; CORRADE_INTERNAL_ASSERT(std::abs(bitmap.width-charPositions[i].width()) <= 2); CORRADE_INTERNAL_ASSERT(std::abs(bitmap.rows-charPositions[i].height()) <= 2); for(Int yin = 0, yout = charPositions[i].bottom(), ymax = bitmap.rows; yin != ymax; ++yin, ++yout) for(Int xin = 0, xout = charPositions[i].left(), xmax = bitmap.width; xin != xmax; ++xin, ++xout) pixmap[yout*atlasSize.x() + xout] = bitmap.buffer[(bitmap.rows-yin-1)*bitmap.width + xin]; /* Save character texture position and texture coordinates for given character index */ CORRADE_INTERNAL_ASSERT_OUTPUT(glyphs.insert({charIndices[i], std::make_tuple( Rectangle::fromSize((Vector2(glyph->bitmap_left, glyph->bitmap_top-charPositions[i].height()) - Vector2(radius))/_size, Vector2(charPositions[i].size() + 2*padding)/_size), Rectangle(Vector2(charPositions[i].bottomLeft() - padding)/atlasSize, Vector2(charPositions[i].topRight() + padding)/atlasSize) )}).second); } /* Set texture data */ #ifndef MAGNUM_TARGET_GLES output->setImage(0, Texture2D::InternalFormat::R8, &image); #else output->setImage(0, Texture2D::InternalFormat::Red, &image); #endif } void FreeTypeFont::prerender(const std::string& characters, const Vector2i& atlasSize) { prerenderInternal(characters, atlasSize, 0, &_texture); } void FreeTypeFont::prerenderDistanceField(const std::string& characters, const Vector2i& sourceAtlasSize, const Vector2i& atlasSize, Int radius) { MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_storage); /* Render input texture */ Texture2D input; input.setWrapping(Texture2D::Wrapping::ClampToEdge) ->setMinificationFilter(Texture2D::Filter::Linear) ->setMagnificationFilter(Texture2D::Filter::Linear); prerenderInternal(characters, sourceAtlasSize, radius, &input); /* Create distance field from input texture */ _texture.setStorage(1, Texture2D::InternalFormat::R8, atlasSize); TextureTools::distanceField(&input, &_texture, Rectanglei::fromSize({}, atlasSize), radius); } FreeTypeFont::~FreeTypeFont() { FT_Done_Face(_ftFont); } const std::tuple<Rectangle, Rectangle>& FreeTypeFont::operator[](char32_t character) const { auto it = glyphs.find(character); if(it == glyphs.end()) return glyphs.at(0); return it->second; } AbstractLayouter* FreeTypeFont::layout(const Float size, const std::string& text) { return new FreeTypeLayouter(*this, size, text); } namespace { FreeTypeLayouter::FreeTypeLayouter(FreeTypeFont& font, const Float size, const std::string& text): font(font), size(size) { /* Get glyph codes from characters */ glyphs.reserve(text.size()); _glyphCount = text.size(); for(std::size_t i = 0; i != text.size(); ) { UnsignedInt codepoint; std::tie(codepoint, i) = Corrade::Utility::Unicode::nextChar(text, i); glyphs.push_back(FT_Get_Char_Index(font.font(), codepoint)); } } std::tuple<Rectangle, Rectangle, Vector2> FreeTypeLayouter::renderGlyph(const Vector2& cursorPosition, const UnsignedInt i) { /* Position of the texture in the resulting glyph, texture coordinates */ Rectangle texturePosition, textureCoordinates; std::tie(texturePosition, textureCoordinates) = font[glyphs[i]]; /* Load glyph */ CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(font.font(), glyphs[i], FT_LOAD_DEFAULT) == 0); const FT_GlyphSlot slot = font.font()->glyph; Vector2 offset = Vector2(0, 0); /** @todo really? */ Vector2 advance = Vector2(slot->advance.x, slot->advance.y)/(64*font.size()); /* Absolute quad position, composed from cursor position, glyph offset and texture position, denormalized to requested text size */ Rectangle quadPosition = Rectangle::fromSize( (cursorPosition + offset + Vector2(texturePosition.left(), texturePosition.bottom()))*size, texturePosition.size()*size); return std::make_tuple(quadPosition, textureCoordinates, advance); } } }} <commit_msg>Text: assert that also freeing up FreeType resources doesn't fail.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz> 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 "FreeTypeFont.h" #include <algorithm> #include <ft2build.h> #include FT_FREETYPE_H #include <Utility/Unicode.h> #include "Extensions.h" #include "Image.h" #include "TextureTools/Atlas.h" #include "TextureTools/DistanceField.h" namespace Magnum { namespace Text { namespace { class FreeTypeLayouter: public AbstractLayouter { public: explicit FreeTypeLayouter(FreeTypeFont& font, const Float size, const std::string& text); std::tuple<Rectangle, Rectangle, Vector2> renderGlyph(const Vector2& cursorPosition, const UnsignedInt i) override; private: FreeTypeFont& font; std::vector<FT_UInt> glyphs; const Float size; }; } FreeTypeFontRenderer::FreeTypeFontRenderer() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Init_FreeType(&_library) == 0); } FreeTypeFontRenderer::~FreeTypeFontRenderer() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Done_FreeType(_library) == 0); } FreeTypeFont::FreeTypeFont(FreeTypeFontRenderer& renderer, const std::string& fontFile, Float size): _size(size) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_New_Face(renderer.library(), fontFile.c_str(), 0, &_ftFont) == 0); finishConstruction(); } FreeTypeFont::FreeTypeFont(FreeTypeFontRenderer& renderer, const unsigned char* data, std::size_t dataSize, Float size): _size(size) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_New_Memory_Face(renderer.library(), data, dataSize, 0, &_ftFont) == 0); finishConstruction(); } void FreeTypeFont::finishConstruction() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Set_Char_Size(_ftFont, 0, _size*64, 100, 100) == 0); #ifndef MAGNUM_TARGET_GLES MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_rg); #else MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::EXT::texture_rg); #endif /* Set up the texture */ _texture.setWrapping(Texture2D::Wrapping::ClampToEdge) ->setMinificationFilter(Texture2D::Filter::Linear) ->setMagnificationFilter(Texture2D::Filter::Linear); } void FreeTypeFont::prerenderInternal(const std::string& characters, const Vector2i& atlasSize, const Int radius, Texture2D* output) { glyphs.clear(); /** @bug Crash when atlas is too small */ /* Get glyph codes from characters */ std::vector<FT_UInt> charIndices; charIndices.reserve(characters.size()+1); charIndices.push_back(0); for(std::size_t i = 0; i != characters.size(); ) { UnsignedInt codepoint; std::tie(codepoint, i) = Corrade::Utility::Unicode::nextChar(characters, i); charIndices.push_back(FT_Get_Char_Index(_ftFont, codepoint)); } /* Remove duplicates (e.g. uppercase and lowercase mapped to same glyph) */ std::sort(charIndices.begin(), charIndices.end()); charIndices.erase(std::unique(charIndices.begin(), charIndices.end()), charIndices.end()); /* Sizes of all characters */ const Vector2i padding = Vector2i(radius); std::vector<Vector2i> charSizes; charSizes.reserve(charIndices.size()); for(FT_UInt c: charIndices) { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(_ftFont, c, FT_LOAD_DEFAULT) == 0); charSizes.push_back(Vector2i(_ftFont->glyph->metrics.width, _ftFont->glyph->metrics.height)/64); } /* Create texture atlas */ const std::vector<Rectanglei> charPositions = TextureTools::atlas(atlasSize, charSizes, padding); /* Render all characters to the atlas and create character map */ glyphs.reserve(charPositions.size()); unsigned char* pixmap = new unsigned char[atlasSize.product()](); Image2D image(atlasSize, Image2D::Format::Red, Image2D::Type::UnsignedByte, pixmap); for(std::size_t i = 0; i != charPositions.size(); ++i) { /* Load and render glyph */ /** @todo B&W only if radius != 0 */ FT_GlyphSlot glyph = _ftFont->glyph; CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(_ftFont, charIndices[i], FT_LOAD_DEFAULT) == 0); CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL) == 0); /* Copy rendered bitmap to texture image */ const FT_Bitmap& bitmap = glyph->bitmap; CORRADE_INTERNAL_ASSERT(std::abs(bitmap.width-charPositions[i].width()) <= 2); CORRADE_INTERNAL_ASSERT(std::abs(bitmap.rows-charPositions[i].height()) <= 2); for(Int yin = 0, yout = charPositions[i].bottom(), ymax = bitmap.rows; yin != ymax; ++yin, ++yout) for(Int xin = 0, xout = charPositions[i].left(), xmax = bitmap.width; xin != xmax; ++xin, ++xout) pixmap[yout*atlasSize.x() + xout] = bitmap.buffer[(bitmap.rows-yin-1)*bitmap.width + xin]; /* Save character texture position and texture coordinates for given character index */ CORRADE_INTERNAL_ASSERT_OUTPUT(glyphs.insert({charIndices[i], std::make_tuple( Rectangle::fromSize((Vector2(glyph->bitmap_left, glyph->bitmap_top-charPositions[i].height()) - Vector2(radius))/_size, Vector2(charPositions[i].size() + 2*padding)/_size), Rectangle(Vector2(charPositions[i].bottomLeft() - padding)/atlasSize, Vector2(charPositions[i].topRight() + padding)/atlasSize) )}).second); } /* Set texture data */ #ifndef MAGNUM_TARGET_GLES output->setImage(0, Texture2D::InternalFormat::R8, &image); #else output->setImage(0, Texture2D::InternalFormat::Red, &image); #endif } void FreeTypeFont::prerender(const std::string& characters, const Vector2i& atlasSize) { prerenderInternal(characters, atlasSize, 0, &_texture); } void FreeTypeFont::prerenderDistanceField(const std::string& characters, const Vector2i& sourceAtlasSize, const Vector2i& atlasSize, Int radius) { MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_storage); /* Render input texture */ Texture2D input; input.setWrapping(Texture2D::Wrapping::ClampToEdge) ->setMinificationFilter(Texture2D::Filter::Linear) ->setMagnificationFilter(Texture2D::Filter::Linear); prerenderInternal(characters, sourceAtlasSize, radius, &input); /* Create distance field from input texture */ _texture.setStorage(1, Texture2D::InternalFormat::R8, atlasSize); TextureTools::distanceField(&input, &_texture, Rectanglei::fromSize({}, atlasSize), radius); } FreeTypeFont::~FreeTypeFont() { CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Done_Face(_ftFont) == 0); } const std::tuple<Rectangle, Rectangle>& FreeTypeFont::operator[](char32_t character) const { auto it = glyphs.find(character); if(it == glyphs.end()) return glyphs.at(0); return it->second; } AbstractLayouter* FreeTypeFont::layout(const Float size, const std::string& text) { return new FreeTypeLayouter(*this, size, text); } namespace { FreeTypeLayouter::FreeTypeLayouter(FreeTypeFont& font, const Float size, const std::string& text): font(font), size(size) { /* Get glyph codes from characters */ glyphs.reserve(text.size()); _glyphCount = text.size(); for(std::size_t i = 0; i != text.size(); ) { UnsignedInt codepoint; std::tie(codepoint, i) = Corrade::Utility::Unicode::nextChar(text, i); glyphs.push_back(FT_Get_Char_Index(font.font(), codepoint)); } } std::tuple<Rectangle, Rectangle, Vector2> FreeTypeLayouter::renderGlyph(const Vector2& cursorPosition, const UnsignedInt i) { /* Position of the texture in the resulting glyph, texture coordinates */ Rectangle texturePosition, textureCoordinates; std::tie(texturePosition, textureCoordinates) = font[glyphs[i]]; /* Load glyph */ CORRADE_INTERNAL_ASSERT_OUTPUT(FT_Load_Glyph(font.font(), glyphs[i], FT_LOAD_DEFAULT) == 0); const FT_GlyphSlot slot = font.font()->glyph; Vector2 offset = Vector2(0, 0); /** @todo really? */ Vector2 advance = Vector2(slot->advance.x, slot->advance.y)/(64*font.size()); /* Absolute quad position, composed from cursor position, glyph offset and texture position, denormalized to requested text size */ Rectangle quadPosition = Rectangle::fromSize( (cursorPosition + offset + Vector2(texturePosition.left(), texturePosition.bottom()))*size, texturePosition.size()*size); return std::make_tuple(quadPosition, textureCoordinates, advance); } } }} <|endoftext|>
<commit_before>#include "UpdateDialogWin32.h" #include "AppInfo.h" #include "Log.h" // enable themed controls // see http://msdn.microsoft.com/en-us/library/bb773175%28v=vs.85%29.aspx // for details #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") static const char* updateDialogClassName = "UPDATEDIALOG"; static std::map<HWND,UpdateDialogWin32*> windowDialogMap; // enable the standard Windows font for a widget // (typically Tahoma or Segoe UI) void setDefaultFont(HWND window) { SendMessage(window, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE, 0)); } LRESULT WINAPI updateDialogWindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { std::map<HWND,UpdateDialogWin32*>::const_iterator iter = windowDialogMap.find(window); if (iter != windowDialogMap.end()) { return iter->second->windowProc(window,message,wParam,lParam); } else { return DefWindowProc(window,message,wParam,lParam); } }; void registerWindowClass() { WNDCLASSEX wcex; ZeroMemory(&wcex,sizeof(WNDCLASSEX)); wcex.cbSize = sizeof(WNDCLASSEX); HBRUSH background = CreateSolidBrush(GetSysColor(COLOR_3DFACE)); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = updateDialogWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hIcon = LoadIcon(GetModuleHandle(0),"IDI_APPICON"); wcex.hCursor = LoadCursor(0,IDC_ARROW); wcex.hbrBackground = (HBRUSH)background; wcex.lpszMenuName = (LPCTSTR)0; wcex.lpszClassName = updateDialogClassName; wcex.hIconSm = 0; wcex.hInstance = GetModuleHandle(0); RegisterClassEx(&wcex); } UpdateDialogWin32::UpdateDialogWin32() : m_hadError(false) { registerWindowClass(); } UpdateDialogWin32::~UpdateDialogWin32() { for (std::map<HWND,UpdateDialogWin32*>::iterator iter = windowDialogMap.begin(); iter != windowDialogMap.end(); iter++) { if (iter->second == this) { std::map<HWND,UpdateDialogWin32*>::iterator oldIter = iter; ++iter; windowDialogMap.erase(oldIter); } else { ++iter; } } } void UpdateDialogWin32::init() { int width = 300; int height = 130; DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; m_window.CreateEx(0 /* dwExStyle */, updateDialogClassName /* class name */, AppInfo::name(), style, 0, 0, width, height, 0 /* parent */, 0 /* menu */, 0 /* reserved */); m_progressBar.Create(&m_window); m_finishButton.Create(&m_window); m_progressLabel.Create(&m_window); installWindowProc(&m_window); installWindowProc(&m_finishButton); setDefaultFont(m_progressLabel); setDefaultFont(m_finishButton); m_progressBar.SetRange(0,100); m_finishButton.SetWindowText("Finish"); m_finishButton.EnableWindow(false); m_progressLabel.SetWindowText("Installing Updates"); m_window.SetWindowPos(0,0,0,width,height,0); m_progressBar.SetWindowPos(0,10,40,width - 30,20,0); m_progressLabel.SetWindowPos(0,10,15,width - 30,20,0); m_finishButton.SetWindowPos(0,width-100,70,80,25,0); m_window.CenterWindow(); m_window.ShowWindow(); } void UpdateDialogWin32::exec() { m_app.Run(); } void UpdateDialogWin32::updateError(const std::string& errorMessage) { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateFailed); message->message = errorMessage; SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } void UpdateDialogWin32::updateProgress(int percentage) { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateProgress); message->progress = percentage; SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } void UpdateDialogWin32::updateFinished() { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateFinished); SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } LRESULT WINAPI UpdateDialogWin32::windowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CLOSE: if (window == m_window.GetHwnd()) { return 0; } break; case WM_COMMAND: { if (reinterpret_cast<HWND>(lParam) == m_finishButton.GetHwnd()) { PostQuitMessage(0); } } break; case WM_USER: { if (window == m_window.GetHwnd()) { UpdateMessage* message = reinterpret_cast<UpdateMessage*>(wParam); switch (message->type) { case UpdateMessage::UpdateFailed: { m_hadError = true; std::string text = AppInfo::updateErrorMessage(message->message); MessageBox(m_window.GetHwnd(),text.c_str(),"Update Problem",MB_OK); } break; case UpdateMessage::UpdateProgress: m_progressBar.SetPos(message->progress); break; case UpdateMessage::UpdateFinished: { std::string message; m_finishButton.EnableWindow(true); if (m_hadError) { message = "Update failed."; } else { message = "Updates installed."; } message += " Click 'Finish' to restart the application."; m_progressLabel.SetWindowText(message.c_str()); } break; } delete message; } } break; } return DefWindowProc(window,message,wParam,lParam); } void UpdateDialogWin32::installWindowProc(CWnd* window) { windowDialogMap[window->GetHwnd()] = this; } <commit_msg>Fix Windows compile<commit_after>#include "UpdateDialogWin32.h" #include "AppInfo.h" #include "Log.h" // enable themed controls // see http://msdn.microsoft.com/en-us/library/bb773175%28v=vs.85%29.aspx // for details #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") static const char* updateDialogClassName = "UPDATEDIALOG"; static std::map<HWND,UpdateDialogWin32*> windowDialogMap; // enable the standard Windows font for a widget // (typically Tahoma or Segoe UI) void setDefaultFont(HWND window) { SendMessage(window, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE, 0)); } LRESULT WINAPI updateDialogWindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { std::map<HWND,UpdateDialogWin32*>::const_iterator iter = windowDialogMap.find(window); if (iter != windowDialogMap.end()) { return iter->second->windowProc(window,message,wParam,lParam); } else { return DefWindowProc(window,message,wParam,lParam); } }; void registerWindowClass() { WNDCLASSEX wcex; ZeroMemory(&wcex,sizeof(WNDCLASSEX)); wcex.cbSize = sizeof(WNDCLASSEX); HBRUSH background = CreateSolidBrush(GetSysColor(COLOR_3DFACE)); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = updateDialogWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hIcon = LoadIcon(GetModuleHandle(0),"IDI_APPICON"); wcex.hCursor = LoadCursor(0,IDC_ARROW); wcex.hbrBackground = (HBRUSH)background; wcex.lpszMenuName = (LPCTSTR)0; wcex.lpszClassName = updateDialogClassName; wcex.hIconSm = 0; wcex.hInstance = GetModuleHandle(0); RegisterClassEx(&wcex); } UpdateDialogWin32::UpdateDialogWin32() : m_hadError(false) { registerWindowClass(); } UpdateDialogWin32::~UpdateDialogWin32() { for (std::map<HWND,UpdateDialogWin32*>::iterator iter = windowDialogMap.begin(); iter != windowDialogMap.end(); iter++) { if (iter->second == this) { std::map<HWND,UpdateDialogWin32*>::iterator oldIter = iter; ++iter; windowDialogMap.erase(oldIter); } else { ++iter; } } } void UpdateDialogWin32::init() { int width = 300; int height = 130; DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; m_window.CreateEx(0 /* dwExStyle */, updateDialogClassName /* class name */, AppInfo::name().c_str(), style, 0, 0, width, height, 0 /* parent */, 0 /* menu */, 0 /* reserved */); m_progressBar.Create(&m_window); m_finishButton.Create(&m_window); m_progressLabel.Create(&m_window); installWindowProc(&m_window); installWindowProc(&m_finishButton); setDefaultFont(m_progressLabel); setDefaultFont(m_finishButton); m_progressBar.SetRange(0,100); m_finishButton.SetWindowText("Finish"); m_finishButton.EnableWindow(false); m_progressLabel.SetWindowText("Installing Updates"); m_window.SetWindowPos(0,0,0,width,height,0); m_progressBar.SetWindowPos(0,10,40,width - 30,20,0); m_progressLabel.SetWindowPos(0,10,15,width - 30,20,0); m_finishButton.SetWindowPos(0,width-100,70,80,25,0); m_window.CenterWindow(); m_window.ShowWindow(); } void UpdateDialogWin32::exec() { m_app.Run(); } void UpdateDialogWin32::updateError(const std::string& errorMessage) { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateFailed); message->message = errorMessage; SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } void UpdateDialogWin32::updateProgress(int percentage) { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateProgress); message->progress = percentage; SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } void UpdateDialogWin32::updateFinished() { UpdateMessage* message = new UpdateMessage(UpdateMessage::UpdateFinished); SendNotifyMessage(m_window.GetHwnd(),WM_USER,reinterpret_cast<WPARAM>(message),0); } LRESULT WINAPI UpdateDialogWin32::windowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CLOSE: if (window == m_window.GetHwnd()) { return 0; } break; case WM_COMMAND: { if (reinterpret_cast<HWND>(lParam) == m_finishButton.GetHwnd()) { PostQuitMessage(0); } } break; case WM_USER: { if (window == m_window.GetHwnd()) { UpdateMessage* message = reinterpret_cast<UpdateMessage*>(wParam); switch (message->type) { case UpdateMessage::UpdateFailed: { m_hadError = true; std::string text = AppInfo::updateErrorMessage(message->message); MessageBox(m_window.GetHwnd(),text.c_str(),"Update Problem",MB_OK); } break; case UpdateMessage::UpdateProgress: m_progressBar.SetPos(message->progress); break; case UpdateMessage::UpdateFinished: { std::string message; m_finishButton.EnableWindow(true); if (m_hadError) { message = "Update failed."; } else { message = "Updates installed."; } message += " Click 'Finish' to restart the application."; m_progressLabel.SetWindowText(message.c_str()); } break; } delete message; } } break; } return DefWindowProc(window,message,wParam,lParam); } void UpdateDialogWin32::installWindowProc(CWnd* window) { windowDialogMap[window->GetHwnd()] = this; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/bit_count.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file bit_count.H /// @brief count bits /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_BIT_COUNT_H_ #define _MSS_BIT_COUNT_H_ #include <fapi2.H> namespace mss { /// /// @brief Count the bits in a T which are set (1) /// @tparam T an integral type. e.g., uint64_t, uint8_t /// @param[in] i_value the value to check, count /// @return uint64_t the number of bits set in the input /// template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> inline uint64_t bit_count(const T& i_value) { if (i_value == 0) { return 0; } else { return bit_count(i_value >> 1) + (i_value & 0x01); } } /// /// @brief Return the bit position of the first bit set, from the left /// @tparam T, an integral type. e.g., uint64_t, uint8_t /// @param[in] i_value the value to check /// @return uint64_t the bit position of the first set bit /// @bote assumes you checked to make sure there were bits set because it will return 0 /// template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> inline uint64_t first_bit_set(const T& i_value, const uint64_t i_pos = 0) { if (i_value == 0) { return 0; } if (fapi2::buffer<T>(i_value).template getBit(i_pos)) { return i_pos; } else { return first_bit_set(i_value, i_pos + 1); } } } #endif <commit_msg>L3 work for mss xmls<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/bit_count.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file bit_count.H /// @brief count bits /// // *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef _MSS_BIT_COUNT_H_ #define _MSS_BIT_COUNT_H_ #include <fapi2.H> namespace mss { /// /// @brief Count the bits in a T which are set (1) /// @tparam T an integral type. e.g., uint64_t, uint8_t /// @param[in] i_value the value to check, count /// @return uint64_t the number of bits set in the input /// template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> inline uint64_t bit_count(const T& i_value) { if (i_value == 0) { return 0; } else { return bit_count(i_value >> 1) + (i_value & 0x01); } } /// /// @brief Return the bit position of the first bit set, from the left /// @tparam T, an integral type. e.g., uint64_t, uint8_t /// @param[in] i_value the value to check /// @return uint64_t the bit position of the first set bit /// @bote assumes you checked to make sure there were bits set because it will return 0 /// template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> inline uint64_t first_bit_set(const T& i_value, const uint64_t i_pos = 0) { if (i_value == 0) { return 0; } if (fapi2::buffer<T>(i_value).template getBit(i_pos)) { return i_pos; } else { return first_bit_set(i_value, i_pos + 1); } } } #endif <|endoftext|>
<commit_before>/*! * \author ddubois * \date 12-Sep-18. */ #include "shaderpack_validator.hpp" #include "../json_utils.hpp" #include "../../util/utils.hpp" #include "../../../tests/src/general_test_setup.hpp" #ifdef ERROR #undef ERROR #endif namespace nova { /*! * \brief All the default values for a JSON pipeline * * If a field is in `pipeline_data` but not in this structure, it is a required field and cannot be given a * default value. It will thus cause an exception */ nlohmann::json default_graphics_pipeline = { {"parentName", ""}, {"defines", std::array<std::string, 0>{}}, {"states", std::array<std::string, 0>{}}, {"frontFace", nlohmann::json::object_t()}, {"backFace", nlohmann::json::object_t()}, {"fallback", ""}, {"depthBias", 0}, {"slopeScaledDepthBias", 0}, {"stencilRef", 0}, {"stencilReadMask", 0}, {"stencilWriteMask", 0}, {"msaaSupport", "None"}, {"primitiveMode", "Triangles"}, {"sourceBlendFactor", "One"}, {"destinationBlendFactor", "Zero"}, {"alphaSrc", "One"}, {"alphaDst", "Zero"}, {"depthFunc", "Less"}, {"renderQueue", "Opaque"}, {"fragmentShader", ""}, {"tessellationControlShader", ""}, {"tessellationEvaluationShader", ""}, {"geometryShader", ""} }; std::vector<std::string> required_graphics_pipeline_fields = {"name", "pass", "vertexFields", "vertexShader"}; nlohmann::json default_texture_format = {{"pixelFormat", "RGBA8"}, {"dimensionType", "Absolute"}}; void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report); #define PIPELINE_MSG(name, msg) ("Pipeline " + (name) + ": " + (msg)) validation_report validate_graphics_pipeline(nlohmann::json &pipeline_json) { validation_report report; const std::string name = get_json_value<std::string>(pipeline_json, "name").value_or("<NAME_MISSING>"); // Don't need to check for the name's existence here, it'll be checked with the rest of the required fields const std::string pipeline_context = "Pipeline " + name; // Check non-required fields first for(const auto &str : default_graphics_pipeline.items()) { ensure_field_exists(pipeline_json, str.key(), pipeline_context, default_graphics_pipeline, report); } // Check required items report.errors.reserve(required_graphics_pipeline_fields.size()); for(const std::string &field_name : required_graphics_pipeline_fields) { const auto &itr = pipeline_json.find(field_name); if(itr == pipeline_json.end()) { report.errors.emplace_back(PIPELINE_MSG(name, "Missing field " + field_name)); } } return report; } #define RESOURCES_MSG(msg) (std::string("Resources file: ") + (msg)) validation_report validate_shaderpack_resources_data(nlohmann::json &resources_json) { validation_report report; bool missing_textures = false; const auto &textures_itr = resources_json.find("textures"); if(textures_itr == resources_json.end()) { missing_textures = true; } else { auto &textures_array = *textures_itr; if(textures_array.empty()) { missing_textures = true; } else { for(auto &tex : textures_array) { const validation_report texture_report = validate_texture_data(tex); report.merge_in(texture_report); } } } if(missing_textures) { report.warnings.emplace_back(RESOURCES_MSG("Missing dynamic resources. If you ONLY use the backbuffer in your shaderpack, you can ignore this message")); } const nlohmann::json::iterator &samplers_itr = resources_json.find("samplers"); if(samplers_itr == resources_json.end()) { if(!missing_textures) { report.errors.emplace_back(RESOURCES_MSG("No samplers defined, but dynamic textures are defined. You need to define your own samplers to access a texture with")); } } else { nlohmann::json &all_samplers = *samplers_itr; if(!all_samplers.is_array()) { report.errors.emplace_back(RESOURCES_MSG("Samplers array must be an array, but like it isn't")); } else { for(nlohmann::json &sampler : all_samplers) { const validation_report sampler_report = validate_sampler_data(sampler); report.merge_in(sampler_report); } } } return report; } #define TEXTURE_MSG(name, msg) ("Texture " + (name) + ": " + (msg)) validation_report validate_texture_data(nlohmann::json &texture_json) { validation_report report; const auto name_maybe = get_json_value<std::string>(texture_json, "name"); std::string name; if(name_maybe) { name = name_maybe.value(); } else { name = "<NAME_MISSING>"; texture_json["name"] = name; report.errors.emplace_back(TEXTURE_MSG(name, "Missing field name")); } const auto format_itr = texture_json.find("format"); if(format_itr == texture_json.end()) { report.errors.emplace_back(TEXTURE_MSG(name, "Missing field format")); } else { const validation_report format_report = validate_texture_format(*format_itr, name); report.merge_in(format_report); } return report; } #define FORMAT_MSG(tex_name, msg) ("Format of texture " + (tex_name) + ": " + (msg)) validation_report validate_texture_format(nlohmann::json &format_json, const std::string &texture_name) { validation_report report; ensure_field_exists(format_json, "pixelFormat", "Format of texture " + texture_name, default_texture_format, report); ensure_field_exists(format_json, "dimensionType", "Format of texture " + texture_name, default_texture_format, report); const bool missing_width = format_json.find("width") == format_json.end(); if(missing_width) { report.errors.emplace_back(FORMAT_MSG(texture_name, "Missing field width")); } const bool missing_height = format_json.find("height") == format_json.end(); if(missing_height) { report.errors.emplace_back(FORMAT_MSG(texture_name, "Missing field height")); } return report; } #define SAMPLER_MSG(name, msg) ("Sampler " + (name) + ": " + (msg)) validation_report validate_sampler_data(nlohmann::json &sampler_json) { validation_report report; const std::string name = get_json_value<std::string>(sampler_json, "name").value_or("<NAME_MISSING>"); if(name == "<NAME_MISSING>") { report.errors.emplace_back(SAMPLER_MSG(name, "Missing field name")); } const bool missing_filter = sampler_json.find("filter") == sampler_json.end(); if(missing_filter) { report.errors.emplace_back(SAMPLER_MSG(name, "Missing field filter")); } const bool missing_wrap_mode = sampler_json.find("wrapMode") == sampler_json.end(); if(missing_wrap_mode) { report.errors.emplace_back(SAMPLER_MSG(name, "Missing field wrapMode")); } return report; } #define MATERIAL_MSG(name, error) ("Material " + (name) + ": " + (error)) #define MATERIAL_PASS_MSG(mat_name, pass_name, error) ("Material pass " + (pass_name) + " in material " + (mat_name) + ": " + (error)) validation_report validate_material(nlohmann::json &material_json) { validation_report report; const std::string name = get_json_value<std::string>(material_json, "name").value_or("<NAME_MISSING>"); if(name == "<NAME_MISSING>") { report.errors.emplace_back(MATERIAL_MSG(name, "Missing material name")); } const bool missing_geometry_filter = material_json.find("filter") == material_json.end(); if(missing_geometry_filter) { report.errors.emplace_back(MATERIAL_MSG(name, "Missing geometry filter")); } const bool missing_passes = material_json.find("passes") == material_json.end(); if(missing_passes) { report.errors.emplace_back(MATERIAL_MSG(name, "Missing material passes")); } else { const nlohmann::json &passes_json = material_json.at("passes"); if(!passes_json.is_array()) { report.errors.emplace_back(MATERIAL_MSG(name, "Passes field must be an array")); return report; } else if(passes_json.empty()) { report.errors.emplace_back(MATERIAL_MSG(name, "Passes field must have at least one item")); return report; } for(const auto &pass_json : passes_json) { const std::string pass_name = get_json_value<std::string>(pass_json, "name").value_or("<NAME_MISSING>"); if(pass_name == "<NAME_MISSING>") { report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, "Missing field name")); } const auto pipeline_maybe = get_json_value<std::string>(pass_json, "pipeline"); if(!pipeline_maybe) { report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, "Missing field pipeline")); } const auto bindings_itr = pass_json.find("bindings"); if(bindings_itr == pass_json.end()) { report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, "Missing field bindings")); } else { const nlohmann::json &bindings = *bindings_itr; if(bindings.empty()) { report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, "Field bindings exists but it's empty")); } } } } return report; } void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report) { if(j.find(field_name) == j.end()) { j[field_name] = default_value[field_name]; report.warnings.emplace_back(context + ": Missing field " + field_name + ". A default value of '" + j[field_name].dump() + "' will be used"); } } void print(const validation_report &report) { for(const auto &error : report.errors) { NOVA_LOG(ERROR) << error; } for(const auto &warning : report.warnings) { NOVA_LOG(DEBUG) << warning; } } void validation_report::merge_in(const validation_report &other) { errors.insert(errors.end(), other.errors.begin(), other.errors.end()); warnings.insert(warnings.begin(), other.warnings.begin(), other.warnings.end()); } } // namespace nova <commit_msg>clang-tidy: cppcoreguidelines-macro-usage<commit_after>/*! * \author ddubois * \date 12-Sep-18. */ #include "shaderpack_validator.hpp" #include "../json_utils.hpp" #include "../../util/utils.hpp" #include "../../../tests/src/general_test_setup.hpp" #include <fmt/format.h> #ifdef ERROR #undef ERROR #endif namespace nova { /*! * \brief All the default values for a JSON pipeline * * If a field is in `pipeline_data` but not in this structure, it is a required field and cannot be given a * default value. It will thus cause an exception */ nlohmann::json default_graphics_pipeline = { {"parentName", ""}, {"defines", std::array<std::string, 0>{}}, {"states", std::array<std::string, 0>{}}, {"frontFace", nlohmann::json::object_t()}, {"backFace", nlohmann::json::object_t()}, {"fallback", ""}, {"depthBias", 0}, {"slopeScaledDepthBias", 0}, {"stencilRef", 0}, {"stencilReadMask", 0}, {"stencilWriteMask", 0}, {"msaaSupport", "None"}, {"primitiveMode", "Triangles"}, {"sourceBlendFactor", "One"}, {"destinationBlendFactor", "Zero"}, {"alphaSrc", "One"}, {"alphaDst", "Zero"}, {"depthFunc", "Less"}, {"renderQueue", "Opaque"}, {"fragmentShader", ""}, {"tessellationControlShader", ""}, {"tessellationEvaluationShader", ""}, {"geometryShader", ""} }; std::vector<std::string> required_graphics_pipeline_fields = {"name", "pass", "vertexFields", "vertexShader"}; nlohmann::json default_texture_format = {{"pixelFormat", "RGBA8"}, {"dimensionType", "Absolute"}}; void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report); static std::string pipeline_msg(const std::string& name, const std::string field_name) { return format(fmt("Pipeline {:s}: Missing field {:s}"), name, field_name); } validation_report validate_graphics_pipeline(nlohmann::json &pipeline_json) { validation_report report; const std::string name = get_json_value<std::string>(pipeline_json, "name").value_or("<NAME_MISSING>"); // Don't need to check for the name's existence here, it'll be checked with the rest of the required fields const std::string pipeline_context = "Pipeline " + name; // Check non-required fields first for(const auto &str : default_graphics_pipeline.items()) { ensure_field_exists(pipeline_json, str.key(), pipeline_context, default_graphics_pipeline, report); } // Check required items report.errors.reserve(required_graphics_pipeline_fields.size()); for(const std::string &field_name : required_graphics_pipeline_fields) { const auto &itr = pipeline_json.find(field_name); if(itr == pipeline_json.end()) { report.errors.emplace_back(pipeline_msg(name, field_name)); } } return report; } static std::string resources_msg(const std::string& msg) { return format(fmt("Resources file: {:s}"), msg); } validation_report validate_shaderpack_resources_data(nlohmann::json &resources_json) { validation_report report; bool missing_textures = false; const auto &textures_itr = resources_json.find("textures"); if(textures_itr == resources_json.end()) { missing_textures = true; } else { auto &textures_array = *textures_itr; if(textures_array.empty()) { missing_textures = true; } else { for(auto &tex : textures_array) { const validation_report texture_report = validate_texture_data(tex); report.merge_in(texture_report); } } } if(missing_textures) { report.warnings.emplace_back(resources_msg("Missing dynamic resources. If you ONLY use the backbuffer in your shaderpack, you can ignore this message")); } const nlohmann::json::iterator &samplers_itr = resources_json.find("samplers"); if(samplers_itr == resources_json.end()) { if(!missing_textures) { report.errors.emplace_back(resources_msg("No samplers defined, but dynamic textures are defined. You need to define your own samplers to access a texture with")); } } else { nlohmann::json &all_samplers = *samplers_itr; if(!all_samplers.is_array()) { report.errors.emplace_back(resources_msg("Samplers array must be an array, but like it isn't")); } else { for(nlohmann::json &sampler : all_samplers) { const validation_report sampler_report = validate_sampler_data(sampler); report.merge_in(sampler_report); } } } return report; } static std::string texture_msg(const std::string& name, const std::string& msg) { return format(fmt("Texture {:s}: {:s}"), name, msg); } validation_report validate_texture_data(nlohmann::json &texture_json) { validation_report report; const auto name_maybe = get_json_value<std::string>(texture_json, "name"); std::string name; if(name_maybe) { name = name_maybe.value(); } else { name = "<NAME_MISSING>"; texture_json["name"] = name; report.errors.emplace_back(texture_msg(name, "Missing field name")); } const auto format_itr = texture_json.find("format"); if(format_itr == texture_json.end()) { report.errors.emplace_back(texture_msg(name, "Missing field format")); } else { const validation_report format_report = validate_texture_format(*format_itr, name); report.merge_in(format_report); } return report; } static std::string format_msg(const std::string& tex_name, const std::string& msg) { return format(fmt("Format of texture {:s}: {:s}"), tex_name, msg); } validation_report validate_texture_format(nlohmann::json &format_json, const std::string &texture_name) { validation_report report; const std::string context = format(fmt("Format of texture {:s}"), texture_name); ensure_field_exists(format_json, "pixelFormat", context, default_texture_format, report); ensure_field_exists(format_json, "dimensionType", context, default_texture_format, report); const bool missing_width = format_json.find("width") == format_json.end(); if(missing_width) { report.errors.emplace_back(format_msg(texture_name, "Missing field width")); } const bool missing_height = format_json.find("height") == format_json.end(); if(missing_height) { report.errors.emplace_back(format_msg(texture_name, "Missing field height")); } return report; } static std::string sampler_msg(const std::string& name, const std::string& msg) { return format(fmt("Sampler {:s}: {:s}"), name, msg); } validation_report validate_sampler_data(nlohmann::json &sampler_json) { validation_report report; const std::string name = get_json_value<std::string>(sampler_json, "name").value_or("<NAME_MISSING>"); if(name == "<NAME_MISSING>") { report.errors.emplace_back(sampler_msg(name, "Missing field name")); } const bool missing_filter = sampler_json.find("filter") == sampler_json.end(); if(missing_filter) { report.errors.emplace_back(sampler_msg(name, "Missing field filter")); } const bool missing_wrap_mode = sampler_json.find("wrapMode") == sampler_json.end(); if(missing_wrap_mode) { report.errors.emplace_back(sampler_msg(name, "Missing field wrapMode")); } return report; } static std::string material_msg(const std::string& name, const std::string& msg) { return format(fmt("Material {:s}: {:s}"), name, msg); } static std::string material_pass_msg(const std::string& mat_name, const std::string& pass_name, const std::string& error) { return format(fmt("Material pass {:s} in material {:s}: {:s}"), pass_name, mat_name, error); } validation_report validate_material(nlohmann::json &material_json) { validation_report report; const std::string name = get_json_value<std::string>(material_json, "name").value_or("<NAME_MISSING>"); if(name == "<NAME_MISSING>") { report.errors.emplace_back(material_msg(name, "Missing material name")); } const bool missing_geometry_filter = material_json.find("filter") == material_json.end(); if(missing_geometry_filter) { report.errors.emplace_back(material_msg(name, "Missing geometry filter")); } const bool missing_passes = material_json.find("passes") == material_json.end(); if(missing_passes) { report.errors.emplace_back(material_msg(name, "Missing material passes")); } else { const nlohmann::json &passes_json = material_json.at("passes"); if(!passes_json.is_array()) { report.errors.emplace_back(material_msg(name, "Passes field must be an array")); return report; } else if(passes_json.empty()) { report.errors.emplace_back(material_msg(name, "Passes field must have at least one item")); return report; } for(const auto &pass_json : passes_json) { const std::string pass_name = get_json_value<std::string>(pass_json, "name").value_or("<NAME_MISSING>"); if(pass_name == "<NAME_MISSING>") { report.errors.emplace_back(material_pass_msg(name, pass_name, "Missing field name")); } const auto pipeline_maybe = get_json_value<std::string>(pass_json, "pipeline"); if(!pipeline_maybe) { report.errors.emplace_back(material_pass_msg(name, pass_name, "Missing field pipeline")); } const auto bindings_itr = pass_json.find("bindings"); if(bindings_itr == pass_json.end()) { report.warnings.emplace_back(material_pass_msg(name, pass_name, "Missing field bindings")); } else { const nlohmann::json &bindings = *bindings_itr; if(bindings.empty()) { report.warnings.emplace_back(material_pass_msg(name, pass_name, "Field bindings exists but it's empty")); } } } } return report; } void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report) { if(j.find(field_name) == j.end()) { j[field_name] = default_value[field_name]; report.warnings.emplace_back(context + ": Missing field " + field_name + ". A default value of '" + j[field_name].dump() + "' will be used"); } } void print(const validation_report &report) { for(const auto &error : report.errors) { NOVA_LOG(ERROR) << error; } for(const auto &warning : report.warnings) { NOVA_LOG(DEBUG) << warning; } } void validation_report::merge_in(const validation_report &other) { errors.insert(errors.end(), other.errors.begin(), other.errors.end()); warnings.insert(warnings.begin(), other.warnings.begin(), other.warnings.end()); } } // namespace nova <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "statusWidget.h" #include <QMenu> #include <QFileDialog> #include <QMessageBox> statusWidget::statusWidget(QWidget* parent) { setupUi(this); QMenu* menu = new QMenu(this); menu->addAction(actionAvailable); menu->addAction(actionBusy); menu->addAction(actionAway); // menu->addAction(actionInvisible); menu->addSeparator(); menu->addAction(actionSign_out); toolButton_userName->setMenu(menu); bool check = connect(statusTextWidgetObject, SIGNAL(statusTextChanged(const QString&)), SIGNAL(statusTextChanged(const QString&))); Q_ASSERT(check); check = connect(actionAvailable, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionBusy, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionAway, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionInvisible, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionSign_out, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(pushButton_avatar, SIGNAL(clicked()), SLOT(avatarSelection())); Q_ASSERT(check); } void statusWidget::setStatusText(const QString& statusText) { statusTextWidgetObject->setStatusText(statusText); } void statusWidget::presenceMenuTriggered() { QString icon = "green"; QAction* action = qobject_cast<QAction*>(sender()); if(action == actionAvailable) { emit presenceTypeChanged(QXmppPresence::Available); icon = "green"; } else if(action == actionBusy) { emit presenceStatusTypeChanged(QXmppPresence::Status::DND); icon = "red"; } else if(action == actionAway) { emit presenceStatusTypeChanged(QXmppPresence::Status::Away); icon = "orange"; } else if(action == actionInvisible) { emit presenceStatusTypeChanged(QXmppPresence::Status::Invisible); icon = "gray"; } else if(action == actionSign_out) { emit presenceTypeChanged(QXmppPresence::Unavailable); icon = "gray"; } label->setPixmap(QPixmap(":/icons/resource/"+icon+".png")); } void statusWidget::setPresenceAndStatusType(QXmppPresence::Type presenceType, QXmppPresence::Status::Type statusType) { if(presenceType == QXmppPresence::Available) { QString icon = "green"; switch(statusType) { case QXmppPresence::Status::Online: case QXmppPresence::Status::Chat: icon = "green"; break; case QXmppPresence::Status::Away: case QXmppPresence::Status::XA: icon = "orange"; break; case QXmppPresence::Status::DND: icon = "red"; break; case QXmppPresence::Status::Invisible: case QXmppPresence::Status::Offline: icon = "gray"; break; } label->setPixmap(QPixmap(":/icons/resource/"+icon+".png")); } else if(presenceType == QXmppPresence::Unavailable) { label->setPixmap(QPixmap(":/icons/resource/gray.png")); } } void statusWidget::avatarSelection() { QString file = QFileDialog::getOpenFileName(this, "Select your avatar", QString(), QString("Images (*.png *.jpeg *.jpg)")); if(file.isEmpty()) return; QImage image; if(image.load(file)) { QImage scaled = image.scaled(QSize(96, 96), Qt::KeepAspectRatio, Qt::SmoothTransformation); emit avatarChanged(scaled); } else QMessageBox::information(this, "Avatar selection", "Invalid image file"); } void statusWidget::setDisplayName(const QString& name) { toolButton_userName->setText(name); } void statusWidget::setAvatar(const QImage& image) { pushButton_avatar->setIcon(QIcon(QPixmap::fromImage(image))); } <commit_msg>add more filters<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "statusWidget.h" #include <QMenu> #include <QFileDialog> #include <QMessageBox> statusWidget::statusWidget(QWidget* parent) { setupUi(this); QMenu* menu = new QMenu(this); menu->addAction(actionAvailable); menu->addAction(actionBusy); menu->addAction(actionAway); // menu->addAction(actionInvisible); menu->addSeparator(); menu->addAction(actionSign_out); toolButton_userName->setMenu(menu); bool check = connect(statusTextWidgetObject, SIGNAL(statusTextChanged(const QString&)), SIGNAL(statusTextChanged(const QString&))); Q_ASSERT(check); check = connect(actionAvailable, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionBusy, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionAway, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionInvisible, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(actionSign_out, SIGNAL(triggered()), SLOT(presenceMenuTriggered())); Q_ASSERT(check); check = connect(pushButton_avatar, SIGNAL(clicked()), SLOT(avatarSelection())); Q_ASSERT(check); } void statusWidget::setStatusText(const QString& statusText) { statusTextWidgetObject->setStatusText(statusText); } void statusWidget::presenceMenuTriggered() { QString icon = "green"; QAction* action = qobject_cast<QAction*>(sender()); if(action == actionAvailable) { emit presenceTypeChanged(QXmppPresence::Available); icon = "green"; } else if(action == actionBusy) { emit presenceStatusTypeChanged(QXmppPresence::Status::DND); icon = "red"; } else if(action == actionAway) { emit presenceStatusTypeChanged(QXmppPresence::Status::Away); icon = "orange"; } else if(action == actionInvisible) { emit presenceStatusTypeChanged(QXmppPresence::Status::Invisible); icon = "gray"; } else if(action == actionSign_out) { emit presenceTypeChanged(QXmppPresence::Unavailable); icon = "gray"; } label->setPixmap(QPixmap(":/icons/resource/"+icon+".png")); } void statusWidget::setPresenceAndStatusType(QXmppPresence::Type presenceType, QXmppPresence::Status::Type statusType) { if(presenceType == QXmppPresence::Available) { QString icon = "green"; switch(statusType) { case QXmppPresence::Status::Online: case QXmppPresence::Status::Chat: icon = "green"; break; case QXmppPresence::Status::Away: case QXmppPresence::Status::XA: icon = "orange"; break; case QXmppPresence::Status::DND: icon = "red"; break; case QXmppPresence::Status::Invisible: case QXmppPresence::Status::Offline: icon = "gray"; break; } label->setPixmap(QPixmap(":/icons/resource/"+icon+".png")); } else if(presenceType == QXmppPresence::Unavailable) { label->setPixmap(QPixmap(":/icons/resource/gray.png")); } } void statusWidget::avatarSelection() { QString fileFilters = QString("Images (*.png *.jpeg *.jpg *.gif *.bmp);;All Files (*.*)"); QString file = QFileDialog::getOpenFileName(this, "Select your avatar", QString(), fileFilters); if(file.isEmpty()) return; QImage image; if(image.load(file)) { QImage scaled = image.scaled(QSize(96, 96), Qt::KeepAspectRatio, Qt::SmoothTransformation); emit avatarChanged(scaled); } else QMessageBox::information(this, "Avatar selection", "Invalid image file"); } void statusWidget::setDisplayName(const QString& name) { toolButton_userName->setText(name); } void statusWidget::setAvatar(const QImage& image) { pushButton_avatar->setIcon(QIcon(QPixmap::fromImage(image))); } <|endoftext|>
<commit_before>#ifndef SILICIUM_RANGE_VALUE_HPP #define SILICIUM_RANGE_VALUE_HPP #include <boost/range/algorithm/equal.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/functional/hash.hpp> namespace Si { template <class BidirectionalRange> struct range_value { BidirectionalRange range; range_value() { } range_value(BidirectionalRange range) : range(std::move(range)) { } }; template <class BidirectionalRange1, class BidirectionalRange2> bool operator == (range_value<BidirectionalRange1> const &left, range_value<BidirectionalRange2> const &right) { return boost::range::equal(left.range, right.range); } template <class BidirectionalRange> auto make_range_value(BidirectionalRange &&range) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> range_value<typename std::decay<BidirectionalRange>::type> #endif { return range_value<typename std::decay<BidirectionalRange>::type>(std::forward<BidirectionalRange>(range)); } } namespace std { template <class BidirectionalRange> struct hash<Si::range_value<BidirectionalRange>> { std::size_t operator()(Si::range_value<BidirectionalRange> const &value) const { using boost::begin; using boost::end; return boost::hash_range(begin(value.range), end(value.range)); } }; } #endif <commit_msg>add missing include<commit_after>#ifndef SILICIUM_RANGE_VALUE_HPP #define SILICIUM_RANGE_VALUE_HPP #include <silicium/config.hpp> #include <boost/range/algorithm/equal.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/functional/hash.hpp> namespace Si { template <class BidirectionalRange> struct range_value { BidirectionalRange range; range_value() { } range_value(BidirectionalRange range) : range(std::move(range)) { } }; template <class BidirectionalRange1, class BidirectionalRange2> bool operator == (range_value<BidirectionalRange1> const &left, range_value<BidirectionalRange2> const &right) { return boost::range::equal(left.range, right.range); } template <class BidirectionalRange> auto make_range_value(BidirectionalRange &&range) #if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE -> range_value<typename std::decay<BidirectionalRange>::type> #endif { return range_value<typename std::decay<BidirectionalRange>::type>(std::forward<BidirectionalRange>(range)); } } namespace std { template <class BidirectionalRange> struct hash<Si::range_value<BidirectionalRange>> { std::size_t operator()(Si::range_value<BidirectionalRange> const &value) const { using boost::begin; using boost::end; return boost::hash_range(begin(value.range), end(value.range)); } }; } #endif <|endoftext|>
<commit_before>#ifndef VIENNAGRID_ALGORITHM_INTERSECT_HPP #define VIENNAGRID_ALGORITHM_INTERSECT_HPP /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/forwards.hpp" #include "viennagrid/algorithm/numeric.hpp" #include "viennagrid/algorithm/inner_prod.hpp" #include "viennagrid/algorithm/norm.hpp" namespace viennagrid { namespace geometry { namespace interval { struct open_tag {}; struct closed_tag {}; template<typename tag0, typename tag1> open_tag intersect_tag( tag0, tag1 ) { return open_tag(); } inline closed_tag intersect_tag ( closed_tag, closed_tag ) { return closed_tag(); } inline bool is_open(open_tag) { return true; } inline bool is_open(closed_tag) { return false; } inline bool is_closed(open_tag) { return false; } inline bool is_closed(closed_tag) { return true; } struct open_open_tag { typedef open_tag first_tag; typedef open_tag second_tag; }; struct open_closed_tag { typedef open_tag first_tag; typedef closed_tag second_tag; }; struct closed_open_tag { typedef closed_tag first_tag; typedef open_tag second_tag; }; struct closed_closed_tag { typedef closed_tag first_tag; typedef closed_tag second_tag; }; template<typename dual_tag> typename dual_tag::first_tag first_tag( dual_tag ) { return typename dual_tag::first_tag(); } template<typename dual_tag> typename dual_tag::second_tag second_tag( dual_tag ) { return typename dual_tag::second_tag(); } inline open_open_tag make_tag( open_tag, open_tag ) { return open_open_tag(); } inline open_closed_tag make_tag( open_tag, closed_tag ) { return open_closed_tag(); } inline closed_open_tag make_tag( closed_tag, open_tag ) { return closed_open_tag(); } inline closed_closed_tag make_tag( closed_tag, closed_tag ) { return closed_closed_tag(); } template<typename numeric_type> bool greater( numeric_type ref, numeric_type to_test, open_tag ) { return ref < to_test; } template<typename numeric_type> bool greater( numeric_type ref, numeric_type to_test, closed_tag ) { return ref <= to_test; } template<typename numeric_type> bool less( numeric_type ref, numeric_type to_test, open_tag ) { return ref > to_test; } template<typename numeric_type> bool less( numeric_type ref, numeric_type to_test, closed_tag ) { return ref >= to_test; } template<typename numeric_type, typename first_tag_type, typename second_tag_type> bool point_in_interval( numeric_type first, first_tag_type first_tag, numeric_type second, second_tag_type second_tag, numeric_type to_test ) { return (first <= second) ? (greater(first, to_test, first_tag) && less(second, to_test, second_tag)) : (greater(second, to_test, second_tag) && less(first, to_test, first_tag)); } template<typename numeric_type, typename dual_tag> bool point_in_interval( numeric_type first, numeric_type second, dual_tag tag, numeric_type to_test ) { return point_in_interval(first, first_tag(tag), second, second_tag(tag), to_test); } template<typename numeric_type, typename interval_0_tag_type, typename interval_1_tag_type> bool interval_intersect(numeric_type first_0, numeric_type second_0, interval_0_tag_type interval_0_tag, numeric_type first_1, numeric_type second_1, interval_1_tag_type interval_1_tag ) { return point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), first_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), first_tag(interval_1_tag)), first_1 ) || point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), second_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), second_tag(interval_1_tag)), second_1 ) || point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), first_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), first_tag(interval_0_tag)), first_0 ) || point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), second_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), second_tag(interval_0_tag)), second_0 ) || ( (first_0 == first_1) && (second_0 == second_1) && (std::abs(second_0 - first_0) > 0) ) || ( (first_0 == second_1) && (second_0 == first_1) && (std::abs(second_0 - first_0) > 0) ); } } template<typename point_type, typename numeric_config, typename line_tag> bool point_line_intersect(point_type const & p, point_type const & q0, point_type const & q1, line_tag tag, numeric_config nc ) { typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type; typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type; point_type dir = q1 - q0; point_type lhs = p - q0; inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir) ); // std::cout << " " << dir[0] << " " << lhs [0] << std::endl; if ( norm_1(dir) < relative_eps ) return false; if ( std::abs(dir[0] * lhs[1] - lhs[0] * dir[1]) < relative_eps ) { return (std::abs(dir[0]) < relative_eps) ? interval::point_in_interval(coord_type(0), dir[1], tag, lhs[1]) : interval::point_in_interval(coord_type(0), dir[0], tag, lhs[0]); } return false; } template <typename point_type, typename numeric_config, typename line1_tag, typename line2_tag> bool line_line_intersect(point_type const & v0, point_type const & v1, line1_tag tag1, //endpoints of first line point_type const & w0, point_type const & w1, line2_tag tag2, //endpoints of second line numeric_config nc ) { //typedef point_t<CoordType, CoordinateSystem> PointType; typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type; typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type; // write V(s) = v0 + s * (v1 - v0), s \in [0,1] // W(t) = w0 + t * (w1 - w0), t \in [0,1] // compute s and t assuming V(s) and W(t) to be infinite lines: // cf. http://www.softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm point_type dir_v = v1 - v0; //direction vector for line V(s) point_type dir_w = w1 - w0; //direction vector for line W(t) coord_type v_in_v = viennagrid::inner_prod(dir_v, dir_v); coord_type v_in_w = viennagrid::inner_prod(dir_v, dir_w); coord_type w_in_w = viennagrid::inner_prod(dir_w, dir_w); coord_type denominator = v_in_v * w_in_w - v_in_w * v_in_w; // std::cout << "denominator: " << denominator << std::endl; if ( std::abs(denominator) < numeric::relative_tolerance(nc, v_in_v * w_in_w) ) //lines parallel (up to round-off) { point_type lhs_v = w0 - v0; inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir_v) ); if ( std::abs(dir_v[0] * lhs_v[1] - lhs_v[0] * dir_v[1]) < relative_eps ) // lines share a common ray { std::size_t index = (std::abs(dir_v[0]) < relative_eps) ? 1 : 0; coord_type w_first = lhs_v[index]; coord_type w_second = w1[index] - v0[index]; return interval::interval_intersect( coord_type(0), dir_v[index], tag1, w_first, w_second, tag2 ); } else return false; } //Lines are not parallel: Compute minimizers s, t: point_type dir_distance = v0 - w0; //any vector connecting two points on V and W //if (inner_prod(dir_distance, dir_distance) / v_in_v < 1e-10) //v0 and w0 are the same point // return std::make_pair(v0, w0); coord_type v_in_dir_distance = viennagrid::inner_prod(dir_v, dir_distance); coord_type w_in_dir_distance = viennagrid::inner_prod(dir_w, dir_distance); coord_type s = (v_in_w * w_in_dir_distance - w_in_w * v_in_dir_distance); coord_type t = (v_in_v * w_in_dir_distance - v_in_w * v_in_dir_distance); return point_in_interval(coord_type(0), denominator, tag1, s) && point_in_interval(coord_type(0), denominator, tag2, t); } template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config> bool line_linestrip_intersect(point_iterator_type it1, const point_iterator_type & it_end, linestrip_tag_type linestrip_tag, const point_type & p0, const point_type & p1, line_tag_type line_tag, numeric_config nc ) { if (it1 == it_end) return false; point_iterator_type it2 = it1++; for (; it2 != it_end; ++it1, ++it2) { if (line_line_intersect( p0, p1, line_tag, *it1, *it2, linestrip_tag, nc )) return true; } return false; } template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config> bool line_polygon_intersect(point_iterator_type it1, point_iterator_type it_end, linestrip_tag_type linestrip_tag, const point_type & p0, const point_type & p1, line_tag_type line_tag, numeric_config nc ) { if (line_linestrip_intersect(it1, it_end, linestrip_tag, p0, p1, line_tag, nc)) return true; else return line_line_intersect( p0, p1, line_tag, *(--it_end), *it1, linestrip_tag, nc ); } } } #endif <commit_msg>added fix for numeric problem in point_in_interval added intersection_result class for return value of intersect functions added callback functor support for intersection (is called when an intersection occurs) added point - ray intersection<commit_after>#ifndef VIENNAGRID_ALGORITHM_INTERSECT_HPP #define VIENNAGRID_ALGORITHM_INTERSECT_HPP /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/forwards.hpp" #include "viennagrid/algorithm/numeric.hpp" #include "viennagrid/algorithm/inner_prod.hpp" #include "viennagrid/algorithm/norm.hpp" #include <boost/concept_check.hpp> namespace viennagrid { namespace geometry { namespace interval { struct open_tag {}; struct closed_tag {}; template<typename tag0, typename tag1> open_tag intersect_tag( tag0, tag1 ) { return open_tag(); } inline closed_tag intersect_tag ( closed_tag, closed_tag ) { return closed_tag(); } inline bool is_open(open_tag) { return true; } inline bool is_open(closed_tag) { return false; } inline bool is_closed(open_tag) { return false; } inline bool is_closed(closed_tag) { return true; } struct open_open_tag { typedef open_tag first_tag; typedef open_tag second_tag; }; struct open_closed_tag { typedef open_tag first_tag; typedef closed_tag second_tag; }; struct closed_open_tag { typedef closed_tag first_tag; typedef open_tag second_tag; }; struct closed_closed_tag { typedef closed_tag first_tag; typedef closed_tag second_tag; }; template<typename dual_tag> typename dual_tag::first_tag first_tag( dual_tag ) { return typename dual_tag::first_tag(); } template<typename dual_tag> typename dual_tag::second_tag second_tag( dual_tag ) { return typename dual_tag::second_tag(); } inline open_open_tag make_tag( open_tag, open_tag ) { return open_open_tag(); } inline open_closed_tag make_tag( open_tag, closed_tag ) { return open_closed_tag(); } inline closed_open_tag make_tag( closed_tag, open_tag ) { return closed_open_tag(); } inline closed_closed_tag make_tag( closed_tag, closed_tag ) { return closed_closed_tag(); } template<typename numeric_type> bool greater( numeric_type ref, numeric_type to_test, open_tag ) { return ref < to_test; } template<typename numeric_type> bool greater( numeric_type ref, numeric_type to_test, closed_tag ) { return ref <= to_test; } template<typename numeric_type> bool less( numeric_type ref, numeric_type to_test, open_tag ) { return ref > to_test; } template<typename numeric_type> bool less( numeric_type ref, numeric_type to_test, closed_tag ) { return ref >= to_test; } template<typename numeric_type, typename first_tag_type, typename second_tag_type, typename numeric_config> bool point_in_interval( numeric_type first, first_tag_type first_tag, numeric_type second, second_tag_type second_tag, numeric_type to_test, numeric_config nc ) { if ( numeric::is_equal(nc, first, to_test) ) return is_closed(first_tag); if ( numeric::is_equal(nc, second, to_test) ) return is_closed(second_tag); return (first <= second) ? (greater(first, to_test, first_tag) && less(second, to_test, second_tag)) : (greater(second, to_test, second_tag) && less(first, to_test, first_tag)); } template<typename numeric_type, typename dual_tag, typename numeric_config> bool point_in_interval( numeric_type first, numeric_type second, dual_tag tag, numeric_type to_test, numeric_config nc ) { return point_in_interval(first, first_tag(tag), second, second_tag(tag), to_test, nc); } template<typename numeric_type, typename interval_0_tag_type, typename interval_1_tag_type, typename numeric_config> bool interval_intersect(numeric_type first_0, numeric_type second_0, interval_0_tag_type interval_0_tag, numeric_type first_1, numeric_type second_1, interval_1_tag_type interval_1_tag, numeric_config nc) { return point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), first_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), first_tag(interval_1_tag)), first_1, nc ) || point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), second_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), second_tag(interval_1_tag)), second_1, nc ) || point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), first_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), first_tag(interval_0_tag)), first_0, nc ) || point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), second_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), second_tag(interval_0_tag)), second_0, nc ) || ( (first_0 == first_1) && (second_0 == second_1) && (std::abs(second_0 - first_0) > 0) ) || ( (first_0 == second_1) && (second_0 == first_1) && (std::abs(second_0 - first_0) > 0) ); } } class intersection_result { intersection_result() : dim_(0) {} intersection_result(int intersection_dimension_) : dim_(intersection_dimension_ + 1) {} public: int dim() const { return dim_-1; } operator bool () const { return dim_; } static intersection_result no_intersection() { return intersection_result(); } static intersection_result intersection_dimension(int intersection_dimension_) { assert(intersection_dimension_ >= 0); return intersection_result(intersection_dimension_); } private: int dim_; }; struct trivial_point_line_intersect_functor { template<typename point_type, typename line_tag> void operator() (point_type const & p, point_type const & q0, point_type const & q1, line_tag tag) {} }; template<typename point_type, typename numeric_config, typename line_tag, typename intersection_functor_type> intersection_result point_line_intersect(point_type const & p, point_type const & q0, point_type const & q1, line_tag tag, numeric_config nc, intersection_functor_type intersection_functor ) { typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type; typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type; point_type dir = q1 - q0; point_type lhs = p - q0; inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir) ); // std::cout << " " << dir[0] << " " << lhs [0] << std::endl; if ( norm_1(dir) < relative_eps ) return intersection_result::no_intersection(); if ( std::abs(dir[0] * lhs[1] - lhs[0] * dir[1]) < relative_eps ) { intersection_functor(p, q0, q1, tag); if ((std::abs(dir[0]) < relative_eps) ? interval::point_in_interval(coord_type(0), dir[1], tag, lhs[1], nc) : interval::point_in_interval(coord_type(0), dir[0], tag, lhs[0], nc)) { return intersection_result::intersection_dimension(0); } } return intersection_result::no_intersection(); } template<typename point_type, typename numeric_config, typename line_tag> intersection_result point_line_intersect(point_type const & p, point_type const & q0, point_type const & q1, line_tag tag, numeric_config nc) { trivial_point_line_intersect_functor f; return point_line_intersect(p, q0, q1, tag, nc, f); } struct trivial_point_ray_intersect_functor { template<typename point_type> void operator() (point_type const & p, point_type const & q0, point_type const & q1) {} }; template<typename point_type, typename numeric_config, typename intersection_functor_type> intersection_result point_ray_intersect(point_type const & p, point_type const & q0, point_type const & q1, numeric_config nc, intersection_functor_type intersection_functor ) { typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type; typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type; point_type dir = q1 - q0; point_type lhs = p - q0; inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir) ); // std::cout << " " << dir[0] << " " << lhs [0] << std::endl; if ( norm_1(dir) < relative_eps ) return intersection_result::no_intersection(); if ( std::abs(dir[0] * lhs[1] - lhs[0] * dir[1]) < relative_eps ) { intersection_functor(p, q0, q1); return intersection_result::intersection_dimension(0); } return intersection_result::no_intersection(); } template<typename point_type, typename numeric_config> intersection_result point_ray_intersect(point_type const & p, point_type const & q0, point_type const & q1, numeric_config nc) { trivial_point_ray_intersect_functor f; return point_ray_intersect(p, q0, q1, nc, f); } struct trivial_line_line_intersect_point_intersection_functor { template<typename point_type, typename line1_tag, typename line2_tag, typename coord_type> void operator() (point_type const & v0, point_type const & v1 , line1_tag tag1, point_type const & w0, point_type const & w1, line2_tag tag2, coord_type s, coord_type t, coord_type denominator) {} }; struct trivial_line_line_intersect_overlapping_lines_functor { template<typename point_type, typename line1_tag, typename line2_tag, typename coord_type> void operator() (point_type const & v0, point_type const & v1 , line1_tag tag1, point_type const & w0, point_type const & w1, line2_tag tag2, coord_type first1, coord_type second1, coord_type first2, coord_type second2) {} }; template <typename point_type, typename numeric_config, typename line1_tag, typename line2_tag, typename point_intersection_functor_type, typename overlapping_lines_functor_type> intersection_result line_line_intersect( point_type const & v0, point_type const & v1, line1_tag tag1, //endpoints of first line point_type const & w0, point_type const & w1, line2_tag tag2, //endpoints of second line numeric_config nc, point_intersection_functor_type point_intersection_functor, overlapping_lines_functor_type overlapping_lines_functor) { //typedef point_t<CoordType, CoordinateSystem> PointType; typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type; typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type; // write V(s) = v0 + s * (v1 - v0), s \in [0,1] // W(t) = w0 + t * (w1 - w0), t \in [0,1] // compute s and t assuming V(s) and W(t) to be infinite lines: // cf. http://www.softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm point_type dir_v = v1 - v0; //direction vector for line V(s) point_type dir_w = w1 - w0; //direction vector for line W(t) coord_type v_in_v = viennagrid::inner_prod(dir_v, dir_v); coord_type v_in_w = viennagrid::inner_prod(dir_v, dir_w); coord_type w_in_w = viennagrid::inner_prod(dir_w, dir_w); coord_type denominator = v_in_v * w_in_w - v_in_w * v_in_w; // std::cout << "denominator: " << denominator << std::endl; if ( std::abs(denominator) < numeric::relative_tolerance(nc, v_in_v * w_in_w) ) //lines parallel (up to round-off) { point_type lhs_v = w0 - v0; inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir_v) ); if ( std::abs(dir_v[0] * lhs_v[1] - lhs_v[0] * dir_v[1]) < relative_eps ) // lines share a common ray { std::size_t index = (std::abs(dir_v[0]) < relative_eps) ? 1 : 0; coord_type w_first = lhs_v[index]; coord_type w_second = w1[index] - v0[index]; if (interval::interval_intersect( coord_type(0), dir_v[index], tag1, w_first, w_second, tag2, nc )) { overlapping_lines_functor(v0, v1, tag1, w0, w1, tag2, coord_type(0), dir_v[index], w_first, w_second); return intersection_result::intersection_dimension(1); } else return intersection_result::no_intersection(); } else return intersection_result::no_intersection(); } //Lines are not parallel: Compute minimizers s, t: point_type dir_distance = v0 - w0; //any vector connecting two points on V and W //if (inner_prod(dir_distance, dir_distance) / v_in_v < 1e-10) //v0 and w0 are the same point // return std::make_pair(v0, w0); coord_type v_in_dir_distance = viennagrid::inner_prod(dir_v, dir_distance); coord_type w_in_dir_distance = viennagrid::inner_prod(dir_w, dir_distance); coord_type s = (v_in_w * w_in_dir_distance - w_in_w * v_in_dir_distance); coord_type t = (v_in_v * w_in_dir_distance - v_in_w * v_in_dir_distance); if (point_in_interval(coord_type(0), denominator, tag1, s, nc) && point_in_interval(coord_type(0), denominator, tag2, t, nc)) { point_intersection_functor(v0, v1, tag1, w0, w1, tag2, s, t, denominator); return intersection_result::intersection_dimension(0); } else return intersection_result::no_intersection(); // return point_in_interval(coord_type(0), denominator, tag1, s) && point_in_interval(coord_type(0), denominator, tag2, t); } template <typename point_type, typename numeric_config, typename line1_tag, typename line2_tag> intersection_result line_line_intersect(point_type const & v0, point_type const & v1, line1_tag tag1, //endpoints of first line point_type const & w0, point_type const & w1, line2_tag tag2, //endpoints of second line numeric_config nc) { trivial_line_line_intersect_point_intersection_functor f1; trivial_line_line_intersect_overlapping_lines_functor f2; return line_line_intersect(v0, v1, tag1, w0, w1, tag2, nc, f1, f2); } template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config> bool line_linestrip_intersect(point_iterator_type it1, const point_iterator_type & it_end, linestrip_tag_type linestrip_tag, const point_type & p0, const point_type & p1, line_tag_type line_tag, numeric_config nc ) { if (it1 == it_end) return false; point_iterator_type it2 = it1++; for (; it2 != it_end; ++it1, ++it2) { if (line_line_intersect( p0, p1, line_tag, *it1, *it2, linestrip_tag, nc )) return true; } return false; } template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config> bool line_polygon_intersect(point_iterator_type it1, point_iterator_type it_end, linestrip_tag_type linestrip_tag, const point_type & p0, const point_type & p1, line_tag_type line_tag, numeric_config nc ) { if (line_linestrip_intersect(it1, it_end, linestrip_tag, p0, p1, line_tag, nc)) return true; else return line_line_intersect( p0, p1, line_tag, *(--it_end), *it1, linestrip_tag, nc ); } } } #endif <|endoftext|>
<commit_before><commit_msg>Create lc943.cpp<commit_after><|endoftext|>
<commit_before>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> #include <knotes/version.h> #include <kdebug.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); writeString( element, "foreground-color", colorToString( foregroundColor() ) ); writeString( element, "background-color", colorToString( backgroundColor() ) ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); } QString Note::productID() const { return QString( "KNotes %s, Kolab resource" ).arg( "KNOTES_VERSION" ); } <commit_msg>Fix setting the producer tag for notes<commit_after>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se> 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> #include <knotes/version.h> #include <kdebug.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); writeString( element, "foreground-color", colorToString( foregroundColor() ) ); writeString( element, "background-color", colorToString( backgroundColor() ) ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); } QString Note::productID() const { return QString( "KNotes %1, Kolab resource" ).arg( KNOTES_VERSION ); } <|endoftext|>
<commit_before>#include "foreign.h" #include "interp.hh" #include "program.hh" #include <initializer_list> #include <list> #include <sstream> #include <string> #include <vector> using namespace std; Value::Value() : type(BOT) {} Value::Value(const bool b) : type(BOOL) { value.b = b; } Value::Value(const int i) : type(INT) { value.i = i; } Value::Value(const float d) : type(FLOAT) { value.d = d; } Value::Value(const Bool b) : type(BOOL) { value.b = b; } Value::Value(const Int i) : type(INT) { value.i = i; } Value::Value(const Float d) : type(FLOAT) { value.d = d; } Value::Value(const Param &p) { switch (p.type) { case Param::INT: type = INT; value.i = p.value.i; break; case Param::FLOAT: type = FLOAT; value.d = p.value.d; break; case Param::STRING: throw (new InterpreterError())->with(_POS); default: throw (new InterpreterError())->with(_POS); } } Value::Value(const std::initializer_list <Value> &vs) : type(VEC) { v = vector<Value>(vs); } Value::Value(const vector <Value> &vs) : type(VEC), v(vs) {} Value::Value(const list <Value> &vs) : type(LIST), l(vs) {} Value::Value(const Foreign f) : type(FOREIGN) { value.f = f; } Value::Value(const Vec_Int vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Float vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Bool vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Foreign vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } string Value::toString() const { switch (type) { case BOOL: return value.b ? "True" : "False"; case INT: return asString<int>(value.i); case FLOAT: return asString<double>(value.d); case BOT: return "null"; case VEC: { ostringstream oss; oss << "<vec>[ "; for (Value v : l.get()) oss << v.toString() << ' '; oss << "]"; return oss.str(); } case LIST: { ostringstream oss; oss << "<list>[ "; for (Value v : l.get()) oss << v.toString() << ' '; oss << "]"; return oss.str(); } case FOREIGN: return "<foreign>"; default: throw (new impossible_error())->with(_POS); } } Value::operator int() const { if (type != INT) throw (new TypeMismatchError())->with(_POS); return value.i; } Value::operator float() const { if (type != FLOAT) throw (new TypeMismatchError())->with(_POS); return value.d; } Value::operator bool() const { if (type != BOOL) throw (new TypeMismatchError())->with(_POS); return value.b; } Value::operator Int() const { if (type != INT) throw (new TypeMismatchError())->with(_POS); return value.i; } Value::operator Float() const { if (type != FLOAT) throw (new TypeMismatchError())->with(_POS); return value.d; } Value::operator Bool() const { if (type != BOOL) throw (new TypeMismatchError())->with(_POS); return value.b; } Value::operator Foreign() const { if (type != FOREIGN) throw (new TypeMismatchError())->with(_POS); return value.f } Value::operator Vec_Int() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Int r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value::operator Vec_Bool() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Bool r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value::operator Vec_Float() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Float r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value Value::operator [](int i) const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); return v.get()[i]; } vector<Value> Value::vec() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); return vector<Value>(v.get()); } list<Value> Value::lst() const { if (type != LIST) throw (new TypeMismatchError())->with(_POS); return list<Value>(l.get()); } double Value::asDouble() const { if (type == FLOAT) return value.d; else if (type == INT) return double(value.i); else throw (new TypeMismatchError())->with(_POS); } <commit_msg>Typo fix<commit_after>#include "foreign.h" #include "interp.hh" #include "program.hh" #include <initializer_list> #include <list> #include <sstream> #include <string> #include <vector> using namespace std; Value::Value() : type(BOT) {} Value::Value(const bool b) : type(BOOL) { value.b = b; } Value::Value(const int i) : type(INT) { value.i = i; } Value::Value(const float d) : type(FLOAT) { value.d = d; } Value::Value(const Bool b) : type(BOOL) { value.b = b; } Value::Value(const Int i) : type(INT) { value.i = i; } Value::Value(const Float d) : type(FLOAT) { value.d = d; } Value::Value(const Param &p) { switch (p.type) { case Param::INT: type = INT; value.i = p.value.i; break; case Param::FLOAT: type = FLOAT; value.d = p.value.d; break; case Param::STRING: throw (new InterpreterError())->with(_POS); default: throw (new InterpreterError())->with(_POS); } } Value::Value(const std::initializer_list <Value> &vs) : type(VEC) { v = vector<Value>(vs); } Value::Value(const vector <Value> &vs) : type(VEC), v(vs) {} Value::Value(const list <Value> &vs) : type(LIST), l(vs) {} Value::Value(const Foreign f) : type(FOREIGN) { value.f = f; } Value::Value(const Vec_Int vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Float vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Bool vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } Value::Value(const Vec_Foreign vi) : type(VEC) { auto res = vector<Value>{}; for (unsigned int i = 0; i < vi.len; i++) res.push_back(vi.data[i]); v = res; } string Value::toString() const { switch (type) { case BOOL: return value.b ? "True" : "False"; case INT: return asString<int>(value.i); case FLOAT: return asString<double>(value.d); case BOT: return "null"; case VEC: { ostringstream oss; oss << "<vec>[ "; for (Value v : l.get()) oss << v.toString() << ' '; oss << "]"; return oss.str(); } case LIST: { ostringstream oss; oss << "<list>[ "; for (Value v : l.get()) oss << v.toString() << ' '; oss << "]"; return oss.str(); } case FOREIGN: return "<foreign>"; default: throw (new impossible_error())->with(_POS); } } Value::operator int() const { if (type != INT) throw (new TypeMismatchError())->with(_POS); return value.i; } Value::operator float() const { if (type != FLOAT) throw (new TypeMismatchError())->with(_POS); return value.d; } Value::operator bool() const { if (type != BOOL) throw (new TypeMismatchError())->with(_POS); return value.b; } Value::operator Int() const { if (type != INT) throw (new TypeMismatchError())->with(_POS); return value.i; } Value::operator Float() const { if (type != FLOAT) throw (new TypeMismatchError())->with(_POS); return value.d; } Value::operator Bool() const { if (type != BOOL) throw (new TypeMismatchError())->with(_POS); return value.b; } Value::operator Foreign() const { if (type != FOREIGN) throw (new TypeMismatchError())->with(_POS); return value.f; } Value::operator Vec_Int() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Int r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value::operator Vec_Bool() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Bool r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value::operator Vec_Float() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); Vec_Float r; r.len = v.get().size(); for (unsigned int i = 0; i < r.len; i++) r.data[i] = v.get()[i]; return r; } Value Value::operator [](int i) const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); return v.get()[i]; } vector<Value> Value::vec() const { if (type != VEC) throw (new TypeMismatchError())->with(_POS); return vector<Value>(v.get()); } list<Value> Value::lst() const { if (type != LIST) throw (new TypeMismatchError())->with(_POS); return list<Value>(l.get()); } double Value::asDouble() const { if (type == FLOAT) return value.d; else if (type == INT) return double(value.i); else throw (new TypeMismatchError())->with(_POS); } <|endoftext|>
<commit_before>// $Id$ /** * @file makeComponentConfigurationObject.C * @brief Creation of HLT component configuration objects in OCDB * * <pre> * Usage: aliroot -b -q makeComponentConfigurationObject.C'("path", "param", "uri", runmin, runmax)' * </pre> * * Create an OCDB entry with a TObjString containing param. * Many HLT components understand configuration strings containing * arguments and parameters just like the command line arguments. * This macro facilitates the creation of an appropriate object * from a parameter string. * * Parameters: <br> * - path path of the entry within the OCDB * - param (opt) string to be stored in the TObjSting, default empty * - uri (opt) the OCDB URI, default $ALICE_ROOT * - runmin (opt) default 0 * - runmax (opt) default 999999999 * * Note: The configuration procedure of an HLT component is not * restricted to that scheme. The implementation is up to the * developer and more complex objects are possible. * * @author Matthias.Richter@ift.uib.no * @ingroup alihlt_tutorial */ void makeComponentConfigurationObject(const char* path, const char* param="", const char* cdbUri=NULL, int runmin=0, int runmax=999999999) { AliCDBManager* man = AliCDBManager::Instance(); if (!man) { cerr << "can not get AliCDBManager" << end; exit; } TString storage; if (!man->IsDefaultStorageSet()) { if (cdbUri) { storage=cdbUri; if (storage.Contains("://")!=0) { storage="local://"; storage+=cdbUri; } } else { storage="local://$ALICE_ROOT/OCDB"; } man->SetDefaultStorage(storage); } else { storage = man->GetDefaultStorage()->GetURI(); } // here is the actual content of the configuration object TObjString obj=param; AliCDBPath cdbPath(path); AliCDBId cdbId(cdbPath, runmin, runmax); AliCDBMetaData cdbMetaData; man->Put(&obj, cdbId, &cdbMetaData); cout << "adding TObjString type OCDB object " << path << " (" << (param[0]==0?"<empty>":param) << ") [" << runmin << "," << runmax << "] in " << storage << endl; } void makeComponentConfigurationObject() { cout << "===============================================================" << endl; cout << "usage: aliroot -b -q -l makeComponentConfigurationObject.C'(\"path\", \"param\", \"uri\", rangemin, rangemax)'" << endl << endl; cout << " path path of the entry within the OCDB" << endl; cout << " param (opt) string to be stored in the TObjSting, default empty" << endl; cout << " uri (opt) the OCDB URI, default $ALICE_ROOT/OCDB " << endl; cout << " rangemin (opt) default 0" << endl; cout << " rangemax (opt) default 999999999" << endl; cout << "===============================================================" << endl; } <commit_msg>bugfix: wrong logic for the 'local:/' prefix corrected<commit_after>// $Id$ /** * @file makeComponentConfigurationObject.C * @brief Creation of HLT component configuration objects in OCDB * * <pre> * Usage: aliroot -b -q makeComponentConfigurationObject.C'("path", "param", "uri", runmin, runmax)' * </pre> * * Create an OCDB entry with a TObjString containing param. * Many HLT components understand configuration strings containing * arguments and parameters just like the command line arguments. * This macro facilitates the creation of an appropriate object * from a parameter string. * * Parameters: <br> * - path path of the entry within the OCDB * - param (opt) string to be stored in the TObjSting, default empty * - uri (opt) the OCDB URI, default $ALICE_ROOT * - runmin (opt) default 0 * - runmax (opt) default 999999999 * * Note: The configuration procedure of an HLT component is not * restricted to that scheme. The implementation is up to the * developer and more complex objects are possible. * * @author Matthias.Richter@ift.uib.no * @ingroup alihlt_tutorial */ void makeComponentConfigurationObject(const char* path, const char* param="", const char* cdbUri=NULL, int runmin=0, int runmax=999999999) { AliCDBManager* man = AliCDBManager::Instance(); if (!man) { cerr << "can not get AliCDBManager" << end; exit; } TString storage; if (!man->IsDefaultStorageSet()) { if (cdbUri) { storage=cdbUri; if (storage.Contains("://")==0) { storage="local://"; storage+=cdbUri; } } else { storage="local://$ALICE_ROOT/OCDB"; } man->SetDefaultStorage(storage); } else { storage = man->GetDefaultStorage()->GetURI(); } // here is the actual content of the configuration object TObjString obj=param; AliCDBPath cdbPath(path); AliCDBId cdbId(cdbPath, runmin, runmax); AliCDBMetaData cdbMetaData; man->Put(&obj, cdbId, &cdbMetaData); cout << "adding TObjString type OCDB object " << path << " (" << (param[0]==0?"<empty>":param) << ") [" << runmin << "," << runmax << "] in " << storage << endl; } void makeComponentConfigurationObject() { cout << "===============================================================" << endl; cout << "usage: aliroot -b -q -l makeComponentConfigurationObject.C'(\"path\", \"param\", \"uri\", rangemin, rangemax)'" << endl << endl; cout << " path path of the entry within the OCDB" << endl; cout << " param (opt) string to be stored in the TObjSting, default empty" << endl; cout << " uri (opt) the OCDB URI, default $ALICE_ROOT/OCDB " << endl; cout << " rangemin (opt) default 0" << endl; cout << " rangemax (opt) default 999999999" << endl; cout << "===============================================================" << endl; } <|endoftext|>
<commit_before>/// /// @file S2_easy.cpp /// @brief Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves in parallel using OpenMP /// (Deleglise-Rivat algorithm). /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <int128.hpp> #include <min_max.hpp> #include <pmath.hpp> #include <S2Status.hpp> #include <fast_div.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace S2_easy { /// Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves. /// @param T either int64_t or uint128_t. /// template <typename T1, typename T2> T1 S2_easy(T1 x, int64_t y, int64_t z, int64_t c, vector<T2>& primes, int threads) { T1 s2_easy = 0; int64_t x13 = iroot<3>(x); int64_t thread_threshold = 1000; threads = validate_threads(threads, x13, thread_threshold); PiTable pi(y); int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_x13 = pi[x13]; S2Status status; #pragma omp parallel for schedule(dynamic, 1) num_threads(threads) reduction(+: s2_easy) for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++) { int64_t prime = primes[b]; T1 x2 = x / prime; int64_t min_trivial_leaf = min(x2 / prime, y); int64_t min_clustered_easy_leaf = (int64_t) isqrt(x2); int64_t min_sparse_easy_leaf = z / prime; int64_t min_hard_leaf = max(y / prime, prime); min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf); min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf); int64_t l = pi[min_trivial_leaf]; T1 sum = 0; // Find all clustered easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (primes[l] > min_clustered_easy_leaf) { int64_t xn = (int64_t) fast_div(x2, primes[l]); int64_t phi_xn = pi[xn] - b + 2; int64_t last_prime = primes[b + phi_xn - 1]; int64_t xm = max((int64_t) fast_div(x2, last_prime), min_clustered_easy_leaf); int64_t l2 = pi[xm]; sum += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int64_t xn = (int64_t) fast_div(x2, primes[l]); sum += pi[xn] - b + 2; } if (print_status()) status.print(b, pi_x13); s2_easy += sum; } return s2_easy; } } // namespace S2_easy } // namespace namespace primecount { int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { print(""); print("=== S2_easy(x, y) ==="); print("Computation of the easy special leaves"); print(x, y, c, threads); double time = get_wtime(); vector<int32_t> primes = generate_primes(y); int64_t s2_easy = S2_easy::S2_easy((intfast64_t) x, y, z, c, primes, threads); print("S2_easy", s2_easy, time); return s2_easy; } #ifdef HAVE_INT128_T int128_t S2_easy(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { print(""); print("=== S2_easy(x, y) ==="); print("Computation of the easy special leaves"); print(x, y, c, threads); double time = get_wtime(); int128_t s2_easy; // uses less memory if (y <= std::numeric_limits<uint32_t>::max()) { vector<uint32_t> primes = generate_primes<uint32_t>(y); s2_easy = S2_easy::S2_easy((intfast128_t) x, y, z, c, primes, threads); } else { vector<int64_t> primes = generate_primes<int64_t>(y); s2_easy = S2_easy::S2_easy((intfast128_t) x, y, z, c, primes, threads); } print("S2_easy", s2_easy, time); return s2_easy; } #endif } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file S2_easy.cpp /// @brief Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves in parallel using OpenMP /// (Deleglise-Rivat algorithm). /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <int128.hpp> #include <min_max.hpp> #include <pmath.hpp> #include <S2Status.hpp> #include <fast_div.hpp> #include <stdint.h> #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace S2_easy { /// Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves. /// @param T either int64_t or uint128_t. /// template <typename T1, typename T2> T1 S2_easy(T1 x, int64_t y, int64_t z, int64_t c, vector<T2>& primes, int threads) { T1 s2_easy = 0; int64_t x13 = iroot<3>(x); int64_t thread_threshold = 1000; threads = validate_threads(threads, x13, thread_threshold); PiTable pi(y); int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_x13 = pi[x13]; S2Status status; #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy) for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++) { int64_t prime = primes[b]; T1 x2 = x / prime; int64_t min_trivial_leaf = min(x2 / prime, y); int64_t min_clustered_easy_leaf = (int64_t) isqrt(x2); int64_t min_sparse_easy_leaf = z / prime; int64_t min_hard_leaf = max(y / prime, prime); min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf); min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf); int64_t l = pi[min_trivial_leaf]; T1 sum = 0; // Find all clustered easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (primes[l] > min_clustered_easy_leaf) { int64_t xn = (int64_t) fast_div(x2, primes[l]); int64_t phi_xn = pi[xn] - b + 2; int64_t last_prime = primes[b + phi_xn - 1]; int64_t xm = max((int64_t) fast_div(x2, last_prime), min_clustered_easy_leaf); int64_t l2 = pi[xm]; sum += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int64_t xn = (int64_t) fast_div(x2, primes[l]); sum += pi[xn] - b + 2; } if (print_status()) status.print(b, pi_x13); s2_easy += sum; } return s2_easy; } } // namespace S2_easy } // namespace namespace primecount { int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { print(""); print("=== S2_easy(x, y) ==="); print("Computation of the easy special leaves"); print(x, y, c, threads); double time = get_wtime(); vector<int32_t> primes = generate_primes(y); int64_t s2_easy = S2_easy::S2_easy((intfast64_t) x, y, z, c, primes, threads); print("S2_easy", s2_easy, time); return s2_easy; } #ifdef HAVE_INT128_T int128_t S2_easy(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { print(""); print("=== S2_easy(x, y) ==="); print("Computation of the easy special leaves"); print(x, y, c, threads); double time = get_wtime(); int128_t s2_easy; // uses less memory if (y <= std::numeric_limits<uint32_t>::max()) { vector<uint32_t> primes = generate_primes<uint32_t>(y); s2_easy = S2_easy::S2_easy((intfast128_t) x, y, z, c, primes, threads); } else { vector<int64_t> primes = generate_primes<int64_t>(y); s2_easy = S2_easy::S2_easy((intfast128_t) x, y, z, c, primes, threads); } print("S2_easy", s2_easy, time); return s2_easy; } #endif } // namespace primecount <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" #if defined(__ANDROID__) #include <android/api-level.h> #endif _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) \ && (!defined(__ANDROID__) || __ANDROID_API__ >= 23) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = errno; int ret; if ((ret = ::strerror_r(ev, buffer, strerror_buff_size)) != 0) { // If `ret == -1` then the error is specified using `errno`, otherwise // `ret` represents the error. const int new_errno = ret == -1 ? errno : ret; errno = old_errno; if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; _VSTD::abort(); #endif } _LIBCPP_END_NAMESPACE_STD <commit_msg>external/libcxx: Replace errno with set/get_errno<commit_after>/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" #if defined(__ANDROID__) #include <android/api-level.h> #endif _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) \ && (!defined(__ANDROID__) || __ANDROID_API__ >= 23) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = get_errno(); int ret; if ((ret = ::strerror_r(ev, buffer, strerror_buff_size)) != 0) { // If `ret == -1` then the error is specified using `get_errno()`, otherwise // `ret` represents the error. const int new_errno = ret == -1 ? get_errno() : ret; set_errno(old_errno); if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; _VSTD::abort(); #endif } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>#include <GLFW/glfw3.h> #include <cstring> #include <stdlib.h> // srand, rand #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds #include "math.h" #include <windows.h> #include <stdbool.h> #define pi 3.14159265358979 const int width = 1366; //ĵ const int height = 768; //ĵ float* pixels = new float[width*height * 3];// ȼ 迭 . ػ x 3(rgb)Դϴ. double xpos, ypos;//콺 Ŀ ġ ( xpos, ypos) /*콺 Ŀ ٱ ִ Ǵϱ Լ*/ bool incircle(const int& i,const int& j,const int& r)//콺 Ŀ ٱ ִ Ǵϱ Լ { if ((xpos - i)*(xpos - i) + (ypos - j)*(ypos - j) <= r*r)//̸ { return true; } else //̸ܺ { return false; } } /*ȼ迭 (rgb) ִ Լ */ void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue) { pixels[(i + width* j) * 3 + 0] = red; pixels[(i + width* j) * 3 + 1] = green; pixels[(i + width* j) * 3 + 2] = blue; } /* ִ̾ ׸ Լ*/ void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue) { if (i1 - i0 == 0)// Լ и 0̸ x2-x1 ̰ 0̸ Ƿ 0϶ yุ׸°. { for (int i = j0;i < j1;i++) { drawPixel(i1, i, red, green, blue); } } else if ((j1 - j0) != 0)//Ⱑ 0̾ƴ ϰ { for (int i = i0; i < i1; i++) { const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0; drawPixel(i, j, red, green, blue);// i j rgb ׸ drawPixel(i, j - 1, red, green, blue);drawPixel(i, j + 1, red, green, blue);// ȼ ⶧ ߰־ϴ. } } else//ϰ { for (int i = i0; i < i1; i++) { const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0; drawPixel(i, j, red, green, blue);// i j rgb ׸ } } } /*1ȼ ̻ β ׸ Լ*/ void thickLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue) { if (i1 - i0 == 0)//α׸ { for (int i = j0;i < j1;i++) { for (int j = 0;j < 10;j++)//ȼ x 10ŭ ϴ.(β°) { drawPixel(i1 + j, i, red, green, blue); } } } else if ((j1 - j0) != 0) { for (int i = i0; i < i1; i++) { const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0; for (int k = 0;k < 10;k++) { drawPixel(i, j, red, green, blue);// i j rgb ׸ drawPixel(i, j - k, red, green, blue);drawPixel(i, j + k, red, green, blue); } } } else { for (int i = i0; i < i1; i++) { const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0; drawPixel(i, j, red, green, blue);// i j rgb ׸ } } } /* ׸ Լ*/ void drawcircle(const int& x1, const int& y1, const int& r, const float& red, const float& green, const float& blue) { float i = 0.0; float rad_to_deg = 0.0; float degree = 360.0; int x2 = 0, y2 = 0; for (degree = 0;degree < 360;degree++) { rad_to_deg = degree*(pi / 180); x2 = x1 + r*sin(rad_to_deg); y2 = y1 + r*cos(rad_to_deg); drawPixel(x2, y2, red, green, blue); drawPixel(x2 + 1, y2, red, green, blue); drawPixel(x2, y2 - 1, red, green, blue); } } /* 簢 ׸*/ void drawsqaure() { drawLine(650, 600, 750, 600, 1.0f, 0.0f, 0.0f); drawLine(650, 500, 650, 600, 1.0f, 0.0f, 0.0f); drawLine(650, 500, 750, 500, 1.0f, 0.0f, 0.0f); drawLine(750, 500, 750, 601, 1.0f, 0.0f, 0.0f); } /*ﰢ ׸*/ void drawtriangle() { drawLine(100, 100, 200, 250, 1.0f, 0.0f, 0.0f); drawLine(100, 100, 300, 100, 1.0f, 0.0f, 0.0f); drawLine(200, 250, 300, 100, 1.0f, 0.0f, 0.0f); } void drawOnPixelBuffer() { //std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work std::fill_n(pixels, width*height * 3, 1.0f); // white background } void draw() { float r,g,b=0.0f; ypos = height - ypos; printf("xpos =%lf ypos= %lf\n", xpos, ypos); const int i_center = 800, j_center = 450; const int thickness = 100; drawsqaure(); thickLine(150, 500, 250, 600, 1.0f, 0.0f, 0.0f); drawcircle(450, 550,30 , 1.0f, 0.0f, 0.0f); //x drawLine(900, 500, 1000, 600, 1.0f, 0.0f, 0.0f); drawLine(900, 600, 1000, 500, 1.0f, 0.0f, 0.0f); //x drawLine(1200, 500, 1200, 600, 1.0f, 0.0f, 0.0f); drawLine(1170, 530, 1200, 500, 1.0f, 0.0f, 0.0f); drawLine(1200, 500, 1230, 530, 1.0f, 0.0f, 0.0f); //down arrow drawLine(150, 200, 250, 200, 1.0f, 0.0f, 0.0f); drawLine(230, 230, 250, 200, 1.0f, 0.0f, 0.0f); drawLine(230, 170, 250, 200, 1.0f, 0.0f, 0.0f); // right arrow drawLine(400, 160, 450, 260, 1.0f, 0.0f, 0.0f); drawLine(450, 260, 500, 160, 1.0f, 0.0f, 0.0f); drawLine(420, 200, 480, 200, 1.0f, 0.0f, 0.0f); // draw 'A' drawLine(700, 160, 700, 260, 1.0f, 0.0f, 0.0f); //draw l drawLine(900, 200, 1000, 200, 1.0f, 0.0f, 0.0f); drawLine(900, 200, 930, 230, 1.0f, 0.0f, 0.0f); drawLine(900, 200, 930, 170, 1.0f, 0.0f, 0.0f); //draw left arrow drawLine(1200, 160, 1200, 260, 1.0f, 0.0f, 0.0f); drawLine(1170, 230, 1200, 260, 1.0f, 0.0f, 0.0f); drawLine(1200, 260, 1230, 230, 1.0f, 0.0f, 0.0f); for (int i = 200;i < 768;i += 350) { for (int j = 200;j < 1366;j+=250) { if (incircle(j,i,100)== true) { r = 0.0f; g = 0.0f; b = 1.0f; } else { r = 0.0f; g = 0.0f; b = 0.0f; } drawcircle(j, i, 100, r, g, b); } } } int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(width, height, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glClearColor(1, 1, 1, 1); // while background /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { glfwGetCursorPos(window, &xpos, &ypos); /* Render here */ glClear(GL_COLOR_BUFFER_BIT); drawOnPixelBuffer(); //TODO: RGB struct //Make a pixel drawing function //Make a line drawing function draw(); glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } glfwTerminate(); delete[] pixels; // or you may reuse pixels array return 0; } <commit_msg>Delete 20160926_Source.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "sk_tool_utils.h" #include "SkRandom.h" #if SK_SUPPORT_GPU #include "etc1.h" #include "GrContext.h" #include "GrGpu.h" #include "GrRenderTargetContext.h" #include "GrRenderTargetContextPriv.h" #include "GrTextureProxy.h" #include "effects/GrSimpleTextureEffect.h" #include "ops/GrFillRectOp.h" // Basic test of Ganesh's ETC1 support class ETC1GM : public skiagm::GM { public: ETC1GM() { this->setBGColor(0xFFCCCCCC); } protected: SkString onShortName() override { return SkString("etc1"); } SkISize onISize() override { return SkISize::Make(kTexWidth + 2*kPad, kTexHeight + 2*kPad); } void onOnceBeforeDraw() override { SkBitmap bm; SkImageInfo ii = SkImageInfo::Make(kTexWidth, kTexHeight, kRGB_565_SkColorType, kOpaque_SkAlphaType); bm.allocPixels(ii); bm.erase(SK_ColorBLUE, SkIRect::MakeWH(kTexWidth, kTexHeight)); for (int y = 0; y < kTexHeight; y += 4) { for (int x = 0; x < kTexWidth; x += 4) { bm.erase((x+y) % 8 ? SK_ColorRED : SK_ColorGREEN, SkIRect::MakeXYWH(x, y, 4, 4)); } } int size = etc1_get_encoded_data_size(bm.width(), bm.height()); fETC1Data.reset(size); unsigned char* pixels = (unsigned char*) fETC1Data.get(); if (etc1_encode_image((unsigned char*) bm.getAddr16(0, 0), bm.width(), bm.height(), 2, bm.rowBytes(), pixels)) { fETC1Data.reset(); } } void onDraw(SkCanvas* canvas) override { GrRenderTargetContext* renderTargetContext = canvas->internal_private_accessTopLayerRenderTargetContext(); if (!renderTargetContext) { skiagm::GM::DrawGpuOnlyMessage(canvas); return; } GrContext* context = canvas->getGrContext(); if (!context) { return; } GrBackendTexture tex = context->contextPriv().getGpu()->createTestingOnlyBackendTexture( fETC1Data.get(), kTexWidth, kTexHeight, GrColorType::kRGB_ETC1, false, GrMipMapped::kNo, kTexWidth/2); // rowbytes are meaningless for compressed textures, but this is // basically right if (!tex.isValid()) { return; } auto proxy = context->contextPriv().proxyProvider()->wrapBackendTexture( tex, kTopLeft_GrSurfaceOrigin, kAdopt_GrWrapOwnership, kRead_GrIOType); if (!proxy) { return; } const SkMatrix trans = SkMatrix::MakeTrans(-kPad, -kPad); auto fp = GrSimpleTextureEffect::Make(proxy, trans); GrPaint grPaint; grPaint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc)); grPaint.addColorFragmentProcessor(std::move(fp)); SkRect rect = SkRect::MakeXYWH(kPad, kPad, kTexWidth, kTexHeight); renderTargetContext->priv().testingOnly_addDrawOp( GrFillRectOp::Make(context, std::move(grPaint), GrAAType::kNone, SkMatrix::I(), rect)); } private: static const int kPad = 8; static const int kTexWidth = 16; static const int kTexHeight = 20; SkAutoTMalloc<char> fETC1Data; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ETC1GM;) #endif <commit_msg>Fix etc1 GM in preReleaseGpuContext mode.<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "sk_tool_utils.h" #include "SkRandom.h" #if SK_SUPPORT_GPU #include "etc1.h" #include "GrContext.h" #include "GrGpu.h" #include "GrRenderTargetContext.h" #include "GrRenderTargetContextPriv.h" #include "GrTextureProxy.h" #include "effects/GrSimpleTextureEffect.h" #include "ops/GrFillRectOp.h" // Basic test of Ganesh's ETC1 support class ETC1GM : public skiagm::GM { public: ETC1GM() { this->setBGColor(0xFFCCCCCC); } protected: SkString onShortName() override { return SkString("etc1"); } SkISize onISize() override { return SkISize::Make(kTexWidth + 2*kPad, kTexHeight + 2*kPad); } void onOnceBeforeDraw() override { SkBitmap bm; SkImageInfo ii = SkImageInfo::Make(kTexWidth, kTexHeight, kRGB_565_SkColorType, kOpaque_SkAlphaType); bm.allocPixels(ii); bm.erase(SK_ColorBLUE, SkIRect::MakeWH(kTexWidth, kTexHeight)); for (int y = 0; y < kTexHeight; y += 4) { for (int x = 0; x < kTexWidth; x += 4) { bm.erase((x+y) % 8 ? SK_ColorRED : SK_ColorGREEN, SkIRect::MakeXYWH(x, y, 4, 4)); } } int size = etc1_get_encoded_data_size(bm.width(), bm.height()); fETC1Data.reset(size); unsigned char* pixels = (unsigned char*) fETC1Data.get(); if (etc1_encode_image((unsigned char*) bm.getAddr16(0, 0), bm.width(), bm.height(), 2, bm.rowBytes(), pixels)) { fETC1Data.reset(); } } void onDraw(SkCanvas* canvas) override { GrRenderTargetContext* renderTargetContext = canvas->internal_private_accessTopLayerRenderTargetContext(); if (!renderTargetContext) { skiagm::GM::DrawGpuOnlyMessage(canvas); return; } GrContext* context = canvas->getGrContext(); if (!context || context->abandoned()) { return; } GrBackendTexture tex = context->contextPriv().getGpu()->createTestingOnlyBackendTexture( fETC1Data.get(), kTexWidth, kTexHeight, GrColorType::kRGB_ETC1, false, GrMipMapped::kNo, kTexWidth/2); // rowbytes are meaningless for compressed textures, but this is // basically right if (!tex.isValid()) { return; } auto proxy = context->contextPriv().proxyProvider()->wrapBackendTexture( tex, kTopLeft_GrSurfaceOrigin, kAdopt_GrWrapOwnership, kRead_GrIOType); if (!proxy) { return; } const SkMatrix trans = SkMatrix::MakeTrans(-kPad, -kPad); auto fp = GrSimpleTextureEffect::Make(proxy, trans); GrPaint grPaint; grPaint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc)); grPaint.addColorFragmentProcessor(std::move(fp)); SkRect rect = SkRect::MakeXYWH(kPad, kPad, kTexWidth, kTexHeight); renderTargetContext->priv().testingOnly_addDrawOp( GrFillRectOp::Make(context, std::move(grPaint), GrAAType::kNone, SkMatrix::I(), rect)); } private: static const int kPad = 8; static const int kTexWidth = 16; static const int kTexHeight = 20; SkAutoTMalloc<char> fETC1Data; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ETC1GM;) #endif <|endoftext|>
<commit_before>/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - a 3rd pot allows speed tuning * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - TODO LATER other pins for ADC pots and 2 push buttons * - on ATtinyX4 based boards: * - TODO */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include <fastarduino/Timer.hh> #include "Multiplexer.hh" #include "TestData.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::Timer TIMER_DISPLAY = Board::Timer::TIMER0; static constexpr const Board::TimerPrescaler PRESCALER_DISPLAY = Board::TimerPrescaler::DIV_256; static constexpr const Board::Timer TIMER_PROGRESS = Board::Timer::TIMER1; static constexpr const Board::TimerPrescaler PRESCALER_PROGRESS = Board::TimerPrescaler::DIV_1024; USE_TIMER0(); USE_TIMER1(); #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2; static constexpr const Board::Timer TIMER_DISPLAY = Board::Timer::TIMER0; static constexpr const Board::TimerPrescaler PRESCALER_DISPLAY = Board::TimerPrescaler::DIV_256; USE_TIMER0(); #else #error "Current target is not yet supported!" #endif static constexpr const uint16_t REFRESH_PERIOD_MS = 2; static constexpr const uint16_t PROGRESS_PERIOD_MS = 2000; static constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS / REFRESH_PERIOD_MS; static constexpr const uint8_t BLINKING_COUNTER = 20; using MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>; static constexpr const uint8_t ROWS = MULTIPLEXER::ROWS; static constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS; //TODO Make it a template based on game size (num rows, num columns) //TODO Make a class to hold one generation and access its members? class GameOfLife { public: GameOfLife(uint8_t game[ROWS]):_current_generation(game) {} void progress_game() { uint8_t next_generation[ROWS]; for (uint8_t row = 0; row < ROWS; ++row) for (uint8_t col = 0; col < COLUMNS; ++col) { uint8_t count_neighbours = neighbours(row, col); switch (count_neighbours) { case 3: // cell is alive next_generation[row] |= _BV(col); break; case 4: // cell state is kept if (_current_generation[row] & _BV(col)) next_generation[row] |= _BV(col); else next_generation[row] &= ~_BV(col); break; default: // cell state is dead next_generation[row] &= ~_BV(col); break; } } // Copy next generation to current one for (uint8_t row = 0; row < ROWS; ++row) _current_generation[row] = next_generation[row]; } private: static uint8_t neighbours_in_row(uint8_t game_row, uint8_t col) { //TODO possibly optimize by: // - copy row to GPIOR0 // - rotate GPIOR (col+1) times // check individual bits 0, 1 and 2 uint8_t count = (game_row & _BV(col)) ? 1 : 0; if (game_row & _BV(col ? col - 1 : COLUMNS - 1)) ++count; if (game_row & _BV(col == COLUMNS - 1 ? 0 : col + 1)) ++count; return count; } uint8_t neighbours(uint8_t row, uint8_t col) { uint8_t count = neighbours_in_row(row ? _current_generation[row - 1] : _current_generation[ROWS - 1], col); count += neighbours_in_row(row == ROWS - 1 ? _current_generation[0] : _current_generation[row + 1], col); count += neighbours_in_row(_current_generation[row], col); return count; } uint8_t* _current_generation; }; class DisplayRefresher: public TimerCallback { public: DisplayRefresher(MULTIPLEXER& mux):_mux(mux) {} virtual void on_timer() override { _mux.refresh(); } private: MULTIPLEXER& _mux; }; class GameProgresser: public TimerCallback { public: GameProgresser(GameOfLife& game): _game(game) {} virtual void on_timer() override { _game.progress_game(); } private: GameOfLife& _game; }; // OPEN POINTS/TODO // - Use TIMER vectors or not? For refresh, for game progress or for both? // - Use INT/PCI Vectors for start/stop and other buttons? Normally not needed // - Implement initial board setup (with 3 buttons at first: previous, next, select/unselect) // - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16) int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); // Initialize Multiplexer MULTIPLEXER mux; for (uint8_t i = 0; i < MULTIPLEXER::ROWS; ++i) mux.data()[i] = data[i]; // Initialize game board GameOfLife game{mux.data()}; DisplayRefresher display_refresher{mux}; Timer<TIMER_DISPLAY> display_timer{display_refresher}; display_timer.begin(PRESCALER_DISPLAY, F_CPU / 1000 / _BV(uint8_t(PRESCALER_DISPLAY)) * REFRESH_PERIOD_MS - 1); GameProgresser game_progresser{game}; Timer<TIMER_PROGRESS> progress_timer{game_progresser}; progress_timer.begin(PRESCALER_PROGRESS, F_CPU / 1000 / _BV(uint8_t(PRESCALER_PROGRESS)) * PROGRESS_PERIOD_MS - 1); // Loop to light every LED for one second // uint16_t progress_counter = 0; while (true) { // mux.refresh(); // Time::delay_ms(PROGRESS_PERIOD_MS); // if (++progress_counter == PROGRESS_COUNTER) // { // game.progress_game(); // progress_counter = 0; // } } return 0; } <commit_msg>Test conway with 2 Timers (1 for display refresh, 1 for progressing game). Very inefficient in code size.<commit_after>/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - a 3rd pot allows speed tuning * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - TODO LATER other pins for ADC pots and 2 push buttons * - on ATtinyX4 based boards: * - TODO */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include <fastarduino/Timer.hh> #include "Multiplexer.hh" #include "TestData.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::Timer TIMER_DISPLAY = Board::Timer::TIMER0; static constexpr const Board::TimerPrescaler PRESCALER_DISPLAY = Board::TimerPrescaler::DIV_256; static constexpr const Board::Timer TIMER_PROGRESS = Board::Timer::TIMER1; static constexpr const Board::TimerPrescaler PRESCALER_PROGRESS = Board::TimerPrescaler::DIV_1024; USE_TIMER0(); USE_TIMER1(); #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2; static constexpr const Board::Timer TIMER_DISPLAY = Board::Timer::TIMER0; static constexpr const Board::TimerPrescaler PRESCALER_DISPLAY = Board::TimerPrescaler::DIV_256; static constexpr const Board::Timer TIMER_PROGRESS = Board::Timer::TIMER1; static constexpr const Board::TimerPrescaler PRESCALER_PROGRESS = Board::TimerPrescaler::DIV_1024; USE_TIMER0(); USE_TIMER1(); #else #error "Current target is not yet supported!" #endif static constexpr const uint16_t REFRESH_PERIOD_MS = 2; static constexpr const uint16_t PROGRESS_PERIOD_MS = 2000; static constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS / REFRESH_PERIOD_MS; static constexpr const uint8_t BLINKING_COUNTER = 20; using MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>; static constexpr const uint8_t ROWS = MULTIPLEXER::ROWS; static constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS; //TODO Make it a template based on game size (num rows, num columns) //TODO Make a class to hold one generation and access its members? class GameOfLife { public: GameOfLife(uint8_t game[ROWS]):_current_generation(game) {} void progress_game() { uint8_t next_generation[ROWS]; for (uint8_t row = 0; row < ROWS; ++row) for (uint8_t col = 0; col < COLUMNS; ++col) { uint8_t count_neighbours = neighbours(row, col); switch (count_neighbours) { case 3: // cell is alive next_generation[row] |= _BV(col); break; case 4: // cell state is kept if (_current_generation[row] & _BV(col)) next_generation[row] |= _BV(col); else next_generation[row] &= ~_BV(col); break; default: // cell state is dead next_generation[row] &= ~_BV(col); break; } } // Copy next generation to current one for (uint8_t row = 0; row < ROWS; ++row) _current_generation[row] = next_generation[row]; } private: static uint8_t neighbours_in_row(uint8_t game_row, uint8_t col) { //TODO possibly optimize by: // - copy row to GPIOR0 // - rotate GPIOR (col+1) times // check individual bits 0, 1 and 2 uint8_t count = (game_row & _BV(col)) ? 1 : 0; if (game_row & _BV(col ? col - 1 : COLUMNS - 1)) ++count; if (game_row & _BV(col == COLUMNS - 1 ? 0 : col + 1)) ++count; return count; } uint8_t neighbours(uint8_t row, uint8_t col) { uint8_t count = neighbours_in_row(row ? _current_generation[row - 1] : _current_generation[ROWS - 1], col); count += neighbours_in_row(row == ROWS - 1 ? _current_generation[0] : _current_generation[row + 1], col); count += neighbours_in_row(_current_generation[row], col); return count; } uint8_t* _current_generation; }; class DisplayRefresher: public TimerCallback { public: DisplayRefresher(MULTIPLEXER& mux):_mux(mux) {} virtual void on_timer() override { _mux.refresh(); } private: MULTIPLEXER& _mux; }; class GameProgresser: public TimerCallback { public: GameProgresser(GameOfLife& game): _game(game) {} virtual void on_timer() override { _game.progress_game(); } private: GameOfLife& _game; }; // OPEN POINTS/TODO // - Use TIMER vectors or not? For refresh, for game progress or for both? // - Use INT/PCI Vectors for start/stop and other buttons? Normally not needed // - Implement initial board setup (with 3 buttons at first: previous, next, select/unselect) // - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16) int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); // Initialize Multiplexer MULTIPLEXER mux; for (uint8_t i = 0; i < MULTIPLEXER::ROWS; ++i) mux.data()[i] = data[i]; // Initialize game board GameOfLife game{mux.data()}; DisplayRefresher display_refresher{mux}; Timer<TIMER_DISPLAY> display_timer{display_refresher}; display_timer.begin(PRESCALER_DISPLAY, F_CPU / 1000 / _BV(uint8_t(PRESCALER_DISPLAY)) * REFRESH_PERIOD_MS - 1); GameProgresser game_progresser{game}; Timer<TIMER_PROGRESS> progress_timer{game_progresser}; progress_timer.begin(PRESCALER_PROGRESS, F_CPU / 1000 / _BV(uint8_t(PRESCALER_PROGRESS)) * PROGRESS_PERIOD_MS - 1); // Loop to light every LED for one second // uint16_t progress_counter = 0; while (true) { // mux.refresh(); // Time::delay_ms(PROGRESS_PERIOD_MS); // if (++progress_counter == PROGRESS_COUNTER) // { // game.progress_game(); // progress_counter = 0; // } } return 0; } <|endoftext|>
<commit_before>/* * The MIT License * * Copyright 2017-2018 Norwegian University of Technology * * 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 <iostream> #include <fmi4cpp/fmi2/fmi4cpp.hpp> #include <fmi4cpp/tools/os_util.hpp> using namespace std; using namespace fmi4cpp::fmi2; namespace logger = fmi4cpp::logger; const double stop = 10.0; const double step_size = 1E-4; const fmi2ValueReference vr = 46; int main() { const string fmu_path = string(getenv("TEST_FMUs")) + "/2.0/cs/" + getOs() + "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu"; auto fmu = Fmu(fmu_path).asCoSimulationFmu(); for (const auto &v : *fmu->getModelDescription()->modelVariables()) { if (v.causality() == Causality::output) { logger::info("nNme={}", v.name()); } } auto slave = fmu->newInstance(); slave->setupExperiment(); slave->enterInitializationMode(); slave->exitInitializationMode(); clock_t begin = clock(); double t; double ref; while ((t = slave->getSimulationTime()) <= (stop - step_size)) { if (!slave->doStep(step_size)) { logger::error("Error! doStep returned with status: {}", to_string(slave->getLastStatus())); break; } if (!slave->readReal(vr, ref)) { logger::error("Error! readReal returned with status: {}", to_string(slave->getLastStatus())); break; } } clock_t end = clock(); long elapsed_ms = (long) ((double(end-begin) / CLOCKS_PER_SEC) * 1000.0); logger::info("Time elapsed={}ms", elapsed_ms); slave->terminate(); }<commit_msg>fix typo<commit_after>/* * The MIT License * * Copyright 2017-2018 Norwegian University of Technology * * 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 <iostream> #include <fmi4cpp/fmi2/fmi4cpp.hpp> #include <fmi4cpp/tools/os_util.hpp> using namespace std; using namespace fmi4cpp::fmi2; namespace logger = fmi4cpp::logger; const double stop = 10.0; const double step_size = 1E-4; const fmi2ValueReference vr = 46; int main() { const string fmu_path = string(getenv("TEST_FMUs")) + "/2.0/cs/" + getOs() + "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu"; auto fmu = Fmu(fmu_path).asCoSimulationFmu(); for (const auto &v : *fmu->getModelDescription()->modelVariables()) { if (v.causality() == Causality::output) { logger::info("Name={}", v.name()); } } auto slave = fmu->newInstance(); slave->setupExperiment(); slave->enterInitializationMode(); slave->exitInitializationMode(); clock_t begin = clock(); double t; double ref; while ((t = slave->getSimulationTime()) <= (stop - step_size)) { if (!slave->doStep(step_size)) { logger::error("Error! doStep returned with status: {}", to_string(slave->getLastStatus())); break; } if (!slave->readReal(vr, ref)) { logger::error("Error! readReal returned with status: {}", to_string(slave->getLastStatus())); break; } } clock_t end = clock(); long elapsed_ms = (long) ((double(end-begin) / CLOCKS_PER_SEC) * 1000.0); logger::info("Time elapsed={}ms", elapsed_ms); slave->terminate(); }<|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 The Florida State University * 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. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint8_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = 16; const int NumIntSpecialRegs = 19; const int NumFloatArchRegs = 16; const int NumFloatSpecialRegs = 5; const int NumInternalProcRegs = 0; const int NumIntRegs = NumIntArchRegs + NumIntSpecialRegs; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = 13; const int ReturnAddressReg = 14; const int PCReg = 15; const int ZeroReg = NumIntArchRegs; const int AddrReg = ZeroReg + 1; // Used to generate address for uops const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs; const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum FPControlRegNums { FIR = NumFloatArchRegs, FCCR, FEXR, FENR, FCSR }; enum FCSRBits { Inexact = 1, Underflow, Overflow, DivideByZero, Invalid, Unimplemented }; enum FCSRFields { Flag_Field = 1, Enable_Field = 6, Cause_Field = 11 }; enum MiscIntRegNums { zero_reg = NumIntArchRegs, addr_reg, rhi, rlo, r8_fiq, /* FIQ mode register bank */ r9_fiq, r10_fiq, r11_fiq, r12_fiq, r13_fiq, /* FIQ mode SP and LR */ r14_fiq, r13_irq, /* IRQ mode SP and LR */ r14_irq, r13_svc, /* SVC mode SP and LR */ r14_svc, r13_undef, /* UNDEF mode SP and LR */ r14_undef, r13_abt, /* ABT mode SP and LR */ r14_abt }; } // namespace ArmISA #endif <commit_msg>ARM: Get rid of some unneeded register indexes.<commit_after>/* * Copyright (c) 2007-2008 The Florida State University * 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. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint8_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = 16; const int NumIntSpecialRegs = 19; const int NumFloatArchRegs = 16; const int NumFloatSpecialRegs = 5; const int NumInternalProcRegs = 0; const int NumIntRegs = NumIntArchRegs + NumIntSpecialRegs; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = 13; const int ReturnAddressReg = 14; const int PCReg = 15; const int ZeroReg = NumIntArchRegs; const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs; const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum FPControlRegNums { FIR = NumFloatArchRegs, FCCR, FEXR, FENR, FCSR }; enum FCSRBits { Inexact = 1, Underflow, Overflow, DivideByZero, Invalid, Unimplemented }; enum FCSRFields { Flag_Field = 1, Enable_Field = 6, Cause_Field = 11 }; } // namespace ArmISA #endif <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CTableCell.cpp,v $ $Revision: 1.17 $ $Name: $ $Author: shoops $ $Date: 2009/07/24 14:30:48 $ End CVS Header */ // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <limits> #include <iostream> #include <sstream> #include <float.h> #include <string.h> #include <stdlib.h> #include "copasi.h" #include "CTableCell.h" #include "utilities/utility.h" CTableCell::CTableCell(const char & separator): mSeparator(separator), mName(""), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mIsValue(false), mIsEmpty(true) {} CTableCell::CTableCell(const CTableCell & src): mSeparator(src.mSeparator), mName(src.mName), mValue(src.mValue), mIsValue(src.mIsValue), mIsEmpty(src.mIsEmpty) {} CTableCell::~CTableCell() {} bool CTableCell::setSeparator(const char & separator) { mSeparator = separator; return true; } const char & CTableCell::getSeparator() const {return mSeparator;} const bool & CTableCell::isValue() const {return mIsValue;} const bool & CTableCell::isEmpty() const {return mIsEmpty;} const std::string & CTableCell::getName() const {return mName;} const C_FLOAT64 & CTableCell::getValue() const {return mValue;} std::istream & operator >> (std::istream &is, CTableCell & cell) { static char buffer[256]; cell.mName = ""; do { is.clear(); is.getline(buffer, 256, cell.mSeparator); cell.mName += buffer; } while (strlen(buffer) == 255 && !is.eof()); /* Trim leading and trailing whitespaces from the string */ std::string::size_type begin = cell.mName.find_first_not_of("\x20\x09\x0d\x0a"); if (begin == std::string::npos) { cell.mName = ""; cell.mIsValue = false; cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN(); cell.mIsEmpty = true; return is; } std::string::size_type end = cell.mName.find_last_not_of("\x20\x09\x0d\x0a"); if (end == std::string::npos) cell.mName = cell.mName.substr(begin); else cell.mName = cell.mName.substr(begin, end - begin + 1); cell.mIsEmpty = false; /* Try to convert the string into a number */ const char * Tail; cell.mValue = strToDouble(cell.mName.c_str(), & Tail); if (!*Tail) { cell.mIsValue = true; } else if (cell.mName == "INF") { cell.mIsValue = true; cell.mValue = std::numeric_limits<C_FLOAT64>::infinity(); } else if (cell.mName == "-INF") { cell.mIsValue = true; cell.mValue = - std::numeric_limits<C_FLOAT64>::infinity(); } else { cell.mIsValue = false; cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } return is; } CTableRow::CTableRow(const unsigned C_INT32 & size, const char & separator): mCells(0), mSeparator(separator), mIsEmpty(true) {resize(size);} CTableRow::CTableRow(const CTableRow & src): mCells(src.mCells), mSeparator(src.mSeparator), mIsEmpty(src.mIsEmpty) {} CTableRow::~CTableRow() {} const std::vector< CTableCell > & CTableRow::getCells() const {return mCells;} bool CTableRow::resize(const unsigned C_INT32 & size) { mCells.resize(size); std::vector< CTableCell >::iterator it = mCells.begin(); std::vector< CTableCell >::iterator end = mCells.end(); for (; it != end; ++it) it->setSeparator(mSeparator); return true; } unsigned C_INT32 CTableRow::size() const {return mCells.size();} const unsigned C_INT32 & CTableRow::getLastFilledCell() const {return mLastFilledCell;} unsigned C_INT32 CTableRow::guessColumnNumber(std::istream &is, const bool & rewind) { std::istream::pos_type pos; if (rewind) pos = is.tellg(); is >> *this; if (rewind) is.seekg(pos); unsigned C_INT32 count; for (count = mCells.size() - 1; count != C_INVALID_INDEX; count--) if (!mCells[count].isEmpty()) break; return count + 1; } const bool & CTableRow::isEmpty() const {return mIsEmpty;} std::istream & CTableRow::readLine(std::istream & is) { // Clear the line; std::stringstream line; char c; for (is.get(c); c != 0x0a && c != 0x0d; is.get(c)) { if (is.fail() || is.eof()) break; line.put(c); } // Eat additional line break characters appearing on DOS and Mac text format; if ((c == 0x0d && is.peek() == 0x0a) || // DOS (c == 0x0a && is.peek() == 0x0d)) // Mac is.ignore(1); mIsEmpty = true; mLastFilledCell = C_INVALID_INDEX; std::vector< CTableCell >::iterator it = mCells.begin(); std::vector< CTableCell >::iterator end = mCells.end(); unsigned C_INT count; for (count = 0; it != end && !line.fail(); ++it, ++count) { line >> *it; if (!it->isEmpty()) { mIsEmpty = false; mLastFilledCell = count; } } CTableCell Unread(mSeparator); while (!line.fail() && !line.eof()) { mCells.push_back(Unread); line >> mCells.back(); if (!mCells.back().isEmpty()) { mIsEmpty = false; mLastFilledCell = count; } count++; } if (it == end) return is; // Missing columns are filled with default for (; it != end; ++it) *it = Unread; return is; } std::istream & operator >> (std::istream &is, CTableRow & row) {return row.readLine(is);} <commit_msg>Fixed debug assertion under WIN32.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CTableCell.cpp,v $ $Revision: 1.18 $ $Name: $ $Author: shoops $ $Date: 2009/07/28 19:02:58 $ End CVS Header */ // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <limits> #include <iostream> #include <sstream> #include <float.h> #include <string.h> #include <stdlib.h> #include "copasi.h" #include "CTableCell.h" #include "utilities/utility.h" CTableCell::CTableCell(const char & separator): mSeparator(separator), mName(""), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mIsValue(false), mIsEmpty(true) {} CTableCell::CTableCell(const CTableCell & src): mSeparator(src.mSeparator), mName(src.mName), mValue(src.mValue), mIsValue(src.mIsValue), mIsEmpty(src.mIsEmpty) {} CTableCell::~CTableCell() {} bool CTableCell::setSeparator(const char & separator) { mSeparator = separator; return true; } const char & CTableCell::getSeparator() const {return mSeparator;} const bool & CTableCell::isValue() const {return mIsValue;} const bool & CTableCell::isEmpty() const {return mIsEmpty;} const std::string & CTableCell::getName() const {return mName;} const C_FLOAT64 & CTableCell::getValue() const {return mValue;} std::istream & operator >> (std::istream &is, CTableCell & cell) { static char buffer[256]; cell.mName = ""; do { is.clear(); is.getline(buffer, 256, cell.mSeparator); cell.mName += buffer; } while (strlen(buffer) == 255 && !is.eof()); /* Trim leading and trailing whitespaces from the string */ std::string::size_type begin = cell.mName.find_first_not_of("\x20\x09\x0d\x0a"); if (begin == std::string::npos) { cell.mName = ""; cell.mIsValue = false; cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN(); cell.mIsEmpty = true; return is; } std::string::size_type end = cell.mName.find_last_not_of("\x20\x09\x0d\x0a"); if (end == std::string::npos) cell.mName = cell.mName.substr(begin); else cell.mName = cell.mName.substr(begin, end - begin + 1); cell.mIsEmpty = false; /* Try to convert the string into a number */ const char * Tail; cell.mValue = strToDouble(cell.mName.c_str(), & Tail); if (!*Tail) { cell.mIsValue = true; } else if (cell.mName == "INF") { cell.mIsValue = true; cell.mValue = std::numeric_limits<C_FLOAT64>::infinity(); } else if (cell.mName == "-INF") { cell.mIsValue = true; cell.mValue = - std::numeric_limits<C_FLOAT64>::infinity(); } else { cell.mIsValue = false; cell.mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } return is; } CTableRow::CTableRow(const unsigned C_INT32 & size, const char & separator): mCells(0), mSeparator(separator), mIsEmpty(true) {resize(size);} CTableRow::CTableRow(const CTableRow & src): mCells(src.mCells), mSeparator(src.mSeparator), mIsEmpty(src.mIsEmpty) {} CTableRow::~CTableRow() {} const std::vector< CTableCell > & CTableRow::getCells() const {return mCells;} bool CTableRow::resize(const unsigned C_INT32 & size) { mCells.resize(size); std::vector< CTableCell >::iterator it = mCells.begin(); std::vector< CTableCell >::iterator end = mCells.end(); for (; it != end; ++it) it->setSeparator(mSeparator); return true; } unsigned C_INT32 CTableRow::size() const {return mCells.size();} const unsigned C_INT32 & CTableRow::getLastFilledCell() const {return mLastFilledCell;} unsigned C_INT32 CTableRow::guessColumnNumber(std::istream &is, const bool & rewind) { std::istream::pos_type pos; if (rewind) pos = is.tellg(); is >> *this; if (rewind) is.seekg(pos); unsigned C_INT32 count; for (count = mCells.size() - 1; count != C_INVALID_INDEX; count--) if (!mCells[count].isEmpty()) break; return count + 1; } const bool & CTableRow::isEmpty() const {return mIsEmpty;} std::istream & CTableRow::readLine(std::istream & is) { // Clear the line; std::stringstream line; char c; for (is.get(c); c != 0x0a && c != 0x0d; is.get(c)) { if (is.fail() || is.eof()) break; line.put(c); } // Eat additional line break characters appearing on DOS and Mac text format; if ((c == 0x0d && is.peek() == 0x0a) || // DOS (c == 0x0a && is.peek() == 0x0d)) // Mac is.ignore(1); mIsEmpty = true; mLastFilledCell = C_INVALID_INDEX; std::vector< CTableCell >::iterator it = mCells.begin(); std::vector< CTableCell >::iterator end = mCells.end(); unsigned C_INT count; for (count = 0; it != end && !line.fail(); ++it, ++count) { line >> *it; if (!it->isEmpty()) { mIsEmpty = false; mLastFilledCell = count; } } bool Finished = false; if (it == end) Finished = true; CTableCell Unread(mSeparator); while (!line.fail() && !line.eof()) { mCells.push_back(Unread); line >> mCells.back(); if (!mCells.back().isEmpty()) { mIsEmpty = false; mLastFilledCell = count; } count++; } if (!Finished) { // Missing columns are filled with default for (; it != end; ++it) *it = Unread; } return is; } std::istream & operator >> (std::istream &is, CTableRow & row) {return row.readLine(is);} <|endoftext|>
<commit_before>/** * Created by Liam Huang (Liam0205) on 2018/10/17. */ #ifndef SORTS_MERGE_SORT_HPP_ #define SORTS_MERGE_SORT_HPP_ #include <functional> #include <algorithm> #include <iterator> #include <vector> namespace detail { template <typename InputIt1, typename InputIt2, typename OutputIt, typename BinaryPred = std::less<typename std::iterator_traits<InputIt1>::value_type>> OutputIt merge(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, BinaryPred comp = BinaryPred()) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if (comp(*first2, *first1)) { *d_first = *first2; ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); } } // namespace detail template <typename FrwdIt, typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>> void merge_sort(FrwdIt first, FrwdIt last, BinaryPred comp = BinaryPred()) { const auto len = std::distance(first, last); if (len <= 1) { return; } auto cut = first + len / 2; merge_sort(first, cut, comp); merge_sort(cut, last, comp); std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp; tmp.reserve(len); detail::merge(first, cut, cut, last, std::back_inserter(tmp), comp); std::copy(tmp.begin(), tmp.end(), first); } template <typename BidirIt, typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>> void inplace_merge_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) { const auto len = std::distance(first, last); if (len <= 1) { return; } auto cut = first + len / 2; merge_sort(first, cut, comp); merge_sort(cut, last, comp); std::inplace_merge(first, cut, last, comp); } #endif // SORTS_MERGE_SORT_HPP_ <commit_msg>[cpp][12_sorts] inplace_merge_sort, impl inplace_merge manually.<commit_after>/** * Created by Liam Huang (Liam0205) on 2018/10/17. */ #ifndef SORTS_MERGE_SORT_HPP_ #define SORTS_MERGE_SORT_HPP_ #include <functional> #include <algorithm> #include <iterator> #include <vector> namespace detail { template <typename InputIt1, typename InputIt2, typename OutputIt, typename BinaryPred = std::less<typename std::iterator_traits<InputIt1>::value_type>> OutputIt merge(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, BinaryPred comp = BinaryPred()) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if (comp(*first2, *first1)) { *d_first = *first2; ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); } template <typename FrwdIt, typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>> void inplace_merge(FrwdIt first, FrwdIt middle, FrwdIt last, BinaryPred comp = BinaryPred()) { // with sufficient memory space const auto len = std::distance(first, last); std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp; tmp.reserve(len); detail::merge(first, middle, middle, last, std::back_inserter(tmp), comp); std::copy(tmp.begin(), tmp.end(), first); } } // namespace detail template <typename FrwdIt, typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>> void merge_sort(FrwdIt first, FrwdIt last, BinaryPred comp = BinaryPred()) { const auto len = std::distance(first, last); if (len <= 1) { return; } auto cut = first + len / 2; merge_sort(first, cut, comp); merge_sort(cut, last, comp); std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp; tmp.reserve(len); detail::merge(first, cut, cut, last, std::back_inserter(tmp), comp); std::copy(tmp.begin(), tmp.end(), first); } template <typename BidirIt, typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>> void inplace_merge_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) { const auto len = std::distance(first, last); if (len <= 1) { return; } auto cut = first + len / 2; merge_sort(first, cut, comp); merge_sort(cut, last, comp); std::inplace_merge(first, cut, last, comp); } #endif // SORTS_MERGE_SORT_HPP_ <|endoftext|>
<commit_before>/* * *** ***** ********************* Mercenaries Engineering SARL ***************** Copyright (C) 2016 ************* ********* http://www.mercenaries-engineering.com *********** **** **** ** ** */ #include <ofxImageEffect.h> #include <ofxKeySyms.h> #include <string.h> #include <math.h> #include <algorithm> #include <set> #ifdef WIN32 #include <Windows.h> #undef min #undef max #endif // WIN32 #include <GL/gl.h> #include "ofxUtilities.h" #include "instance.h" #if defined __APPLE__ || defined linux || defined __FreeBSD__ # define EXPORT __attribute__((visibility("default"))) #elif defined _WIN32 # define EXPORT OfxExport #else # error Not building on your operating system quite yet #endif // Split a string in a string set std::set<std::string> split (const char *str, const std::string &delim) { std::set<std::string> result; const char *start = str; while (true) { if (*str == '\0' || delim.find (*str) != delim.npos) { if (start < str) result.emplace (start, str); start = str+1; } if (*str == '\0') break; ++str; } return result; } // Join strings in a single string template<class T> std::string join (const T &names, const char *sep) { std::string result; for (const auto &name : names) { if (!result.empty ()) result += sep; result += name; } return result; } // Escape the regexp characters std::string escapeRegExp (const char *s) { const char *sc = ".^$*+?()[{\\|"; std::string result = "^"; while (*s) { if (std::find (sc, sc+12, *s) != sc+12) result += "\\"; result += *s; ++s; } result += "$"; return result; } // the interaction routines struct MyInteractData { int DownX, DownY; bool Down, Shift; OfxParamHandle patternParam; explicit MyInteractData(OfxParamHandle pParam) : Down (false), Shift (false) , patternParam(pParam) { } }; // get the interact data from an interact instance static MyInteractData * getInteractData(OfxInteractHandle interactInstance) { void *dataV = ofxuGetInteractInstanceData(interactInstance); return (MyInteractData *) dataV; } // creation of an interact instance static OfxStatus interactDescribe(OfxInteractHandle /*interactDescriptor*/) { // and we are good return kOfxStatOK; } // creation of an interact instance static OfxStatus interactCreateInstance(OfxImageEffectHandle effect, OfxInteractHandle interactInstance) { // get the parameter set for this effect OfxParamSetHandle paramSet; gEffectHost->getParamSet(effect, &paramSet); // fetch a handle to the point param from the parameter set OfxParamHandle patternParam; gParamHost->paramGetHandle(paramSet, "pattern", &patternParam, 0); // make my interact's instance data MyInteractData *data = new MyInteractData(patternParam); // and set the interact's data pointer ofxuSetInteractInstanceData(interactInstance, (void *) data); OfxPropertySetHandle interactProps; gInteractHost->interactGetPropertySet(interactInstance, &interactProps); // slave this interact to the point param so redraws are triggered cleanly gPropHost->propSetString(interactProps, kOfxInteractPropSlaveToParam, 0, "pattern"); return kOfxStatOK; } // destruction of an interact instance static OfxStatus interactDestroyInstance(OfxImageEffectHandle, OfxInteractHandle interactInstance) { MyInteractData *data = getInteractData(interactInstance); delete data; return kOfxStatOK; } // size of the cross hair in screen pixels #define kXHairSize 10 // draw an interact instance static OfxStatus interactDraw(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle drawArgs) { // get my private interact data MyInteractData *data = getInteractData(interactInstance); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); if (data->Down) { double penPos[2]; gPropHost->propGetDoubleN(drawArgs, kOfxInteractPropPenPosition, 2, penPos); // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); const float x0 = (float)data->DownX; const float y0 = size.second-(float)data->DownY-1; const float x1 = (float)penPos[0]; const float y1 = (float)penPos[1]; glPushAttrib (GL_ENABLE_BIT|GL_CURRENT_BIT); // if the we have selected the Xhair, draw it highlit glColor3f(1, 1, 1); glEnable(GL_COLOR_LOGIC_OP); glLogicOp(GL_XOR); glLineStipple(1, 0xF0F0); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINE_STRIP); glVertex2f(x0, y0); glVertex2f(x1, y0); glVertex2f(x1, y1); glVertex2f(x0, y1); glVertex2f(x0, y0); glEnd(); glPopAttrib (); } return kOfxStatOK; } // function reacting to pen motion static OfxStatus interactPenMotion(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle return kOfxStatOK; } static OfxStatus interactPenDown(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle MyInteractData *data = getInteractData(interactInstance); double penPos[2]; gPropHost->propGetDoubleN(inArgs, kOfxInteractPropPenPosition, 2, penPos); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); data->DownX = (int)penPos[0]; data->DownY = size.second-(int)penPos[1]-1; data->Down = true; return kOfxStatOK; } static OfxStatus interactKeyDown (OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { MyInteractData *data = getInteractData(interactInstance); int key; gPropHost->propGetInt (inArgs, kOfxPropKeySym, 0, &key); if (key == kOfxKey_Shift_L || key == kOfxKey_Shift_R) data->Shift = true; return kOfxStatOK; } static OfxStatus interactKeyUp (OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { MyInteractData *data = getInteractData(interactInstance); int key; gPropHost->propGetInt (inArgs, kOfxPropKeySym, 0, &key); if (key == kOfxKey_Shift_L || key == kOfxKey_Shift_R) data->Shift = false; return kOfxStatOK; } static OfxStatus interactPenUp(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle MyInteractData *data = getInteractData(interactInstance); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); double penPos[2]; gPropHost->propGetDoubleN(inArgs, kOfxInteractPropPenPosition, 2, penPos); if (data->Down) { // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); const int upX = (int)penPos[0]; const int upY = size.second-(int)penPos[1]-1; std::set<std::string> names; openexrid::Sample sample; const int alpha = instance->Mask.findSlice ("A"); const int maxX = std::min (std::max (upX, data->DownX)+1, size.first); const int maxY = std::min (std::max (upY, data->DownY)+1, size.first); for (int y = std::max (std::min (upY, data->DownY), 0); y < maxY; ++y) for (int x = std::max (std::min (upX, data->DownX), 0); x < maxX; ++x) { // Get the max coverage sample in the pixel float maxCoverage = 0; uint32_t maxId = ~0U; const int sampleN = instance->Mask.getSampleN (x, y); for (int s = 0; s < sampleN; ++s) { openexrid::Sample sample; instance->Mask.getSample (x, y, s, sample); if (alpha == -1 || sample.Values[alpha] > maxCoverage) { maxId = sample.Id; maxCoverage = sample.Values[alpha]; } } // Found something ? if (maxId != ~0U) { const char *name = instance->Mask.getName (maxId); names.insert (escapeRegExp (name)); } } // Get the old pattern const char *_oldPattern; gParamHost->paramGetValue (data->patternParam, &_oldPattern); std::string oldPattern = _oldPattern; /* Nuke escapes the \ of the text parameter */ std::set<std::string> oldNames (split (oldPattern.c_str (), "\n\r")); // Shift ? if (data->Shift) { // Reverse the selection for the previously selected names for (const auto &name : oldNames) { // Try insert auto r = names.insert (name); // Already there, remove it if (!r.second) names.erase (r.first); } } // get the point param's value std::string pattern = join (names, "\n"); gParamHost->paramSetValue(data->patternParam, pattern.c_str ()); data->Down = false; } return kOfxStatOK; } // the entry point for the overlay OfxStatus overlayMain(const char *action, const void *handle, OfxPropertySetHandle inArgs, OfxPropertySetHandle /*outArgs*/) { OfxInteractHandle interact = (OfxInteractHandle ) handle; OfxPropertySetHandle props; gInteractHost->interactGetPropertySet(interact, &props); if(strcmp(action, kOfxActionDescribe) == 0) return interactDescribe(interact); else { // fetch the effect instance from the interact OfxImageEffectHandle effect; gPropHost->propGetPointer(props, kOfxPropEffectInstance, 0, (void **) &effect); if(strcmp(action, kOfxActionCreateInstance) == 0) return interactCreateInstance(effect, interact); else if(strcmp(action, kOfxActionDestroyInstance) == 0) return interactDestroyInstance(effect, interact); else if(strcmp(action, kOfxInteractActionDraw) == 0) return interactDraw(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenMotion) == 0) return interactPenMotion(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenDown) == 0) return interactPenDown(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenUp) == 0) return interactPenUp(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionKeyDown) == 0) return interactKeyDown(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionKeyUp) == 0) return interactKeyUp(effect, interact, inArgs); return kOfxStatReplyDefault; } return kOfxStatReplyDefault; } <commit_msg>[openfx] Fixed crash reading alpha only images<commit_after>/* * *** ***** ********************* Mercenaries Engineering SARL ***************** Copyright (C) 2016 ************* ********* http://www.mercenaries-engineering.com *********** **** **** ** ** */ #include <ofxImageEffect.h> #include <ofxKeySyms.h> #include <string.h> #include <math.h> #include <algorithm> #include <set> #ifdef WIN32 #include <Windows.h> #undef min #undef max #endif // WIN32 #include <GL/gl.h> #include "ofxUtilities.h" #include "instance.h" #if defined __APPLE__ || defined linux || defined __FreeBSD__ # define EXPORT __attribute__((visibility("default"))) #elif defined _WIN32 # define EXPORT OfxExport #else # error Not building on your operating system quite yet #endif // Split a string in a string set std::set<std::string> split (const char *str, const std::string &delim) { std::set<std::string> result; const char *start = str; while (true) { if (*str == '\0' || delim.find (*str) != delim.npos) { if (start < str) result.emplace (start, str); start = str+1; } if (*str == '\0') break; ++str; } return result; } // Join strings in a single string template<class T> std::string join (const T &names, const char *sep) { std::string result; for (const auto &name : names) { if (!result.empty ()) result += sep; result += name; } return result; } // Escape the regexp characters std::string escapeRegExp (const char *s) { const char *sc = ".^$*+?()[{\\|"; std::string result = "^"; while (*s) { if (std::find (sc, sc+12, *s) != sc+12) result += "\\"; result += *s; ++s; } result += "$"; return result; } // the interaction routines struct MyInteractData { int DownX, DownY; bool Down, Shift; OfxParamHandle patternParam; explicit MyInteractData(OfxParamHandle pParam) : Down (false), Shift (false) , patternParam(pParam) { } }; // get the interact data from an interact instance static MyInteractData * getInteractData(OfxInteractHandle interactInstance) { void *dataV = ofxuGetInteractInstanceData(interactInstance); return (MyInteractData *) dataV; } // creation of an interact instance static OfxStatus interactDescribe(OfxInteractHandle /*interactDescriptor*/) { // and we are good return kOfxStatOK; } // creation of an interact instance static OfxStatus interactCreateInstance(OfxImageEffectHandle effect, OfxInteractHandle interactInstance) { // get the parameter set for this effect OfxParamSetHandle paramSet; gEffectHost->getParamSet(effect, &paramSet); // fetch a handle to the point param from the parameter set OfxParamHandle patternParam; gParamHost->paramGetHandle(paramSet, "pattern", &patternParam, 0); // make my interact's instance data MyInteractData *data = new MyInteractData(patternParam); // and set the interact's data pointer ofxuSetInteractInstanceData(interactInstance, (void *) data); OfxPropertySetHandle interactProps; gInteractHost->interactGetPropertySet(interactInstance, &interactProps); // slave this interact to the point param so redraws are triggered cleanly gPropHost->propSetString(interactProps, kOfxInteractPropSlaveToParam, 0, "pattern"); return kOfxStatOK; } // destruction of an interact instance static OfxStatus interactDestroyInstance(OfxImageEffectHandle, OfxInteractHandle interactInstance) { MyInteractData *data = getInteractData(interactInstance); delete data; return kOfxStatOK; } // size of the cross hair in screen pixels #define kXHairSize 10 // draw an interact instance static OfxStatus interactDraw(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle drawArgs) { // get my private interact data MyInteractData *data = getInteractData(interactInstance); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); if (data->Down) { double penPos[2]; gPropHost->propGetDoubleN(drawArgs, kOfxInteractPropPenPosition, 2, penPos); // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); const float x0 = (float)data->DownX; const float y0 = size.second-(float)data->DownY-1; const float x1 = (float)penPos[0]; const float y1 = (float)penPos[1]; glPushAttrib (GL_ENABLE_BIT|GL_CURRENT_BIT); // if the we have selected the Xhair, draw it highlit glColor3f(1, 1, 1); glEnable(GL_COLOR_LOGIC_OP); glLogicOp(GL_XOR); glLineStipple(1, 0xF0F0); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINE_STRIP); glVertex2f(x0, y0); glVertex2f(x1, y0); glVertex2f(x1, y1); glVertex2f(x0, y1); glVertex2f(x0, y0); glEnd(); glPopAttrib (); } return kOfxStatOK; } // function reacting to pen motion static OfxStatus interactPenMotion(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle return kOfxStatOK; } static OfxStatus interactPenDown(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle MyInteractData *data = getInteractData(interactInstance); double penPos[2]; gPropHost->propGetDoubleN(inArgs, kOfxInteractPropPenPosition, 2, penPos); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); data->DownX = (int)penPos[0]; data->DownY = size.second-(int)penPos[1]-1; data->Down = true; return kOfxStatOK; } static OfxStatus interactKeyDown (OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { MyInteractData *data = getInteractData(interactInstance); int key; gPropHost->propGetInt (inArgs, kOfxPropKeySym, 0, &key); if (key == kOfxKey_Shift_L || key == kOfxKey_Shift_R) data->Shift = true; return kOfxStatOK; } static OfxStatus interactKeyUp (OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { MyInteractData *data = getInteractData(interactInstance); int key; gPropHost->propGetInt (inArgs, kOfxPropKeySym, 0, &key); if (key == kOfxKey_Shift_L || key == kOfxKey_Shift_R) data->Shift = false; return kOfxStatOK; } static OfxStatus interactPenUp(OfxImageEffectHandle effect, OfxInteractHandle interactInstance, OfxPropertySetHandle inArgs) { // get my data handle MyInteractData *data = getInteractData(interactInstance); Instance *instance = (Instance*)ofxuGetEffectInstanceData(effect); double penPos[2]; gPropHost->propGetDoubleN(inArgs, kOfxInteractPropPenPosition, 2, penPos); if (data->Down) { // Get the image size const std::pair<int, int> &size = instance->Mask.getSize (); const int upX = (int)penPos[0]; const int upY = size.second-(int)penPos[1]-1; std::set<std::string> names; openexrid::Sample sample; const int alpha = instance->Mask.findSlice ("A"); const int maxX = std::min (std::max (upX, data->DownX)+1, size.first); const int maxY = std::min (std::max (upY, data->DownY)+1, size.first); for (int y = std::max (std::min (upY, data->DownY), 0); y < maxY; ++y) for (int x = std::max (std::min (upX, data->DownX), 0); x < maxX; ++x) { // Get the max coverage sample in the pixel float maxCoverage = 0; uint32_t maxId = ~0U; const int sampleN = instance->Mask.getSampleN (x, y); for (int s = 0; s < sampleN; ++s) { openexrid::Sample sample; instance->Mask.getSample (x, y, s, sample); if (alpha == -1 || sample.Values[alpha] > maxCoverage) { maxId = sample.Id; if (alpha != -1) maxCoverage = sample.Values[alpha]; } } // Found something ? if (maxId != ~0U) { const char *name = instance->Mask.getName (maxId); names.insert (escapeRegExp (name)); } } // Get the old pattern const char *_oldPattern; gParamHost->paramGetValue (data->patternParam, &_oldPattern); std::string oldPattern = _oldPattern; /* Nuke escapes the \ of the text parameter */ std::set<std::string> oldNames (split (oldPattern.c_str (), "\n\r")); // Shift ? if (data->Shift) { // Reverse the selection for the previously selected names for (const auto &name : oldNames) { // Try insert auto r = names.insert (name); // Already there, remove it if (!r.second) names.erase (r.first); } } // get the point param's value std::string pattern = join (names, "\n"); gParamHost->paramSetValue(data->patternParam, pattern.c_str ()); data->Down = false; } return kOfxStatOK; } // the entry point for the overlay OfxStatus overlayMain(const char *action, const void *handle, OfxPropertySetHandle inArgs, OfxPropertySetHandle /*outArgs*/) { OfxInteractHandle interact = (OfxInteractHandle ) handle; OfxPropertySetHandle props; gInteractHost->interactGetPropertySet(interact, &props); if(strcmp(action, kOfxActionDescribe) == 0) return interactDescribe(interact); else { // fetch the effect instance from the interact OfxImageEffectHandle effect; gPropHost->propGetPointer(props, kOfxPropEffectInstance, 0, (void **) &effect); if(strcmp(action, kOfxActionCreateInstance) == 0) return interactCreateInstance(effect, interact); else if(strcmp(action, kOfxActionDestroyInstance) == 0) return interactDestroyInstance(effect, interact); else if(strcmp(action, kOfxInteractActionDraw) == 0) return interactDraw(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenMotion) == 0) return interactPenMotion(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenDown) == 0) return interactPenDown(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionPenUp) == 0) return interactPenUp(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionKeyDown) == 0) return interactKeyDown(effect, interact, inArgs); else if(strcmp(action, kOfxInteractActionKeyUp) == 0) return interactKeyUp(effect, interact, inArgs); return kOfxStatReplyDefault; } return kOfxStatReplyDefault; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addonstoolbarmanager.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2007-01-23 07:10:00 $ * * 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 * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_ #include <uielement/toolbarmanager.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class AddonsToolBarManager : public ToolBarManager { public: AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~AddonsToolBarManager(); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); virtual void RefreshImages(); using ToolBarManager::FillToolbar; void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar ); protected: DECL_LINK( Click, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Command, CommandEvent * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); virtual bool MenuItemAllowed( sal_uInt16 ) const; private: struct AddonsParams { rtl::OUString aImageId; rtl::OUString aTarget; }; }; } #endif // __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ <commit_msg>INTEGRATION: CWS fwk66 (1.7.36); FILE MERGED 2007/06/04 11:11:03 cd 1.7.36.1: #i78020# Support merging to menu and toolbar for add-ons<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addonstoolbarmanager.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2007-07-10 15:05:41 $ * * 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 * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_ #include <uielement/toolbarmanager.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class AddonsToolBarManager : public ToolBarManager { public: AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~AddonsToolBarManager(); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); virtual void RefreshImages(); using ToolBarManager::FillToolbar; void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar ); protected: DECL_LINK( Click, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Command, CommandEvent * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); virtual bool MenuItemAllowed( sal_uInt16 ) const; }; } #endif // __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ <|endoftext|>
<commit_before>/* =============================================================================== FILE: arithmeticencoder.hpp CONTENTS: A modular C++ wrapper for an adapted version of Amir Said's FastAC Code. see: http://www.cipr.rpi.edu/~said/FastAC.html PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com COPYRIGHT: (c) 2007-2017, martin isenburg, rapidlasso - fast tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: 1 July 2016 -- can be used as init dummy by "native LAS 1.4 compressor" 6 September 2014 -- removed the (unused) inheritance from EntropyEncoder 10 January 2011 -- licensing change for LGPL release and liblas integration 8 December 2010 -- unified framework for all entropy coders 30 October 2009 -- refactoring Amir Said's FastAC code =============================================================================== */ #ifndef ARITHMETIC_ENCODER_HPP #define ARITHMETIC_ENCODER_HPP #include "mydefs.hpp" #include "bytestreamout.hpp" class ArithmeticModel; class ArithmeticBitModel; class ArithmeticEncoder { public: /* Constructor & Destructor */ ArithmeticEncoder(); ~ArithmeticEncoder(); /* Manage encoding */ BOOL init(ByteStreamOut* outstream); void done(); /* Manage an entropy model for a single bit */ ArithmeticBitModel* createBitModel(); void initBitModel(ArithmeticBitModel* model); void destroyBitModel(ArithmeticBitModel* model); /* Manage an entropy model for n symbols (table optional) */ ArithmeticModel* createSymbolModel(U32 n); void initSymbolModel(ArithmeticModel* model, U32 *table=0); void destroySymbolModel(ArithmeticModel* model); /* Encode a bit with modelling */ void encodeBit(ArithmeticBitModel* model, U32 sym); /* Encode a symbol with modelling */ void encodeSymbol(ArithmeticModel* model, U32 sym); /* Encode a bit without modelling */ void writeBit(U32 sym); /* Encode bits without modelling */ void writeBits(U32 bits, U32 sym); /* Encode an unsigned char without modelling */ void writeByte(U8 sym); /* Encode an unsigned short without modelling */ void writeShort(U16 sym); /* Encode an unsigned int without modelling */ void writeInt(U32 sym); /* Encode a float without modelling */ void writeFloat(F32 sym); /* Encode an unsigned 64 bit int without modelling */ void writeInt64(U64 sym); /* Encode a double without modelling */ void writeDouble(F64 sym); /* Only write to outstream if ArithmeticEncoder is dummy */ ByteStreamOut* getByteStreamOut() const { return outstream; }; private: ByteStreamOut* outstream; void propagate_carry(); void renorm_enc_interval(); void manage_outbuffer(); U8* outbuffer; U8* endbuffer; U8* outbyte; U8* endbyte; U32 base, value, length; }; #endif <commit_msg>removal of unused variable and blanks (from Andrew Bell)<commit_after>/* =============================================================================== FILE: arithmeticencoder.hpp CONTENTS: A modular C++ wrapper for an adapted version of Amir Said's FastAC Code. see: http://www.cipr.rpi.edu/~said/FastAC.html PROGRAMMERS: martin.isenburg@rapidlasso.com - http://rapidlasso.com COPYRIGHT: (c) 2007-2017, martin isenburg, rapidlasso - fast tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: 1 July 2016 -- can be used as init dummy by "native LAS 1.4 compressor" 6 September 2014 -- removed the (unused) inheritance from EntropyEncoder 10 January 2011 -- licensing change for LGPL release and liblas integration 8 December 2010 -- unified framework for all entropy coders 30 October 2009 -- refactoring Amir Said's FastAC code =============================================================================== */ #ifndef ARITHMETIC_ENCODER_HPP #define ARITHMETIC_ENCODER_HPP #include "mydefs.hpp" #include "bytestreamout.hpp" class ArithmeticModel; class ArithmeticBitModel; class ArithmeticEncoder { public: /* Constructor & Destructor */ ArithmeticEncoder(); ~ArithmeticEncoder(); /* Manage encoding */ BOOL init(ByteStreamOut* outstream); void done(); /* Manage an entropy model for a single bit */ ArithmeticBitModel* createBitModel(); void initBitModel(ArithmeticBitModel* model); void destroyBitModel(ArithmeticBitModel* model); /* Manage an entropy model for n symbols (table optional) */ ArithmeticModel* createSymbolModel(U32 n); void initSymbolModel(ArithmeticModel* model, U32 *table=0); void destroySymbolModel(ArithmeticModel* model); /* Encode a bit with modelling */ void encodeBit(ArithmeticBitModel* model, U32 sym); /* Encode a symbol with modelling */ void encodeSymbol(ArithmeticModel* model, U32 sym); /* Encode a bit without modelling */ void writeBit(U32 sym); /* Encode bits without modelling */ void writeBits(U32 bits, U32 sym); /* Encode an unsigned char without modelling */ void writeByte(U8 sym); /* Encode an unsigned short without modelling */ void writeShort(U16 sym); /* Encode an unsigned int without modelling */ void writeInt(U32 sym); /* Encode a float without modelling */ void writeFloat(F32 sym); /* Encode an unsigned 64 bit int without modelling */ void writeInt64(U64 sym); /* Encode a double without modelling */ void writeDouble(F64 sym); /* Only write to outstream if ArithmeticEncoder is dummy */ ByteStreamOut* getByteStreamOut() const { return outstream; }; private: ByteStreamOut* outstream; void propagate_carry(); void renorm_enc_interval(); void manage_outbuffer(); U8* outbuffer; U8* endbuffer; U8* outbyte; U8* endbyte; U32 base, length; }; #endif <|endoftext|>
<commit_before>/* * Copyright 2022 Google LLC * * 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 <utility> #include "absl/strings/str_format.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/stringpiece.h" namespace fcp { namespace { REGISTER_OP("TensorName") .Attr("InputType: type") .Input("input_tensor: InputType") .Output("tensor_name: string") .SetShapeFn(tensorflow::shape_inference::ScalarShape); class TensorNameOp : public tensorflow::OpKernel { public: explicit TensorNameOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) { const tensorflow::NodeDef& def = context->def(); OP_REQUIRES(context, def.input_size() == 1, tensorflow::errors::InvalidArgument(absl::StrFormat( "Expected single input, found %d.", def.input_size()))); input_name_ = def.input(0); } void Compute(tensorflow::OpKernelContext* context) override { tensorflow::Tensor* output_tensor; OP_REQUIRES_OK(context, context->allocate_output(0, {}, &output_tensor)); output_tensor->scalar<tensorflow::tstring>()() = input_name_; } private: tensorflow::tstring input_name_; }; REGISTER_KERNEL_BUILDER(Name("TensorName").Device(tensorflow::DEVICE_CPU), TensorNameOp); } // namespace } // namespace fcp <commit_msg>Allow TensorName op to ignore control inputs<commit_after>/* * Copyright 2022 Google LLC * * 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 <utility> #include "absl/strings/str_format.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/stringpiece.h" namespace fcp { namespace { REGISTER_OP("TensorName") .Attr("InputType: type") .Input("input_tensor: InputType") .Output("tensor_name: string") .SetShapeFn(tensorflow::shape_inference::ScalarShape); class TensorNameOp : public tensorflow::OpKernel { public: explicit TensorNameOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) { const tensorflow::NodeDef& def = context->def(); // Note: more than one input is allowed since the "true" input node may be // followed by any number of control inputs. OP_REQUIRES( context, def.input_size() >= 1, tensorflow::errors::InvalidArgument("Expected an input, found none.")); input_name_ = def.input(0); } void Compute(tensorflow::OpKernelContext* context) override { tensorflow::Tensor* output_tensor; OP_REQUIRES_OK(context, context->allocate_output(0, {}, &output_tensor)); output_tensor->scalar<tensorflow::tstring>()() = input_name_; } private: tensorflow::tstring input_name_; }; REGISTER_KERNEL_BUILDER(Name("TensorName").Device(tensorflow::DEVICE_CPU), TensorNameOp); } // namespace } // namespace fcp <|endoftext|>
<commit_before>#include "curvedLabel.h" #include "gl/dynamicQuadMesh.h" #include "labels/obbBuffer.h" #include "labels/screenTransform.h" #include "log.h" #include "style/textStyle.h" #include "text/fontContext.h" #include "textLabels.h" #include "util/geom.h" #include "util/lineSampler.h" #include "view/view.h" #include <glm/gtx/norm.hpp> namespace Tangram { void CurvedLabel::applyAnchor(LabelProperty::Anchor _anchor) { using namespace TextLabelProperty; if (m_preferedAlignment == Align::none) { Align newAlignment = alignFromAnchor(_anchor); m_textRangeIndex = int(newAlignment); } else { m_textRangeIndex = int(m_preferedAlignment); } if (m_textRanges[m_textRangeIndex].length == 0) { m_textRangeIndex = 0; } glm::vec2 offset = m_dim; if (m_parent) { offset += m_parent->dimension(); } m_anchor = LabelProperty::anchorDirection(_anchor) * offset * 0.5f; } bool CurvedLabel::updateScreenTransform(const glm::mat4& _mvp, const ViewState& _viewState, const AABB* _bounds, ScreenTransform& _transform) { glm::vec2 min(-m_dim.y); glm::vec2 max(_viewState.viewportSize + m_dim.y); bool clipped = false; bool inside = false; LineSampler<ScreenTransform> sampler { _transform }; for (auto& p : m_modelTransform) { glm::vec2 sp = worldToScreenSpace(_mvp, glm::vec4(p, 0.0, 1.0), _viewState.viewportSize, clipped); if (clipped) { return false; } sampler.add(sp); if (!inside) { if ((sp.x > min.x && sp.x < max.x && sp.y > min.y && sp.y < max.y)) { inside = true; } } } if (!inside || sampler.sumLength() < m_dim.x) { sampler.clearPoints(); return false; } auto center = sampler.point(m_anchorPoint); m_screenCenter = glm::vec2(center); // Chord length for minimal ~120 degree inner angles (squared) // sin(60)*2 const float sqDirLimit = powf(1.7f, 2); // Range to check for angle changes const float sampleWindow = 20; float width = m_dim.x; float start = sampler.point(m_screenAnchorPoint).z - width * 0.5f; if (start < 0 || start + width > sampler.sumLength()) { sampler.clearPoints(); return false; } // Sets current segment to the segment on which the text starts. glm::vec2 p, r; // unused sampler.sample(start, p, r); size_t startSegment = sampler.curSegment(); for (size_t i = startSegment + 1; i < _transform.size(); i++) { float currLength = sampler.point(i).z; glm::vec2 dir = sampler.segmentDirection(i); // Go back within window to check for hard direction changes for (int k = i - 1; k >= int(startSegment); k--) { if (glm::length2(sampler.segmentDirection(k) + dir) < sqDirLimit) { sampler.clearPoints(); return false; } if (sampler.point(k).z < sampler.point(i).z - sampleWindow) { break; } } if (currLength > start + width) { break; } } return true; } void CurvedLabel::obbs(ScreenTransform& _transform, OBBBuffer& _obbs) { glm::vec2 dim = m_dim - m_options.buffer; if (m_occludedLastFrame) { dim += Label::activation_distance_threshold; } // TODO: Remove - Only for testing if (state() == State::dead) { dim -= 4; } float width = dim.x; LineSampler<ScreenTransform> sampler { _transform }; auto center = sampler.point(m_screenAnchorPoint).z; //auto center = sampler.sumLength() * 0.5; auto start = center - width * 0.5f; glm::vec2 p1, p2, rotation; sampler.sample(start, p1, rotation); float prevLength = start; int count = 0; for (size_t i = sampler.curSegment()+1; i < _transform.size(); i++) { float currLength = sampler.point(i).z; float segmentLength = currLength - prevLength; count++; if (start + width > currLength) { p2 = glm::vec2(sampler.point(i)); rotation = sampler.segmentDirection(i-1); _obbs.append({(p1 + p2) * 0.5f, rotation, segmentLength, dim.y}); prevLength = currLength; p1 = p2; } else { segmentLength = (start + width) - prevLength; sampler.sample(start + width, p2, rotation); _obbs.append({(p1 + p2) * 0.5f, rotation, segmentLength, dim.y}); break; } } } void CurvedLabel::addVerticesToMesh(ScreenTransform& _transform, const glm::vec2& _screenSize) { if (!visibleState()) { return; } TextVertex::State state { m_fontAttrib.selectionColor, m_fontAttrib.fill, m_fontAttrib.stroke, uint16_t(m_alpha * TextVertex::alpha_scale), uint16_t(m_fontAttrib.fontScale), }; auto it = m_textLabels.quads.begin() + m_textRanges[m_textRangeIndex].start; auto end = it + m_textRanges[m_textRangeIndex].length; auto& style = m_textLabels.style; auto& meshes = style.getMeshes(); glm::vec2 rotation; LineSampler<ScreenTransform> sampler { _transform }; float width = m_dim.x; if (sampler.sumLength() < width) { return; } float center = sampler.point(m_screenAnchorPoint).z; glm::vec2 p1, p2; sampler.sample(center + it->quad[0].pos.x * TextVertex::position_inv_scale, p1, rotation); // Check based on first charater whether labels needs to be flipped // sampler.sample(center + it->quad[2].pos.x, p2, rotation); sampler.sample(center + (end-1)->quad[2].pos.x * TextVertex::position_inv_scale, p2, rotation); if (p1.x > p2.x) { sampler.reversePoints(); center = sampler.sumLength() - center; } std::array<glm::i16vec2, 4> vertexPosition; glm::i16vec2 min(-m_dim.y * TextVertex::position_scale); glm::i16vec2 max((_screenSize + m_dim.y) * TextVertex::position_scale); for (; it != end; ++it) { auto quad = *it; glm::vec2 origin = {(quad.quad[0].pos.x + quad.quad[2].pos.x) * 0.5f, 0 }; glm::vec2 point; float px = origin.x * TextVertex::position_inv_scale; if (!sampler.sample(center + px, point, rotation)) { continue; } glm::i16vec2 p(point * TextVertex::position_scale); rotation = {rotation.x, -rotation.y}; bool visible = false; for (int i = 0; i < 4; i++) { vertexPosition[i] = p + glm::i16vec2{rotateBy(glm::vec2(quad.quad[i].pos) - origin, rotation)}; if (!visible && vertexPosition[i].x > min.x && vertexPosition[i].x < max.x && vertexPosition[i].y > min.y && vertexPosition[i].y < max.y) { visible = true; } } if (!visible) { continue; } auto* quadVertices = meshes[it->atlas]->pushQuad(); for (int i = 0; i < 4; i++) { TextVertex& v = quadVertices[i]; v.pos = vertexPosition[i]; v.uv = quad.quad[i].uv; v.state = state; } } } } <commit_msg>smooth segment direction changes during glyph placement<commit_after>#include "curvedLabel.h" #include "gl/dynamicQuadMesh.h" #include "labels/obbBuffer.h" #include "labels/screenTransform.h" #include "log.h" #include "style/textStyle.h" #include "text/fontContext.h" #include "textLabels.h" #include "util/geom.h" #include "util/lineSampler.h" #include "view/view.h" #include <glm/gtx/norm.hpp> namespace Tangram { void CurvedLabel::applyAnchor(LabelProperty::Anchor _anchor) { using namespace TextLabelProperty; if (m_preferedAlignment == Align::none) { Align newAlignment = alignFromAnchor(_anchor); m_textRangeIndex = int(newAlignment); } else { m_textRangeIndex = int(m_preferedAlignment); } if (m_textRanges[m_textRangeIndex].length == 0) { m_textRangeIndex = 0; } glm::vec2 offset = m_dim; if (m_parent) { offset += m_parent->dimension(); } m_anchor = LabelProperty::anchorDirection(_anchor) * offset * 0.5f; } bool CurvedLabel::updateScreenTransform(const glm::mat4& _mvp, const ViewState& _viewState, const AABB* _bounds, ScreenTransform& _transform) { glm::vec2 min(-m_dim.y); glm::vec2 max(_viewState.viewportSize + m_dim.y); bool clipped = false; bool inside = false; LineSampler<ScreenTransform> sampler { _transform }; for (auto& p : m_modelTransform) { glm::vec2 sp = worldToScreenSpace(_mvp, glm::vec4(p, 0.0, 1.0), _viewState.viewportSize, clipped); if (clipped) { return false; } sampler.add(sp); if (!inside) { if ((sp.x > min.x && sp.x < max.x && sp.y > min.y && sp.y < max.y)) { inside = true; } } } if (!inside || sampler.sumLength() < m_dim.x) { sampler.clearPoints(); return false; } auto center = sampler.point(m_anchorPoint); m_screenCenter = glm::vec2(center); // Chord length for minimal ~120 degree inner angles (squared) // sin(60)*2 const float sqDirLimit = powf(1.7f, 2); // Range to check for angle changes const float sampleWindow = 20; float width = m_dim.x; float start = sampler.point(m_screenAnchorPoint).z - width * 0.5f; if (start < 0 || start + width > sampler.sumLength()) { sampler.clearPoints(); return false; } // Sets current segment to the segment on which the text starts. glm::vec2 p, r; // unused sampler.sample(start, p, r); size_t startSegment = sampler.curSegment(); for (size_t i = startSegment + 1; i < _transform.size(); i++) { float currLength = sampler.point(i).z; glm::vec2 dir = sampler.segmentDirection(i); // Go back within window to check for hard direction changes for (int k = i - 1; k >= int(startSegment); k--) { if (glm::length2(sampler.segmentDirection(k) + dir) < sqDirLimit) { sampler.clearPoints(); return false; } if (sampler.point(k).z < sampler.point(i).z - sampleWindow) { break; } } if (currLength > start + width) { break; } } return true; } void CurvedLabel::obbs(ScreenTransform& _transform, OBBBuffer& _obbs) { glm::vec2 dim = m_dim - m_options.buffer; if (m_occludedLastFrame) { dim += Label::activation_distance_threshold; } // TODO: Remove - Only for testing if (state() == State::dead) { dim -= 4; } float width = dim.x; LineSampler<ScreenTransform> sampler { _transform }; auto center = sampler.point(m_screenAnchorPoint).z; //auto center = sampler.sumLength() * 0.5; auto start = center - width * 0.5f; glm::vec2 p1, p2, rotation; sampler.sample(start, p1, rotation); float prevLength = start; int count = 0; for (size_t i = sampler.curSegment()+1; i < _transform.size(); i++) { float currLength = sampler.point(i).z; float segmentLength = currLength - prevLength; count++; if (start + width > currLength) { p2 = glm::vec2(sampler.point(i)); rotation = sampler.segmentDirection(i-1); _obbs.append({(p1 + p2) * 0.5f, rotation, segmentLength, dim.y}); prevLength = currLength; p1 = p2; } else { segmentLength = (start + width) - prevLength; sampler.sample(start + width, p2, rotation); _obbs.append({(p1 + p2) * 0.5f, rotation, segmentLength, dim.y}); break; } } } void CurvedLabel::addVerticesToMesh(ScreenTransform& _transform, const glm::vec2& _screenSize) { if (!visibleState()) { return; } TextVertex::State state { m_fontAttrib.selectionColor, m_fontAttrib.fill, m_fontAttrib.stroke, uint16_t(m_alpha * TextVertex::alpha_scale), uint16_t(m_fontAttrib.fontScale), }; auto it = m_textLabels.quads.begin() + m_textRanges[m_textRangeIndex].start; auto end = it + m_textRanges[m_textRangeIndex].length; auto& style = m_textLabels.style; auto& meshes = style.getMeshes(); glm::vec2 rotation; LineSampler<ScreenTransform> sampler { _transform }; float width = m_dim.x; if (sampler.sumLength() < width) { return; } float center = sampler.point(m_screenAnchorPoint).z; glm::vec2 p1, p2; sampler.sample(center + it->quad[0].pos.x * TextVertex::position_inv_scale, p1, rotation); // Check based on first charater whether labels needs to be flipped // sampler.sample(center + it->quad[2].pos.x, p2, rotation); sampler.sample(center + (end-1)->quad[2].pos.x * TextVertex::position_inv_scale, p2, rotation); if (p1.x > p2.x) { sampler.reversePoints(); center = sampler.sumLength() - center; } std::array<glm::i16vec2, 4> vertexPosition; glm::i16vec2 min(-m_dim.y * TextVertex::position_scale); glm::i16vec2 max((_screenSize + m_dim.y) * TextVertex::position_scale); for (; it != end; ++it) { auto quad = *it; glm::vec2 origin = {(quad.quad[0].pos.x + quad.quad[2].pos.x) * 0.5f, 0 }; glm::vec2 point, p1, p2, r1, r2; auto xStart = quad.quad[0].pos.x * TextVertex::position_inv_scale; auto xEnd = quad.quad[2].pos.x * TextVertex::position_inv_scale; float px = origin.x * TextVertex::position_inv_scale; if (!sampler.sample(center + px, point, rotation)) { continue; } bool ok1 = sampler.sample(center + xStart, p1, r1); bool ok2 = sampler.sample(center + xEnd, p2, r2); if (ok1 && ok2) { if (r1 == r2) { rotation = r1; } else { rotation = glm::normalize(p2 - p1); } //point = (p1 + p2) * 0.5f; point = point * 0.5f + (p1 + p2) * 0.25f; } glm::i16vec2 p(point * TextVertex::position_scale); rotation = {rotation.x, -rotation.y}; bool visible = false; for (int i = 0; i < 4; i++) { vertexPosition[i] = p + glm::i16vec2{rotateBy(glm::vec2(quad.quad[i].pos) - origin, rotation)}; if (!visible && vertexPosition[i].x > min.x && vertexPosition[i].x < max.x && vertexPosition[i].y > min.y && vertexPosition[i].y < max.y) { visible = true; } } if (!visible) { continue; } auto* quadVertices = meshes[it->atlas]->pushQuad(); for (int i = 0; i < 4; i++) { TextVertex& v = quadVertices[i]; v.pos = vertexPosition[i]; v.uv = quad.quad[i].uv; v.state = state; } } } } <|endoftext|>
<commit_before>#include "application.h" // POSIX #include <stropts.h> // STL #include <atomic> #include <cassert> #include <algorithm> // PDTK #include <object.h> #include <specialized/eventbackend.h> // atomic vars are to avoid race conditions static std::atomic_int s_return_value (0); static std::atomic_bool s_run (true); static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; lockable<std::queue<vfunc>> Application::ms_signal_queue; std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>> Application::ms_fd_signals; enum { Read = 0, Write = 1, }; Application::Application (void) noexcept { if(s_pipeio[Read] == posix::invalid_descriptor) { assert(::pipe(s_pipeio) != posix::error_response); EventBackend::init(); EventBackend::watch(s_pipeio[Read], EventFlags::Readable); } } Application::~Application(void) noexcept { EventBackend::destroy(); } void Application::step(void) noexcept { static uint8_t dummydata = 0; posix::write(s_pipeio[Write], &dummydata, 1); } int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists { while(s_run) { EventBackend::getevents(); for(auto pos : EventBackend::results) { if(pos.first == s_pipeio[Read]) { while(::ioctl(pos.first, I_FLUSH, FLUSHRW) == posix::error_response && // not interested in the data errno == std::errc::interrupted); // ignore interruptions run(); } else { auto entries = ms_fd_signals.equal_range(pos.first); for_each(entries.first, entries.second, [pos](auto& entry) { if(entry.second.first & pos.second) entry.second.second(pos.first, pos.second); }); } } } return s_return_value; // quit() has been called, return value specified } void Application::run(void) noexcept { static std::queue<vfunc> exec_queue; if(s_run && exec_queue.empty()) // while application is running and not currently executing { ms_signal_queue.lock(); // get exclusive access exec_queue.swap(ms_signal_queue); // swap the queues to prevent race conditions and the need for constant locking/unlocking ms_signal_queue.unlock(); // access is no longer needed while(s_run && !exec_queue.empty()) // if haven't quit and still have signals to execute { exec_queue.front()(); // execute current signal exec_queue.pop(); // discard current signal } } } void Application::quit(int return_value) noexcept { if(s_run) { s_return_value = return_value; s_run = false; } } <commit_msg>documentation<commit_after>#include "application.h" // POSIX #include <stropts.h> // STL #include <atomic> #include <cassert> #include <algorithm> // PDTK #include <object.h> #include <specialized/eventbackend.h> // atomic vars are to avoid race conditions static std::atomic_int s_return_value (0); static std::atomic_bool s_run (true); static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; lockable<std::queue<vfunc>> Application::ms_signal_queue; std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>> Application::ms_fd_signals; enum { Read = 0, Write = 1, }; Application::Application (void) noexcept { if(s_pipeio[Read] == posix::invalid_descriptor) { assert(::pipe(s_pipeio) != posix::error_response); EventBackend::init(); EventBackend::watch(s_pipeio[Read], EventFlags::Readable); } } Application::~Application(void) noexcept { EventBackend::destroy(); } void Application::step(void) noexcept { static uint8_t dummydata = 0; posix::write(s_pipeio[Write], &dummydata, 1); } int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists { while(s_run) { EventBackend::getevents(); for(auto pos : EventBackend::results) { if(pos.first == s_pipeio[Read]) // if this was object enqueue FD { while(::ioctl(pos.first, I_FLUSH, FLUSHRW) == posix::error_response && // discard the data (it's merely a trigger) errno == std::errc::interrupted); // don't be interrupted while flushing the FD channel run(); // execute queue of object signal calls } else { auto entries = ms_fd_signals.equal_range(pos.first); // get all then entries for that FD for_each(entries.first, entries.second, // for each FD [pos](auto& fdsigpair) { if(fdsigpair.second.first & pos.second) // test to see if the current FD signal pair matches the triggering EventFlag fdsigpair.second.second(pos.first, pos.second); // call the fuction with the FD and triggering EventFlag }); } } } return s_return_value; // quit() has been called, return value specified } void Application::run(void) noexcept { static std::queue<vfunc> exec_queue; if(s_run && exec_queue.empty()) // while application is running and not currently executing { ms_signal_queue.lock(); // get exclusive access exec_queue.swap(ms_signal_queue); // swap the queues to prevent race conditions and the need for constant locking/unlocking ms_signal_queue.unlock(); // access is no longer needed while(s_run && !exec_queue.empty()) // if haven't quit and still have object signals to execute { exec_queue.front()(); // execute current object signal exec_queue.pop(); // discard current object signal } } } void Application::quit(int return_value) noexcept { if(s_run) { s_return_value = return_value; s_run = false; } } <|endoftext|>
<commit_before><commit_msg>fix overflow in cuts<commit_after><|endoftext|>
<commit_before>#include <aery32/all.h> #include "board.h" #define LED AVR32_PIN_PC04 volatile bool pa00 = false; void isrhandler_group2(void) { pa00 = gpio_read_pin(AVR32_PIN_PA00); delay_ms(10); if (gpio_read_pin(ARV32_PIN_PA00) == pa00) { /* Still connected? */ gpio_toggle_pin(LED); } porta->ifrc = (1 << 0); /* Remember to clear the interrupt */ } using namespace aery; int main(void) { /* * Put your application initialization sequence here. The default * board initializer defines all pins as input and sets the CPU clock * speed to 66 MHz. */ board::init(); gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH); /* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */ gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE); /* Init interrupt controller */ intc_init(); intc_register_isrhandler( &isrhandler_group2, /* Function pointer to the ISR handler */ 2, /* Interrupt group number */ 0 /* Priority level */ ); /* Enable interrupts globally */ intc_enable_globally(); for(;;) { /* * Now try to connect PA00 to GND and then disconnecting it * to let the pull-up to set the pin state high again. The LED * should toggle on the pin change. */ } return 0; } <commit_msg>Update gpio_extint_pin_change.cpp<commit_after>#include <aery32/all.h> #include "board.h" #define LED AVR32_PIN_PC04 volatile bool pa00 = false; using namespace aery; void isrhandler_group2(void) { pa00 = gpio_read_pin(AVR32_PIN_PA00); delay_ms(10); if (gpio_read_pin(ARV32_PIN_PA00) == pa00) { /* Still connected? */ gpio_toggle_pin(LED); } porta->ifrc = (1 << 0); /* Remember to clear the interrupt */ } int main(void) { /* * Put your application initialization sequence here. The default * board initializer defines all pins as input and sets the CPU clock * speed to 66 MHz. */ board::init(); gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH); /* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */ gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE); /* Init interrupt controller */ intc_init(); intc_register_isrhandler( &isrhandler_group2, /* Function pointer to the ISR handler */ 2, /* Interrupt group number */ 0 /* Priority level */ ); /* Enable interrupts globally */ intc_enable_globally(); for(;;) { /* * Now try to connect PA00 to GND and then disconnecting it * to let the pull-up to set the pin state high again. The LED * should toggle on the pin change. */ } return 0; } <|endoftext|>
<commit_before>//LUDUM DARE 30 #include <map> #include <string> #include <sstream> #include <iostream> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> namespace sf{ bool operator< (const sf::Color& c1, const sf::Color& c2){ if(c1.r < c2.r) return true; else if(c1.r > c2.r) return false; else if(c1.g < c2.g) return true; else if(c1.g > c2.g) return false; else if(c1.b < c2.b) return true; else if(c1.b > c2.b) return false; else if(c1.a < c2.a) return true; else if(c1.a > c2.a) return false; else return false; } } sf::Color getColisionColor(float posx, float posy, sf::Image& img, sf::Sprite& bSprite){ return img.getPixel( posx/bSprite.getScale().x, posy/bSprite.getScale().y); } int main(){ sf::Vector2f v = sf::Vector2f(0,0); sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Gravity"); const float g = (int)window.getSize().y*2 ; sf::RectangleShape r(sf::Vector2f(window.getSize().x/10, window.getSize().y/10)); r.setPosition(0,0); r.setFillColor(sf::Color::White); sf::Clock timer; float deltatime = 0; float ground = window.getSize().y-2; // float ground = window.getSize().y*6/7; sf::Text text; sf::Font font; if(! font.loadFromFile("font.ttf")) std::cout << "penguin" << std::endl; text.setFont(font); text.setPosition(0,0); text.setString("penguin <3"); sf::Image bimg; sf::Texture bTex; sf::Sprite bSprite; std::map<sf::Color, sf::Time> colorsColiding; int pantalla = 0; bool reboot = false; bool needshiet = true; //GAME LOOP while(window.isOpen()){ if(needshiet){ v = sf::Vector2f(0,0); colorsColiding.clear(); r.setPosition(0,0); std::stringstream s; s << "board" << pantalla; std::string board = s.str(); if(!bimg.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD IMAGE" << std::endl; if(!bTex.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD texture" << std::endl; bSprite.setTexture(bTex, true); bSprite.scale(window.getSize().x/bSprite.getGlobalBounds().width , window.getSize().y/bSprite.getGlobalBounds().height); needshiet = false; deltatime = 0; } deltatime = timer.restart().asSeconds(); sf::Event event; while(window.pollEvent(event)) if (event.type == sf::Event::Closed) window.close(); if(r.getPosition().y > 0){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up )) v.y = (int)window.getSize().y/2 * -1; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) v.y = (int)window.getSize().y * -1; } // if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down )) v.x = 0; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left )) v.x = (int)window.getSize().x/20 * -1; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) v.x = window.getSize().x/20; if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { reboot = true; v.x = 0; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) window.close(); r.move(v * deltatime); if(r.getPosition().y < 0) {v.y += g*deltatime;} if( (r.getPosition().y + r.getSize().y) < ground || v.y < 0) v.y += g *deltatime; else { r.setPosition(r.getPosition().x, ground - r.getSize().y); v.y = 0; } if(r.getPosition().x + r.getSize().x > window.getSize().x) r.setPosition(window.getSize().x-1-r.getSize().x, r.getPosition().y); sf::FloatRect fr = r.getGlobalBounds(); if(r.getPosition().y >= 0 && r.getPosition().x+r.getSize().x < window.getSize().x && r.getPosition().x > 0) { sf::Color color = getColisionColor(r.getPosition().x, r.getPosition().y, bimg, bSprite); if(color != sf::Color::Black) colorsColiding[color] += sf::seconds(deltatime); sf::Color color2 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y, bimg, bSprite); if(color2 != sf::Color::Black) colorsColiding[color2] += sf::seconds(deltatime); sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite); if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime); sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite); if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime); } std::stringstream ss; for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){ std::string col = "wat:"; sf::Color aux = (it->first); if(aux.r > aux.g and aux.r > aux.b) { if(aux.g < 100) col = "Red:"; else col = "Yellow"; } else if(aux.g > aux.r and aux.g > aux.b) col = "Green:"; else if(aux.b > aux.g and aux.b > aux.r) col = "Blue:"; if((int)(it->second).asSeconds() > 0) ss << " " << col << " " << (int)(it->second).asSeconds(); } std::string str = ss.str(); text.setString(str); int max = 0; int qtty = 0; int min = 99999999; if(colorsColiding[sf::Color::White] != sf::seconds(0.0) || reboot){ for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){ int num = (int)(it->second).asSeconds(); if(num > 0) { if(num > max) max = num; if(num < min) min = num; ++qtty; } } //if(! max - min <= 3) reboot = true; if((max - min <= 3 && qtty >= 3) || reboot) { if(!reboot)text.setString("YouWonTheGame!"); else text.setString(" Nice try!"); window.clear(); window.draw(bSprite); window.draw(text); window.draw(r); window.display(); sf::Clock c; float t = 0; while(t < 3){ t += c.restart().asSeconds(); timer.restart(); } if(!reboot) ++pantalla; needshiet = true; reboot = false; } else reboot = true; } window.clear(); window.draw(bSprite); window.draw(text); window.draw(r); window.display(); } } <commit_msg>punctuation<commit_after>//LUDUM DARE 30 #include <map> #include <string> #include <sstream> #include <iostream> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> namespace sf{ bool operator< (const sf::Color& c1, const sf::Color& c2){ if(c1.r < c2.r) return true; else if(c1.r > c2.r) return false; else if(c1.g < c2.g) return true; else if(c1.g > c2.g) return false; else if(c1.b < c2.b) return true; else if(c1.b > c2.b) return false; else if(c1.a < c2.a) return true; else if(c1.a > c2.a) return false; else return false; } } sf::Color getColisionColor(float posx, float posy, sf::Image& img, sf::Sprite& bSprite){ return img.getPixel( posx/bSprite.getScale().x, posy/bSprite.getScale().y); } int main(){ sf::Vector2f v = sf::Vector2f(0,0); sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Gravity"); const float g = (int)window.getSize().y*2 ; sf::RectangleShape r(sf::Vector2f(window.getSize().x/10, window.getSize().y/10)); r.setPosition(0,0); r.setFillColor(sf::Color::White); sf::Clock timer; float deltatime = 0; float ground = window.getSize().y-2; // float ground = window.getSize().y*6/7; sf::Text text; sf::Font font; if(! font.loadFromFile("font.ttf")) std::cout << "penguin" << std::endl; text.setFont(font); text.setPosition(0,0); text.setString("penguin <3"); sf::Image bimg; sf::Texture bTex; sf::Sprite bSprite; std::map<sf::Color, sf::Time> colorsColiding; int pantalla = 0; bool reboot = false; bool needshiet = true; //GAME LOOP while(window.isOpen()){ if(needshiet){ v = sf::Vector2f(0,0); colorsColiding.clear(); r.setPosition(0,0); std::stringstream s; s << "board" << pantalla; std::string board = s.str(); if(!bimg.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD IMAGE" << std::endl; if(!bTex.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD texture" << std::endl; bSprite.setTexture(bTex, true); bSprite.scale(window.getSize().x/bSprite.getGlobalBounds().width , window.getSize().y/bSprite.getGlobalBounds().height); needshiet = false; deltatime = 0; } deltatime = timer.restart().asSeconds(); sf::Event event; while(window.pollEvent(event)) if (event.type == sf::Event::Closed) window.close(); if(r.getPosition().y > 0){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up )) v.y = (int)window.getSize().y/2 * -1; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) v.y = (int)window.getSize().y * -1; } // if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down )) v.x = 0; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left )) v.x = (int)window.getSize().x/20 * -1; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) v.x = window.getSize().x/20; if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { reboot = true; v.x = 0; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) window.close(); r.move(v * deltatime); if(r.getPosition().y < 0) {v.y += g*deltatime;} if( (r.getPosition().y + r.getSize().y) < ground || v.y < 0) v.y += g *deltatime; else { r.setPosition(r.getPosition().x, ground - r.getSize().y); v.y = 0; } if(r.getPosition().x + r.getSize().x > window.getSize().x) r.setPosition(window.getSize().x-1-r.getSize().x, r.getPosition().y); sf::FloatRect fr = r.getGlobalBounds(); if(r.getPosition().y >= 0 && r.getPosition().x+r.getSize().x < window.getSize().x && r.getPosition().x > 0) { sf::Color color = getColisionColor(r.getPosition().x, r.getPosition().y, bimg, bSprite); if(color != sf::Color::Black) colorsColiding[color] += sf::seconds(deltatime); sf::Color color2 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y, bimg, bSprite); if(color2 != sf::Color::Black) colorsColiding[color2] += sf::seconds(deltatime); sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite); if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime); sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite); if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime); } std::stringstream ss; for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){ std::string col = "wat:"; sf::Color aux = (it->first); if(aux.r > aux.g and aux.r > aux.b) { if(aux.g < 100) col = "Red:"; else col = "Yellow"; } else if(aux.g > aux.r and aux.g > aux.b) col = "Green:"; else if(aux.b > aux.g and aux.b > aux.r) col = "Blue:"; if((int)(it->second).asSeconds() > 0) ss << " " << col << " " << (int)(it->second).asSeconds(); } std::string str = ss.str(); text.setString(str); int max = 0; int qtty = 0; int min = 99999999; if(colorsColiding[sf::Color::White] != sf::seconds(0.0) || reboot){ for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){ int num = (int)(it->second).asSeconds(); if(num > 0) { if(num > max) max = num; if(num < min) min = num; ++qtty; } } //if(! max - min <= 3) reboot = true; if((max - min <= 3 && qtty >= 3) || reboot) { char *intStr = itoa(max); string str = string(intStr); // string(itoa(max)) (?) if(!reboot)text.setString("YouWonTheGame! punctuation = " + str); else text.setString(" Nice try!"); window.clear(); window.draw(bSprite); window.draw(text); window.draw(r); window.display(); sf::Clock c; float t = 0; while(t < 3){ t += c.restart().asSeconds(); timer.restart(); } if(!reboot) ++pantalla; needshiet = true; reboot = false; } else reboot = true; } window.clear(); window.draw(bSprite); window.draw(text); window.draw(r); window.display(); } } <|endoftext|>
<commit_before>// // OpenFlight loader for OpenSceneGraph // // Copyright (C) 2005-2006 Brede Johansen // #include <osgSim/LightPointNode> #include <osg/Texture2D> #include "Registry.h" #include "Document.h" #include "RecordInputStream.h" using namespace flt; /** LightPoint */ class LightPoint : public PrimaryRecord { enum Directionality { OMNIDIRECTIONAL = 0, UNIDIRECTIONAL = 1, BIDIRECTIONAL = 2 }; // flags static const unsigned int NO_BACK_COLOR_BIT = 0x80000000u >> 1; int16 _material; int16 _feature; osg::Vec4f _backColor; int32 _displayMode; float32 _intensityFront; float32 _intensityBack; float32 _minDefocus; float32 _maxDefocus; int32 _fadeMode; int32 _fogPunchMode; int32 _directionalMode; int32 _rangeMode; float32 _minPixelSize; float32 _maxPixelSize; float32 _actualPixelSize; float32 _transparentFalloff; float32 _transparentFalloffExponent; float32 _transparentFalloffScalar; float32 _transparentFalloffClamp; float32 _fog; float32 _sizeDifferenceThreshold; int32 _directionality; float32 _lobeHorizontal; float32 _lobeVertical; float32 _lobeRoll; float32 _falloff; float32 _ambientIntensity; float32 _animationPeriod; float32 _animationPhaseDelay; float32 _animationPeriodEnable; float32 _significance; int32 _drawOrder; uint32 _flags; osg::Vec3f _animationAxis; osg::ref_ptr<osgSim::LightPointNode> _lpn; public: LightPoint() {} META_Record(LightPoint) META_setID(_lpn) META_setComment(_lpn) META_setMatrix(_lpn) // Add lightpoint, add two if bidirectional. virtual void addVertex(Vertex& vertex) { osgSim::LightPoint lp; lp._position = vertex._coord; lp._radius = 0.5f * _actualPixelSize; lp._intensity = _intensityFront; // color lp._color = (vertex.validColor()) ? vertex._color : osg::Vec4(1,1,1,1); // sector bool directional = (_directionality==UNIDIRECTIONAL) || (_directionality==BIDIRECTIONAL); if (directional && vertex.validNormal()) { lp._sector = new osgSim::DirectionalSector( vertex._normal, osg::DegreesToRadians(_lobeHorizontal), osg::DegreesToRadians(_lobeVertical), osg::DegreesToRadians(_lobeRoll)); } _lpn->addLightPoint(lp); // Create a new lightpoint if bi-directional. if ((_directionality==BIDIRECTIONAL) && vertex.validNormal()) { // back intensity lp._intensity = _intensityBack; // back color if (!(_flags & NO_BACK_COLOR_BIT)) lp._color = _backColor; // back sector lp._sector = new osgSim::DirectionalSector( -vertex._normal, osg::DegreesToRadians(_lobeHorizontal), osg::DegreesToRadians(_lobeVertical), osg::DegreesToRadians(_lobeRoll)); _lpn->addLightPoint(lp); } } protected: virtual ~LightPoint() {} virtual void readRecord(RecordInputStream& in, Document& document) { std::string id = in.readString(8); _material = in.readInt16(); _feature = in.readInt16(); int32 backColorIndex = in.readInt32(); _backColor = document.getColorPool() ? document.getColorPool()->getColor(backColorIndex) : osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f); _displayMode = in.readInt32(); _intensityFront = in.readFloat32(); _intensityBack = in.readFloat32(); _minDefocus = in.readFloat32(); _maxDefocus = in.readFloat32(); _fadeMode = in.readInt32(); _fogPunchMode = in.readInt32(); _directionalMode = in.readInt32(); _rangeMode = in.readInt32(); _minPixelSize = in.readFloat32(); // * document.unitScale(); _maxPixelSize = in.readFloat32(); // * document.unitScale(); _actualPixelSize = in.readFloat32(); // * document.unitScale(); _transparentFalloff = in.readFloat32(); _transparentFalloffExponent = in.readFloat32(); _transparentFalloffScalar = in.readFloat32(); _transparentFalloffClamp = in.readFloat32(); _fog = in.readFloat32(); in.forward(4); _sizeDifferenceThreshold = in.readFloat32(); _directionality = in.readInt32(); _lobeHorizontal = in.readFloat32(); _lobeVertical = in.readFloat32(); _lobeRoll = in.readFloat32(); _falloff = in.readFloat32(); _ambientIntensity = in.readFloat32(); _animationPeriod = in.readFloat32(); _animationPhaseDelay = in.readFloat32(); _animationPeriodEnable = in.readFloat32(); _significance = in.readFloat32(); _drawOrder = in.readInt32(); _flags = in.readUInt32(0); _animationAxis = in.readVec3f(); _lpn = new osgSim::LightPointNode; _lpn->setName(id); _lpn->setMinPixelSize(_minPixelSize); _lpn->setMaxPixelSize(_maxPixelSize); // Add to parent if (_parent.valid()) _parent->addChild(*_lpn); } }; RegisterRecordProxy<LightPoint> g_LightPoint(LIGHT_POINT_OP); /** IndexedLightPoint */ class IndexedLightPoint : public PrimaryRecord { enum Directionality { OMNIDIRECTIONAL = 0, UNIDIRECTIONAL = 1, BIDIRECTIONAL = 2 }; // flags static const unsigned int NO_BACK_COLOR_BIT = 0x80000000u >> 1; osg::ref_ptr<osgSim::LightPointNode> _lpn; osg::ref_ptr<LPAppearance> _appearance; public: IndexedLightPoint() {} META_Record(IndexedLightPoint) META_setID(_lpn) META_setComment(_lpn) META_setMatrix(_lpn) // Add lightpoint, add two if bidirectional. virtual void addVertex(Vertex& vertex) { if (_appearance.valid()) { osgSim::LightPoint lp; lp._position = vertex._coord; lp._radius = 0.5f * _appearance->actualPixelSize; lp._intensity = _appearance->intensityFront; // color lp._color = (vertex.validColor()) ? vertex._color : osg::Vec4(1,1,1,1); // sector bool directional = (_appearance->directionality==UNIDIRECTIONAL) || (_appearance->directionality==BIDIRECTIONAL); if (directional && vertex.validNormal()) { lp._sector = new osgSim::DirectionalSector( vertex._normal, osg::DegreesToRadians(_appearance->horizontalLobeAngle), osg::DegreesToRadians(_appearance->verticalLobeAngle), osg::DegreesToRadians(_appearance->lobeRollAngle)); } _lpn->addLightPoint(lp); // Create a new lightpoint if bi-directional. if ((_appearance->directionality==BIDIRECTIONAL) && vertex.validNormal()) { // back intensity lp._intensity = _appearance->intensityBack; // back color if (!(_appearance->flags & NO_BACK_COLOR_BIT)) lp._color = _appearance->backColor; // back sector lp._sector = new osgSim::DirectionalSector( -vertex._normal, osg::DegreesToRadians(_appearance->horizontalLobeAngle), osg::DegreesToRadians(_appearance->verticalLobeAngle), osg::DegreesToRadians(_appearance->lobeRollAngle)); _lpn->addLightPoint(lp); } } } protected: virtual ~IndexedLightPoint() {} virtual void readRecord(RecordInputStream& in, Document& document) { std::string id = in.readString(8); int32 appearanceIndex = in.readInt32(); /*int32 animationIndex =*/ in.readInt32(); /*int32 drawOrder =*/ in.readInt32(); // for calligraphic lights LightPointAppearancePool* lpaPool = document.getOrCreateLightPointAppearancePool(); _appearance = lpaPool->get(appearanceIndex); _lpn = new osgSim::LightPointNode; _lpn->setName(id); if (_appearance.valid()) { _lpn->setMinPixelSize(_appearance->minPixelSize); _lpn->setMaxPixelSize(_appearance->maxPixelSize); if (_appearance->texturePatternIndex != -1) { // Use point sprites for light points. _lpn->setPointSprite(); TexturePool* tp = document.getOrCreateTexturePool(); osg::StateSet* textureStateSet = tp->get(_appearance->texturePatternIndex); if (textureStateSet) { // Merge face stateset with texture stateset osg::StateSet* stateset = _lpn->getOrCreateStateSet(); stateset->merge(*textureStateSet); } } } // Add to parent if (_parent.valid()) _parent->addChild(*_lpn); } }; RegisterRecordProxy<IndexedLightPoint> g_IndexedLightPoint(INDEXED_LIGHT_POINT_OP); /** LightPointSystem */ class LightPointSystem : public PrimaryRecord { public: LightPointSystem() {} META_Record(LightPointSystem) protected: virtual ~LightPointSystem() {} virtual void readRecord(RecordInputStream& in, Document& /*document*/) { std::string id = in.readString(8); osg::notify(osg::INFO) << "ID: " << id << std::endl; osg::Group* group = new osg::Group; group->setName(id); if (_parent.valid()) _parent->addChild(*group); } }; RegisterRecordProxy<LightPointSystem> g_LightPointSystem(LIGHT_POINT_SYSTEM_OP); <commit_msg>From Charles Cole, "he attached code implements the LightPointSystem class to allow for the OpenFlight plug-in to read and handle light point system nodes. The behavior is very similar to the old plug-in in that a MultiSwitch node is created to handle the "enabled" flag bit set in the node record. The code also reverts the changes for the actualPixelSize as mentioned above. And lastly, the code requires the previously submitted changes for the plug-in.<commit_after>// // OpenFlight loader for OpenSceneGraph // // Copyright (C) 2005-2006 Brede Johansen // #include <osgSim/MultiSwitch> #include <osgSim/LightPointSystem> #include <osgSim/LightPointNode> #include <osg/Texture2D> #include "Registry.h" #include "Document.h" #include "RecordInputStream.h" using namespace flt; /** LightPoint */ class LightPoint : public PrimaryRecord { enum Directionality { OMNIDIRECTIONAL = 0, UNIDIRECTIONAL = 1, BIDIRECTIONAL = 2 }; // flags enum Flags { // bit 0 = reserved NO_BACK_COLOR = 0x80000000u >> 1, // bit 1 = no back color // bit 2 = reserved CALLIGRAPHIC = 0x80000000u >> 3, // bit 3 = calligraphic proximity occulting REFLECTIVE = 0x80000000u >> 4, // bit 4 = reflective, non-emissive point // bit 5-7 = randomize intensity // 0 = never // 1 = low // 2 = medium // 3 = high PERSPECTIVE = 0x80000000u >> 8, // bit 8 = perspective mode FLASHING = 0x80000000u >> 9, // bit 9 = flashing ROTATING = 0x80000000u >> 10, // bit 10 = rotating ROTATE_CC = 0x80000000u >> 11, // bit 11 = rotate counter clockwise // bit 12 = reserved // bit 13-14 = quality // 0 = low // 1 = medium // 2 = high // 3 = undefined VISIBLE_DAY = 0x80000000u >> 15, // bit 15 = visible during day VISIBLE_DUSK = 0x80000000u >> 16, // bit 16 = visible during dusk VISIBLE_NIGHT = 0x80000000u >> 17 // bit 17 = visible during night // bit 18-31 = spare }; int16 _material; int16 _feature; osg::Vec4f _backColor; int32 _displayMode; float32 _intensityFront; float32 _intensityBack; float32 _minDefocus; float32 _maxDefocus; int32 _fadeMode; int32 _fogPunchMode; int32 _directionalMode; int32 _rangeMode; float32 _minPixelSize; float32 _maxPixelSize; float32 _actualPixelSize; float32 _transparentFalloff; float32 _transparentFalloffExponent; float32 _transparentFalloffScalar; float32 _transparentFalloffClamp; float32 _fog; float32 _sizeDifferenceThreshold; int32 _directionality; float32 _lobeHorizontal; float32 _lobeVertical; float32 _lobeRoll; float32 _falloff; float32 _ambientIntensity; float32 _animationPeriod; float32 _animationPhaseDelay; float32 _animationPeriodEnable; float32 _significance; int32 _drawOrder; uint32 _flags; osg::Vec3f _animationAxis; osg::ref_ptr<osgSim::LightPointNode> _lpn; public: LightPoint() {} META_Record(LightPoint) META_setID(_lpn) META_setComment(_lpn) META_setMatrix(_lpn) // Add lightpoint, add two if bidirectional. virtual void addVertex(Vertex& vertex) { osgSim::LightPoint lp; lp._position = vertex._coord; lp._radius = 0.5f * _actualPixelSize; lp._intensity = _intensityFront; // color lp._color = (vertex.validColor()) ? vertex._color : osg::Vec4(1,1,1,1); // sector bool directional = (_directionality==UNIDIRECTIONAL) || (_directionality==BIDIRECTIONAL); if (directional && vertex.validNormal()) { lp._sector = new osgSim::DirectionalSector( vertex._normal, osg::DegreesToRadians(_lobeHorizontal), osg::DegreesToRadians(_lobeVertical), osg::DegreesToRadians(_lobeRoll)); } // if the flashing or rotating bit is set in the flags, add a blink sequence if ((_flags & FLASHING) || (_flags & ROTATING)) { lp._blinkSequence = new osgSim::BlinkSequence(); if (lp._blinkSequence.valid()) { lp._blinkSequence->setDataVariance(osg::Object::DataVariance::DYNAMIC); lp._blinkSequence->setPhaseShift(_animationPhaseDelay); lp._blinkSequence->addPulse(_animationPeriod - _animationPeriodEnable, osg::Vec4f(0.0f, 0.0f, 0.0f, 0.0f)); lp._blinkSequence->addPulse(_animationPeriodEnable, lp._color); } } _lpn->addLightPoint(lp); // Create a new lightpoint if bi-directional. if ((_directionality==BIDIRECTIONAL) && vertex.validNormal()) { // back intensity lp._intensity = _intensityBack; // back color if (!(_flags & NO_BACK_COLOR)) lp._color = _backColor; // back sector lp._sector = new osgSim::DirectionalSector( -vertex._normal, osg::DegreesToRadians(_lobeHorizontal), osg::DegreesToRadians(_lobeVertical), osg::DegreesToRadians(_lobeRoll)); _lpn->addLightPoint(lp); } } protected: virtual ~LightPoint() {} virtual void readRecord(RecordInputStream& in, Document& document) { std::string id = in.readString(8); _material = in.readInt16(); _feature = in.readInt16(); int32 backColorIndex = in.readInt32(); _backColor = document.getColorPool() ? document.getColorPool()->getColor(backColorIndex) : osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f); _displayMode = in.readInt32(); _intensityFront = in.readFloat32(); _intensityBack = in.readFloat32(); _minDefocus = in.readFloat32(); _maxDefocus = in.readFloat32(); _fadeMode = in.readInt32(); _fogPunchMode = in.readInt32(); _directionalMode = in.readInt32(); _rangeMode = in.readInt32(); _minPixelSize = in.readFloat32(); // * document.unitScale(); _maxPixelSize = in.readFloat32(); // * document.unitScale(); _actualPixelSize = in.readFloat32(); // * document.unitScale(); _transparentFalloff = in.readFloat32(); _transparentFalloffExponent = in.readFloat32(); _transparentFalloffScalar = in.readFloat32(); _transparentFalloffClamp = in.readFloat32(); _fog = in.readFloat32(); in.forward(4); _sizeDifferenceThreshold = in.readFloat32(); _directionality = in.readInt32(); _lobeHorizontal = in.readFloat32(); _lobeVertical = in.readFloat32(); _lobeRoll = in.readFloat32(); _falloff = in.readFloat32(); _ambientIntensity = in.readFloat32(); _animationPeriod = in.readFloat32(); _animationPhaseDelay = in.readFloat32(); _animationPeriodEnable = in.readFloat32(); _significance = in.readFloat32(); _drawOrder = in.readInt32(); _flags = in.readUInt32(0); _animationAxis = in.readVec3f(); _lpn = new osgSim::LightPointNode; _lpn->setName(id); _lpn->setMinPixelSize(_minPixelSize); _lpn->setMaxPixelSize(_maxPixelSize); // Add to parent if (_parent.valid()) _parent->addChild(*_lpn); } }; RegisterRecordProxy<LightPoint> g_LightPoint(LIGHT_POINT_OP); /** IndexedLightPoint */ class IndexedLightPoint : public PrimaryRecord { enum Directionality { OMNIDIRECTIONAL = 0, UNIDIRECTIONAL = 1, BIDIRECTIONAL = 2 }; // flags static const unsigned int NO_BACK_COLOR_BIT = 0x80000000u >> 1; osg::ref_ptr<osgSim::LightPointNode> _lpn; osg::ref_ptr<LPAppearance> _appearance; osg::ref_ptr<LPAnimation> _animation; public: IndexedLightPoint() {} META_Record(IndexedLightPoint) META_setID(_lpn) META_setComment(_lpn) META_setMatrix(_lpn) // Add lightpoint, add two if bidirectional. virtual void addVertex(Vertex& vertex) { osgSim::LightPoint lp; if (_appearance.valid()) { lp._position = vertex._coord; lp._radius = 0.5f * _appearance->actualPixelSize; lp._intensity = _appearance->intensityFront; // color lp._color = (vertex.validColor()) ? vertex._color : osg::Vec4(1,1,1,1); // sector bool directional = (_appearance->directionality==UNIDIRECTIONAL) || (_appearance->directionality==BIDIRECTIONAL); if (directional && vertex.validNormal()) { lp._sector = new osgSim::DirectionalSector( vertex._normal, osg::DegreesToRadians(_appearance->horizontalLobeAngle), osg::DegreesToRadians(_appearance->verticalLobeAngle), osg::DegreesToRadians(_appearance->lobeRollAngle)); } // Blink sequence if (_animation.valid()) { osgSim::BlinkSequence* blinkSequence = new osgSim::BlinkSequence; blinkSequence->setName(_animation->name); switch (_animation->animationType) { case LPAnimation::ROTATING: case LPAnimation::STROBE: blinkSequence->setPhaseShift(_animation->animationPhaseDelay); blinkSequence->addPulse(_animation->animationPeriod-_animation->animationEnabledPeriod, osg::Vec4(0,0,0,0)); blinkSequence->addPulse(_animation->animationEnabledPeriod, lp._color); break; case LPAnimation::MORSE_CODE: // todo //blinkSequence->addPulse(double length,lp._color); break; case LPAnimation::FLASHING_SEQUENCE: { blinkSequence->setPhaseShift(_animation->animationPhaseDelay); for (LPAnimation::PulseArray::iterator itr=_animation->sequence.begin(); itr!=_animation->sequence.end(); ++itr) { double duration = itr->duration; osg::Vec4 color; switch (itr->state) { case LPAnimation::ON: color = lp._color; break; case LPAnimation::OFF: color = osg::Vec4(0,0,0,0); break; case LPAnimation::COLOR_CHANGE: color = itr->color; break; } blinkSequence->addPulse(duration, color); } } break; } lp._blinkSequence = blinkSequence; } _lpn->addLightPoint(lp); // Create a new lightpoint if bi-directional. if ((_appearance->directionality==BIDIRECTIONAL) && vertex.validNormal()) { // back intensity lp._intensity = _appearance->intensityBack; // back color if (!(_appearance->flags & NO_BACK_COLOR_BIT)) lp._color = _appearance->backColor; // back sector lp._sector = new osgSim::DirectionalSector( -vertex._normal, osg::DegreesToRadians(_appearance->horizontalLobeAngle), osg::DegreesToRadians(_appearance->verticalLobeAngle), osg::DegreesToRadians(_appearance->lobeRollAngle)); _lpn->addLightPoint(lp); } } } protected: virtual ~IndexedLightPoint() {} virtual void readRecord(RecordInputStream& in, Document& document) { std::string id = in.readString(8); int32 appearanceIndex = in.readInt32(); int32 animationIndex = in.readInt32(); int32 drawOrder = in.readInt32(); // for calligraphic lights LightPointAppearancePool* lpAppearancePool = document.getOrCreateLightPointAppearancePool(); _appearance = lpAppearancePool->get(appearanceIndex); LightPointAnimationPool* lpAnimationPool = document.getOrCreateLightPointAnimationPool(); _animation = lpAnimationPool->get(animationIndex); _lpn = new osgSim::LightPointNode; _lpn->setName(id); if (_appearance.valid()) { _lpn->setMinPixelSize(_appearance->minPixelSize); _lpn->setMaxPixelSize(_appearance->maxPixelSize); if (_appearance->texturePatternIndex != -1) { // Use point sprites for light points. _lpn->setPointSprite(); TexturePool* tp = document.getOrCreateTexturePool(); osg::StateSet* textureStateSet = tp->get(_appearance->texturePatternIndex); if (textureStateSet) { // Merge face stateset with texture stateset osg::StateSet* stateset = _lpn->getOrCreateStateSet(); stateset->merge(*textureStateSet); } } } // Add to parent if (_parent.valid()) _parent->addChild(*_lpn); } }; RegisterRecordProxy<IndexedLightPoint> g_IndexedLightPoint(INDEXED_LIGHT_POINT_OP); /** LightPointSystem */ class LightPointSystem : public PrimaryRecord { float32 _intensity; int32 _animationState; int32 _flags; osg::ref_ptr<osgSim::MultiSwitch> _switch; osg::ref_ptr<osgSim::LightPointSystem> _lps; public: LightPointSystem(): _intensity(1.0f), _animationState(0), _flags(0) {} META_Record(LightPointSystem) META_addChild(_switch) protected: virtual ~LightPointSystem() {} virtual void readRecord(RecordInputStream& in, Document& document) { std::string id = in.readString(8); _intensity = in.readFloat32(); _animationState = in.readInt32(0); _flags = in.readInt32(0); _switch = new osgSim::MultiSwitch; _lps = new osgSim::LightPointSystem; _switch->setName(id); _lps->setName(id); _lps->setIntensity(_intensity); switch (_animationState) { // Note that OpenFlight 15.8 spec says 0 means on and 1 means off. // However, if animation is set on in Creator, it stores a 1, and // a zero is stored for off! So, for now, we ignore the spec... case 0: _lps->setAnimationState( osgSim::LightPointSystem::ANIMATION_OFF ); break; default: case 1: _lps->setAnimationState( osgSim::LightPointSystem::ANIMATION_ON ); break; case 2: _lps->setAnimationState( osgSim::LightPointSystem::ANIMATION_RANDOM ); break; } if (_parent.valid()) _parent->addChild(*((osg::Group*)_switch.get())); } virtual void popLevel(Document& document) { // Set default sets: 0 for all off, 1 for all on _switch->setAllChildrenOff( 0 ); _switch->setAllChildrenOn( 1 ); // set initial on/off state unsigned int initialSet = ( (_flags & 0x80000000) != 0 ) ? 1 : 0; _switch->setActiveSwitchSet( initialSet ); for (unsigned int i = 0; i < _switch->getNumChildren(); i++) { osg::Node* child = _switch->getChild(i); if (osgSim::LightPointNode* lpn = dynamic_cast<osgSim::LightPointNode*>(child)) lpn->setLightPointSystem(_lps.get()); } } }; RegisterRecordProxy<LightPointSystem> g_LightPointSystem(LIGHT_POINT_SYSTEM_OP); <|endoftext|>
<commit_before>/// HEADER #include <csapex/view/widgets/message_preview_widget.h> /// PROJECT #include <csapex/msg/direct_connection.h> #include <csapex/manager/message_renderer_manager.h> #include <csapex/msg/io.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/any_message.h> #include <csapex/utility/uuid_provider.h> #include <csapex/utility/exceptions.h> /// SYSTEM #include <QApplication> #include <QGraphicsPixmapItem> #include <QFocusEvent> #include <iostream> using namespace csapex; using namespace csapex::impl; PreviewInput::PreviewInput(QPointer<MessagePreviewWidget> parent) : Input(UUIDProvider::makeUUID_without_parent("message_preview_in")), parent_(parent) { setType(std::make_shared<connection_types::AnyMessage>()); setVirtual(true); } void PreviewInput::setToken(TokenPtr token) { Input::setToken(token); if(isConnected()) { TokenDataConstPtr msg = token->getTokenData(); if(!parent_) { return; } try { if(auto m = msg::message_cast<connection_types::GenericValueMessage<int>>(msg)) { parent_->displayTextRequest(QString::number(m->value)); return; } else if(auto m = msg::message_cast<connection_types::GenericValueMessage<float>>(msg)) { parent_->displayTextRequest(QString::number(m->value)); return; } else if(auto m = msg::message_cast<connection_types::GenericValueMessage<double>>(msg)) { parent_->displayTextRequest(QString::number(m->value)); return; } else if(auto m = msg::message_cast<connection_types::GenericValueMessage<std::string>>(msg)) { parent_->displayTextRequest(QString::fromStdString(m->value)); return; } MessageRenderer::Ptr renderer = MessageRendererManager::instance().createMessageRenderer(msg); if(renderer) { std::unique_ptr<QImage> img = renderer->render(msg); if(parent_) { parent_->displayImageRequest(*img); } } } catch(const std::exception& e) { // silent death } } } void PreviewInput::detach() { parent_.clear(); } MessagePreviewWidget::MessagePreviewWidget() : pm_item_(nullptr), txt_item_(nullptr) { input_ = std::make_shared<impl::PreviewInput>(this); setScene(new QGraphicsScene); setWindowFlags( windowFlags() | Qt::FramelessWindowHint ); scene()->setBackgroundBrush(QBrush()); qRegisterMetaType < TokenDataConstPtr > ("TokenDataConstPtr"); QObject::connect(this, &MessagePreviewWidget::displayImageRequest, this, &MessagePreviewWidget::displayImage); QObject::connect(this, &MessagePreviewWidget::displayTextRequest, this, &MessagePreviewWidget::displayText); setMaximumSize(256, 256); setAutoFillBackground(false); setAttribute( Qt::WA_TranslucentBackground, true ); setAttribute(Qt::WA_NoSystemBackground, true); } MessagePreviewWidget::~MessagePreviewWidget() { if(scene()) { delete scene(); setScene(nullptr); } input_->detach(); if(isConnected()) { disconnect(); } } void MessagePreviewWidget::connectTo(ConnectorPtr c) { scene()->clear(); if(OutputPtr o = std::dynamic_pointer_cast<Output>(c)) { connectToImpl(o); } else if(InputPtr i = std::dynamic_pointer_cast<Input>(c)) { connectToImpl(i); } else { return; } if(connection_) { QApplication::setOverrideCursor(Qt::BusyCursor); } } void MessagePreviewWidget::connectToImpl(OutputPtr out) { try { connection_ = DirectConnection::connect(out, input_); apex_assert_soft_msg(connection_, "could not connect preview widget"); } catch(const csapex::Failure& e) { std::cerr << "connecting preview panel to " << out->getUUID() << " caused an assertion error: " << e.what() << std::endl; } catch(const std::exception& e) { std::cerr << "connecting preview panel to " << out->getUUID() << " failed: " << e.what() << std::endl; } catch(...) { std::cerr << "connecting preview panel to " << out->getUUID() << " failed with unknown cause" << std::endl; } } void MessagePreviewWidget::connectToImpl(InputPtr in) { if(in->isConnected()) { ConnectorPtr s = in->getSource()->shared_from_this(); if(OutputPtr source = std::dynamic_pointer_cast<Output>(s)) { connection_ = DirectConnection::connect(source, input_); } } } void MessagePreviewWidget::disconnect() { if(!connection_) { return; } while(QApplication::overrideCursor()) { QApplication::restoreOverrideCursor(); } OutputPtr out = connection_->from(); if(out) { out->removeConnection(input_.get()); } connection_.reset(); } void MessagePreviewWidget::displayText(const QString& txt) { if(!txt_item_ || txt != displayed_) { displayed_ = txt; if(pm_item_) { scene()->removeItem(pm_item_); delete pm_item_; pm_item_ = nullptr; } if(txt_item_) { txt_item_->setPlainText(txt); } else { txt_item_ = scene()->addText(displayed_); } resize(scene()->sceneRect().width() + 4, scene()->sceneRect().height() + 4); show(); fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } } void MessagePreviewWidget::displayImage(const QImage &img) { if(img.isNull()) { hide(); return; } if(txt_item_) { scene()->removeItem(txt_item_); delete txt_item_; txt_item_ = nullptr; } if(pm_item_) { pm_item_->setPixmap(QPixmap::fromImage(img)); } else { pm_item_ = scene()->addPixmap(QPixmap::fromImage(img)); } fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); show(); } bool MessagePreviewWidget::isConnected() const { return static_cast<bool>(connection_); } /// MOC #include "../../../include/csapex/view/widgets/moc_message_preview_widget.cpp" <commit_msg>Fix message preview for int, float, double and string<commit_after>/// HEADER #include <csapex/view/widgets/message_preview_widget.h> /// PROJECT #include <csapex/msg/direct_connection.h> #include <csapex/manager/message_renderer_manager.h> #include <csapex/msg/io.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/any_message.h> #include <csapex/utility/uuid_provider.h> #include <csapex/utility/exceptions.h> /// SYSTEM #include <QApplication> #include <QGraphicsPixmapItem> #include <QFocusEvent> #include <iostream> using namespace csapex; using namespace csapex::impl; PreviewInput::PreviewInput(QPointer<MessagePreviewWidget> parent) : Input(UUIDProvider::makeUUID_without_parent("message_preview_in")), parent_(parent) { setType(std::make_shared<connection_types::AnyMessage>()); setVirtual(true); } void PreviewInput::setToken(TokenPtr token) { Input::setToken(token); if(isConnected()) { TokenDataConstPtr message = token->getTokenData(); if(!parent_) { return; } try { if(msg::isExactValue<std::string>(this)) { parent_->displayTextRequest(QString::fromStdString(msg::getValue<std::string>(this))); } else if(msg::isExactValue<int>(this)) { parent_->displayTextRequest(QString::number(msg::getValue<int>(this))); } else if(msg::isExactValue<float>(this)) { parent_->displayTextRequest(QString::number(msg::getValue<float>(this))); } else if(msg::isExactValue<double>(this)) { parent_->displayTextRequest(QString::number(msg::getValue<float>(this))); } else { MessageRenderer::Ptr renderer = MessageRendererManager::instance().createMessageRenderer(message); if(renderer) { std::unique_ptr<QImage> img = renderer->render(message); if(parent_) { parent_->displayImageRequest(*img); } } } } catch(const std::exception& e) { // silent death } } } void PreviewInput::detach() { parent_.clear(); } MessagePreviewWidget::MessagePreviewWidget() : pm_item_(nullptr), txt_item_(nullptr) { input_ = std::make_shared<impl::PreviewInput>(this); setScene(new QGraphicsScene); setWindowFlags( windowFlags() | Qt::FramelessWindowHint ); scene()->setBackgroundBrush(QBrush()); qRegisterMetaType < TokenDataConstPtr > ("TokenDataConstPtr"); QObject::connect(this, &MessagePreviewWidget::displayImageRequest, this, &MessagePreviewWidget::displayImage); QObject::connect(this, &MessagePreviewWidget::displayTextRequest, this, &MessagePreviewWidget::displayText); setMaximumSize(256, 256); setAutoFillBackground(false); setAttribute( Qt::WA_TranslucentBackground, true ); setAttribute(Qt::WA_NoSystemBackground, true); } MessagePreviewWidget::~MessagePreviewWidget() { if(scene()) { delete scene(); setScene(nullptr); } input_->detach(); if(isConnected()) { disconnect(); } } void MessagePreviewWidget::connectTo(ConnectorPtr c) { scene()->clear(); if(OutputPtr o = std::dynamic_pointer_cast<Output>(c)) { connectToImpl(o); } else if(InputPtr i = std::dynamic_pointer_cast<Input>(c)) { connectToImpl(i); } else { return; } if(connection_) { QApplication::setOverrideCursor(Qt::BusyCursor); } } void MessagePreviewWidget::connectToImpl(OutputPtr out) { try { connection_ = DirectConnection::connect(out, input_); apex_assert_soft_msg(connection_, "could not connect preview widget"); } catch(const csapex::Failure& e) { std::cerr << "connecting preview panel to " << out->getUUID() << " caused an assertion error: " << e.what() << std::endl; } catch(const std::exception& e) { std::cerr << "connecting preview panel to " << out->getUUID() << " failed: " << e.what() << std::endl; } catch(...) { std::cerr << "connecting preview panel to " << out->getUUID() << " failed with unknown cause" << std::endl; } } void MessagePreviewWidget::connectToImpl(InputPtr in) { if(in->isConnected()) { ConnectorPtr s = in->getSource()->shared_from_this(); if(OutputPtr source = std::dynamic_pointer_cast<Output>(s)) { connection_ = DirectConnection::connect(source, input_); } } } void MessagePreviewWidget::disconnect() { if(!connection_) { return; } while(QApplication::overrideCursor()) { QApplication::restoreOverrideCursor(); } OutputPtr out = connection_->from(); if(out) { out->removeConnection(input_.get()); } connection_.reset(); } void MessagePreviewWidget::displayText(const QString& txt) { if(!txt_item_ || txt != displayed_) { displayed_ = txt; if(pm_item_) { scene()->removeItem(pm_item_); delete pm_item_; pm_item_ = nullptr; } if(txt_item_) { txt_item_->setPlainText(txt); } else { txt_item_ = scene()->addText(displayed_); } resize(scene()->sceneRect().width() + 4, scene()->sceneRect().height() + 4); show(); fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } } void MessagePreviewWidget::displayImage(const QImage &img) { if(img.isNull()) { hide(); return; } if(txt_item_) { scene()->removeItem(txt_item_); delete txt_item_; txt_item_ = nullptr; } if(pm_item_) { pm_item_->setPixmap(QPixmap::fromImage(img)); } else { pm_item_ = scene()->addPixmap(QPixmap::fromImage(img)); } fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); show(); } bool MessagePreviewWidget::isConnected() const { return static_cast<bool>(connection_); } /// MOC #include "../../../include/csapex/view/widgets/moc_message_preview_widget.cpp" <|endoftext|>
<commit_before>// 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 "tink/config/config_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using ::testing::Eq; namespace crypto { namespace tink { TEST(CreateKeyTypeEntry, Simple) { google::crypto::tink::KeyTypeEntry entry = CreateTinkKeyTypeEntry( "catalogue", "primitive_name", "key_proto_name", 12, true); EXPECT_THAT(entry.catalogue_name(), Eq("catalogue")); } } // namespace tink } // namespace crypto <commit_msg>Complete the "config_util_test".<commit_after>// 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 "tink/config/config_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using ::testing::Eq; namespace crypto { namespace tink { TEST(CreateKeyTypeEntry, Simple) { google::crypto::tink::KeyTypeEntry entry = CreateTinkKeyTypeEntry( "catalogue", "primitive_name", "key_proto_name", 12, true); EXPECT_THAT(entry.primitive_name(), Eq("primitive_name")); EXPECT_THAT(entry.type_url(), Eq("type.googleapis.com/google.crypto.tink.key_proto_name")); EXPECT_THAT(entry.key_manager_version(), Eq(12)); EXPECT_THAT(entry.new_key_allowed(), Eq(true)); EXPECT_THAT(entry.catalogue_name(), Eq("catalogue")); } } // namespace tink } // namespace crypto <|endoftext|>
<commit_before>// Time: O(n * m * k) // Space: O(n * m * k) #include <memory> // enum type for Vehicle enum class VehicleSize { Motorcycle, Compact, Large }; // Foward declaration to make circular reference work. class ParkingSpot; class Level; // Use pImpl idiom to make copy assignment work. class VehicleImpl { public: vector<weak_ptr<ParkingSpot>> parking_spots() const noexcept { return parking_spots_; } int spots_needed() const noexcept { return spots_needed_; } VehicleSize size() const noexcept { return size_; } void park_in_spot(const shared_ptr<ParkingSpot>& spot) { parking_spots_.emplace_back(spot); } void clear_spots(); virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return true; } protected: vector<weak_ptr<ParkingSpot>> parking_spots_; int spots_needed_; VehicleSize size_; }; class Vehicle { public: Vehicle() : pImpl_(new VehicleImpl()) {} vector<weak_ptr<ParkingSpot>> parking_spots() const noexcept { return pImpl_->parking_spots(); } int spots_needed() const noexcept { return pImpl_->spots_needed(); } VehicleSize size() const noexcept { return pImpl_->size(); } void park_in_spot(const shared_ptr<ParkingSpot>& spot) { pImpl_->park_in_spot(spot); } void clear_spots() { pImpl_->clear_spots(); } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return pImpl_->can_fit_in_spot(spot); } protected: shared_ptr<VehicleImpl> pImpl_; }; class ParkingSpot : public std::enable_shared_from_this<ParkingSpot> { public: ParkingSpot(const shared_ptr<Level>& level, int row, int spot_number, VehicleSize spot_size) : level_(level), row_(row), spot_number_(spot_number), spot_size_(spot_size), vehicle_(nullptr) {} bool is_available() const noexcept { return vehicle_ == nullptr; } bool can_fit_vehicle(Vehicle *vehicle) { return is_available() && vehicle->can_fit_in_spot(shared_from_this()); } void park(Vehicle *vehicle) { vehicle_ = vehicle; vehicle_->park_in_spot(shared_from_this()); } void remove_vehicle(); int row() const noexcept { return row_; } int spot_number() const noexcept { return spot_number_; } VehicleSize size() const noexcept { return spot_size_; } private: weak_ptr<Level> level_; int row_, spot_number_; VehicleSize spot_size_; Vehicle *vehicle_; }; // Use pImpl idiom to make copy assignment work. class BusImpl: public VehicleImpl { public: BusImpl() { spots_needed_ = 5; size_ = VehicleSize::Large; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return spot->size() == VehicleSize::Large; } }; class Bus: public Vehicle { public: Bus() { pImpl_ = make_shared<BusImpl>(); } }; // Use pImpl idiom to make copy assignment work. class CarImpl: public VehicleImpl { public: CarImpl() { spots_needed_ = 1; size_ = VehicleSize::Compact; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return spot->size() != VehicleSize::Motorcycle; } }; class Car: public Vehicle { public: Car() { pImpl_ = make_shared<CarImpl>(); } }; // Use pImpl idiom to make copy assignment work. class MotorcycleImpl: public VehicleImpl { public: MotorcycleImpl() { spots_needed_ = 1; size_ = VehicleSize::Motorcycle; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return true; } }; class Motorcycle: public Vehicle { public: Motorcycle() { pImpl_ = make_shared<MotorcycleImpl>(); } }; class Level : public std::enable_shared_from_this<Level> { public: Level(int flr, int num_rows, int spots_per_row) : num_rows_(num_rows), floor_(flr), spots_per_row_(spots_per_row), number_spots_(0), available_spots_(0) { } // Use two-phase construction to avoid the problem that // shared_from_this() cannot be used in ctor! void init() { for (int row = 0; row < num_rows_; ++row) { int i = 0; for (; i < spots_per_row_ / 4; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Motorcycle)); ++number_spots_; } for (; i < spots_per_row_ / 4 * 3; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Compact)); ++number_spots_; } for (; i < spots_per_row_; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Large)); ++number_spots_; } } available_spots_ = number_spots_; } bool park_vehicle(Vehicle *vehicle) { if (available_spots() < vehicle->spots_needed()) { return false; } const auto& spot_num = find_available_spots(vehicle); if (spot_num < 0) { return false; } else { park_starting_at_spot(spot_num, vehicle); return true; } } int find_available_spots(Vehicle *vehicle) { const auto& spots_needed = vehicle->spots_needed(); int last_row = -1; int spots_found = 0; for (int i = 0; i < spots_.size(); ++i) { auto& spot = spots_[i]; if (last_row != spot->row()) { spots_found = 0; last_row = spot->row(); } if (spot->can_fit_vehicle(vehicle)) { ++spots_found; } else { spots_found = 0; } if (spots_found == spots_needed) { return i - (spots_needed - 1); } } return -1; } void park_starting_at_spot(int spot_num, Vehicle *vehicle) { for (int i = spot_num; i < spot_num + vehicle->spots_needed(); ++i) { spots_[i]->park(vehicle); } available_spots_ -= vehicle->spots_needed(); } void spot_freed() noexcept { ++available_spots_; } int available_spots() const noexcept { return available_spots_; } private: int num_rows_; int floor_; int spots_per_row_; int number_spots_; int available_spots_; vector<shared_ptr<ParkingSpot>> spots_; }; void VehicleImpl::clear_spots() { for (const auto& spot : parking_spots_) { if (auto spt = spot.lock()) { spt->remove_vehicle(); } } parking_spots_.clear(); } void ParkingSpot::remove_vehicle() { if (auto spt = level_.lock()) { spt->spot_freed(); } vehicle_ = nullptr; } class ParkingLot { public: // @param n number of leves // @param num_rows each level has num_rows rows of spots // @param spots_per_row each row has spots_per_row spots ParkingLot(int n, int num_rows, int spots_per_row) { for (int i = 0; i < n; ++i) { auto&& ptr = make_shared<Level>(i, num_rows, spots_per_row); ptr->init(); levels_.push_back(ptr); } } // Park the vehicle in a spot (or multiple spots) // Return false if failed bool parkVehicle(Vehicle &vehicle) { unParkVehicle(vehicle); // This may make the parked vehicle move to another place. for (auto& level : levels_) { if (level->park_vehicle(&vehicle)) { return true; } } return false; } // unPark the vehicle void unParkVehicle(Vehicle &vehicle) { vehicle.clear_spots(); } private: vector<shared_ptr<Level>> levels_; }; <commit_msg>Update parking-lot.cpp<commit_after>// Time: O(n * m * k) // Space: O(n * m * k) #include <memory> // enum type for Vehicle enum class VehicleSize { Motorcycle, Compact, Large }; // Foward declaration to make circular reference work. class ParkingSpot; class Level; // Use pImpl idiom to make copy assignment work. class VehicleImpl { public: vector<weak_ptr<ParkingSpot>> parking_spots() const noexcept { return parking_spots_; } int spots_needed() const noexcept { return spots_needed_; } VehicleSize size() const noexcept { return size_; } void park_in_spot(const shared_ptr<ParkingSpot>& spot) { parking_spots_.emplace_back(spot); } void clear_spots(); virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return true; } protected: vector<weak_ptr<ParkingSpot>> parking_spots_; int spots_needed_; VehicleSize size_; }; class Vehicle { public: Vehicle() : pImpl_(new VehicleImpl()) {} vector<weak_ptr<ParkingSpot>> parking_spots() const noexcept { return pImpl_->parking_spots(); } int spots_needed() const noexcept { return pImpl_->spots_needed(); } VehicleSize size() const noexcept { return pImpl_->size(); } void park_in_spot(const shared_ptr<ParkingSpot>& spot) { pImpl_->park_in_spot(spot); } void clear_spots() { pImpl_->clear_spots(); } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return pImpl_->can_fit_in_spot(spot); } protected: shared_ptr<VehicleImpl> pImpl_; }; class ParkingSpot : public std::enable_shared_from_this<ParkingSpot> { public: ParkingSpot(const shared_ptr<Level>& level, int row, int spot_number, VehicleSize spot_size) : level_(level), row_(row), spot_number_(spot_number), spot_size_(spot_size), vehicle_(nullptr) {} bool is_available() const noexcept { return vehicle_ == nullptr; } bool can_fit_vehicle(Vehicle *vehicle) { return is_available() && vehicle->can_fit_in_spot(shared_from_this()); } void park(Vehicle *vehicle) { vehicle_ = vehicle; vehicle_->park_in_spot(shared_from_this()); } void remove_vehicle(); int row() const noexcept { return row_; } int spot_number() const noexcept { return spot_number_; } VehicleSize size() const noexcept { return spot_size_; } private: weak_ptr<Level> level_; int row_, spot_number_; VehicleSize spot_size_; Vehicle *vehicle_; }; // Use pImpl idiom to make copy assignment work. class BusImpl: public VehicleImpl { public: BusImpl() { spots_needed_ = 5; size_ = VehicleSize::Large; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return spot->size() == VehicleSize::Large; } }; class Bus: public Vehicle { public: Bus() { pImpl_ = make_shared<BusImpl>(); } }; // Use pImpl idiom to make copy assignment work. class CarImpl: public VehicleImpl { public: CarImpl() { spots_needed_ = 1; size_ = VehicleSize::Compact; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return spot->size() != VehicleSize::Motorcycle; } }; class Car: public Vehicle { public: Car() { pImpl_ = make_shared<CarImpl>(); } }; // Use pImpl idiom to make copy assignment work. class MotorcycleImpl: public VehicleImpl { public: MotorcycleImpl() { spots_needed_ = 1; size_ = VehicleSize::Motorcycle; } virtual bool can_fit_in_spot(const shared_ptr<ParkingSpot>& spot) const noexcept { return true; } }; class Motorcycle: public Vehicle { public: Motorcycle() { pImpl_ = make_shared<MotorcycleImpl>(); } }; class Level : public std::enable_shared_from_this<Level> { public: Level(int flr, int num_rows, int spots_per_row) : num_rows_(num_rows), floor_(flr), spots_per_row_(spots_per_row), number_spots_(0), available_spots_(0) { } // Use two-phase construction to avoid the problem that // shared_from_this() cannot be used in ctor! void init() { for (int row = 0; row < num_rows_; ++row) { int i = 0; for (; i < spots_per_row_ / 4; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Motorcycle)); ++number_spots_; } for (; i < spots_per_row_ / 4 * 3; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Compact)); ++number_spots_; } for (; i < spots_per_row_; ++i) { spots_.emplace_back( make_shared<ParkingSpot>(shared_from_this(), row, number_spots_, VehicleSize::Large)); ++number_spots_; } } available_spots_ = number_spots_; } bool park_vehicle(Vehicle *vehicle) { if (available_spots() < vehicle->spots_needed()) { return false; } const auto& spot_num = find_available_spots(vehicle); if (spot_num < 0) { return false; } else { park_starting_at_spot(spot_num, vehicle); return true; } } int find_available_spots(Vehicle *vehicle) { const auto& spots_needed = vehicle->spots_needed(); int last_row = -1; int spots_found = 0; for (int i = 0; i < spots_.size(); ++i) { auto& spot = spots_[i]; if (last_row != spot->row()) { spots_found = 0; last_row = spot->row(); } if (spot->can_fit_vehicle(vehicle)) { ++spots_found; } else { spots_found = 0; } if (spots_found == spots_needed) { return i - (spots_needed - 1); } } return -1; } void park_starting_at_spot(int spot_num, Vehicle *vehicle) { for (int i = spot_num; i < spot_num + vehicle->spots_needed(); ++i) { spots_[i]->park(vehicle); } available_spots_ -= vehicle->spots_needed(); } void spot_freed() noexcept { ++available_spots_; } int available_spots() const noexcept { return available_spots_; } private: int num_rows_; int floor_; int spots_per_row_; int number_spots_; int available_spots_; vector<shared_ptr<ParkingSpot>> spots_; }; void VehicleImpl::clear_spots() { for (const auto& spot : parking_spots_) { if (auto spt = spot.lock()) { spt->remove_vehicle(); } } parking_spots_.clear(); } void ParkingSpot::remove_vehicle() { if (auto spt = level_.lock()) { spt->spot_freed(); } vehicle_ = nullptr; } class ParkingLot { public: // @param n number of leves // @param num_rows each level has num_rows rows of spots // @param spots_per_row each row has spots_per_row spots ParkingLot(int n, int num_rows, int spots_per_row) { for (int i = 0; i < n; ++i) { auto&& ptr = make_shared<Level>(i, num_rows, spots_per_row); ptr->init(); levels_.emplace_back(ptr); } } // Park the vehicle in a spot (or multiple spots) // Return false if failed bool parkVehicle(Vehicle &vehicle) { unParkVehicle(vehicle); // This may make the parked vehicle move to another place. for (auto& level : levels_) { if (level->park_vehicle(&vehicle)) { return true; } } return false; } // unPark the vehicle void unParkVehicle(Vehicle &vehicle) { vehicle.clear_spots(); } private: vector<shared_ptr<Level>> levels_; }; <|endoftext|>
<commit_before>#include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" namespace ajokki { datatypes::AnyValue* glfwTerminate_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* full_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* delete_suzanne_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* switch_to_new_material( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* transform_into_new_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); } <commit_msg>Added missing `#include` guards.<commit_after>#ifndef __AJOKKI_CALLBACKS_HPP_INCLUDED #define __AJOKKI_CALLBACKS_HPP_INCLUDED #include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" namespace ajokki { datatypes::AnyValue* glfwTerminate_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* full_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* delete_suzanne_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* switch_to_new_material( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* transform_into_new_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); } #endif <|endoftext|>
<commit_before> #pragma once #include "pipe.hpp" namespace lambda { namespace streams { // // `Stream` concept // struct Stream { using Type = void; Maybe<Type> next(); }; template <class C> class CollectionStream : public Stream { C collection; typename C::const_iterator begin, end; public: using Type = typename C::value_type; CollectionStream(C &&collection) : collection(collection), begin(collection.cbegin()), end(collection.cend()) {} Maybe<Type> next() { return begin != end ? some(std::move(*begin++)) : none; } }; template <class C, REQUIRE_CONCEPT(has_iterator_v<C>)> auto stream(C &&c) { return CollectionStream<C>{std::forward<C>(c)}; } template <class F> class FunctionStream : public Stream { F f; public: using Type = typename std::result_of_t<decltype(std::declval<F>)>::value_type; // Maybe::Type FunctionStream(F &&f) : f(f) {} Maybe<Type> next() { return f(); } }; template <class F> // require is_callable auto stream(F &&f) { return FunctionStream<F>{std::forward<F>(f)}; } } /* streams */ } /* lambda */ <commit_msg>Fix tests.<commit_after> #pragma once #include "pipe.hpp" namespace lambda { namespace streams { // // `Stream` concept // struct Stream { using Type = void; Maybe<Type> next(); }; template <class C> class CollectionStream : public Stream { C collection; typename C::const_iterator begin, end; public: using Type = typename C::value_type; CollectionStream(C &&collection) : collection(collection), begin(collection.cbegin()), end(collection.cend()) {} Maybe<Type> next() { return begin != end ? some(std::move(*begin++)) : none; } }; template <class C, REQUIRE_CONCEPT(has_iterator_v<C>)> auto stream(C &&c) { return CollectionStream<C>{std::forward<C>(c)}; } template <class F> class FunctionStream : public Stream { F f; public: using Type = typename std::result_of_t<decltype(std::declval<F>)>::value_type; // Maybe::Type FunctionStream(F &&f) : f(f) {} Maybe<Type> next() { return f(); } }; template <class F, class = std::enable_if_t<is_callable_v<F>>> auto stream(F &&f) { return FunctionStream<F>{std::forward<F>(f)}; } } /* streams */ } /* lambda */ <|endoftext|>
<commit_before>/*************************************************************************** * @file node.hpp * @author Alan.W * @date 03 August 2014 * @remark CLRS Algorithms implementation, using C++ templates. ***************************************************************************/ //! //! ex15.2-2 //! Give a recursive algorithm MATRIX-CHAIN-MULTIPLY(A, s, i, j) that actually //! performs the optimal matrix-chain multiplication, given the sequence of matrices //! {A1,A2,...An}, the s table computed by MATRIX-CHAIN-ORDER , and the indices i and j . //! (The initial call would be MATRIX-CHAIN-MULTIPLY (A, s, 1, n)) //! // check the lambda in function matrix_chain_multiply. //! #ifndef MATRIX_CHAIN_MUTIPLY_HPP #define MATRIX_CHAIN_MUTIPLY_HPP #include <vector> #include <functional> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include "matrix_chain_order.hpp" namespace ch15 { //! foward declarations template<typename Range> void build_chain(ch15::Chain<typename Range::value_type>& chain, const Range& dimensions, const typename Range::value_type& init_val = 0); template<typename Range> void build_dimensions(const ch15::Chain<typename Range::value_type>& chain, Range& dimensions); template<typename T> void print_matrix_chain(const ch15::Chain<T>& chain); template<typename T> ch15::Matrix<T> matrix_chain_multiply(const ch15::Chain<T>& chain); /** * @brief build_chain * @param chain * @param dimensions * * build a matrix chain using dimemsions stored in a stl container */ template<typename Range> inline void build_chain(ch15::Chain<typename Range::value_type>& chain, const Range& dimensions, const typename Range::value_type& init_val) { using ValueType = typename Range::value_type; for(auto it = dimensions.begin(); it != dimensions.end() - 1; ++it) { auto mat = ch15::Matrix<ValueType>(*it, *(it + 1), init_val); chain.push_back(mat); } } /** * @brief print_matrix_chain * @param chain */ template<typename T> inline void print_matrix_chain(const ch15::Chain<T>& chain) { for(const auto& mat : chain) std::cout << mat << std::endl << std::endl; } /** * @brief build_dimensions * @param chain * @param dimensions * * build dimensions from matrix chain */ template<typename Range> inline void build_dimensions(const ch15::Chain<typename Range::value_type>& chain, Range& dimensions) { dimensions.push_back( chain.begin()->size1() ); for(const auto& mat : chain) dimensions.push_back( mat.size2()); } /** * @brief matrix_chain_multiply * @param chain * * for ex15.2-2 */ template<typename T> ch15::Matrix<T> matrix_chain_multiply(const ch15::Chain<T>& chain) { //! type def for MatrixChainOrder's parameter using RangeType = std::vector<T>; using SizeType = typename ch15::Matrix<T>::size_type; //! build dimensions RangeType dimens; ch15::build_dimensions(chain, dimens); //! build optimal order ch15::MatrixChainOrder<RangeType> order(dimens); order.build(); order.print_optimal(1,chain.size()); std::cout << std::endl; //! lambda to do the real job recursively //! @note ex15.2-2 std::function<ch15::Matrix<T>(SizeType,SizeType)> multiply = [&](SizeType head, SizeType tail) { //! @attention below is the pseudocode for ex15.2-2 if(head == tail) return chain[head - 1]; else return multiply(head, order.s(head - 1,tail - 2)) * multiply(order.s(head - 1,tail - 2) + 1, tail); }; //! return the product return multiply(1, chain.size()); } }//namepspace #endif // MATRIX_CHAIN_MUTIPLY_HPP //! test: build_chain //! : build_dimensions //#include <iostream> //#include <boost/numeric/ublas/io.hpp> //#include "color.hpp" //#include "matrix.hpp" //#include "matrix_chain_mutiply.hpp" //#include "matrix_chain_order.hpp" //int main() //{ // std::vector<int> v = {30,35,15,5,10,20,25}; // ch15::Chain<int> chain; // ch15::build_chain(chain, v, 2); // ch15::print_matrix_chain(chain); // std::vector<int> dimens; // ch15::build_dimensions(chain, dimens); // for(auto d : dimens) // std::cout << d << " "; // std::cout << color::red("\nend\n"); // return 0; //} //! @test matrix_chain_multiply //! ex15.2-2 //#include <iostream> //#include <boost/numeric/ublas/io.hpp> //#include "color.hpp" //#include "matrix.hpp" //#include "matrix_chain_mutiply.hpp" //#include "matrix_chain_order.hpp" //int main() //{ // std::vector<int> v = {30,35,15,5,10,20,25}; // ch15::Chain<int> chain; // ch15::build_chain(chain, v, 2); // std::cout << ch15::matrix_chain_multiply(chain) << std::endl; // std::cout << color::red("\nend\n"); // return 0; //} <commit_msg>add complexity comment modified: matrix_chain_mutiply.hpp<commit_after>/*************************************************************************** * @file node.hpp * @author Alan.W * @date 03 August 2014 * @remark CLRS Algorithms implementation, using C++ templates. ***************************************************************************/ //! //! ex15.2-2 //! Give a recursive algorithm MATRIX-CHAIN-MULTIPLY(A, s, i, j) that actually //! performs the optimal matrix-chain multiplication, given the sequence of matrices //! {A1,A2,...An}, the s table computed by MATRIX-CHAIN-ORDER , and the indices i and j . //! (The initial call would be MATRIX-CHAIN-MULTIPLY (A, s, 1, n)) //! // check the lambda in function matrix_chain_multiply. //! #ifndef MATRIX_CHAIN_MUTIPLY_HPP #define MATRIX_CHAIN_MUTIPLY_HPP #include <vector> #include <functional> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include "matrix_chain_order.hpp" namespace ch15 { //! foward declarations template<typename Range> void build_chain(ch15::Chain<typename Range::value_type>& chain, const Range& dimensions, const typename Range::value_type& init_val = 0); template<typename Range> void build_dimensions(const ch15::Chain<typename Range::value_type>& chain, Range& dimensions); template<typename T> void print_matrix_chain(const ch15::Chain<T>& chain); template<typename T> ch15::Matrix<T> matrix_chain_multiply(const ch15::Chain<T>& chain); /** * @brief build_chain * @param chain * @param dimensions * * build a matrix chain using dimemsions stored in a stl container */ template<typename Range> inline void build_chain(ch15::Chain<typename Range::value_type>& chain, const Range& dimensions, const typename Range::value_type& init_val) { using ValueType = typename Range::value_type; for(auto it = dimensions.begin(); it != dimensions.end() - 1; ++it) { auto mat = ch15::Matrix<ValueType>(*it, *(it + 1), init_val); chain.push_back(mat); } } /** * @brief print_matrix_chain * @param chain */ template<typename T> inline void print_matrix_chain(const ch15::Chain<T>& chain) { for(const auto& mat : chain) std::cout << mat << std::endl << std::endl; } /** * @brief build_dimensions * @param chain * @param dimensions * * build dimensions from matrix chain */ template<typename Range> inline void build_dimensions(const ch15::Chain<typename Range::value_type>& chain, Range& dimensions) { dimensions.push_back( chain.begin()->size1() ); for(const auto& mat : chain) dimensions.push_back( mat.size2()); } /** * @brief matrix_chain_multiply * @param chain * * @complx O(n^3) * for ex15.2-2 */ template<typename T> ch15::Matrix<T> matrix_chain_multiply(const ch15::Chain<T>& chain) { //! type def for MatrixChainOrder's parameter using RangeType = std::vector<T>; using SizeType = typename ch15::Matrix<T>::size_type; //! build dimensions RangeType dimens; ch15::build_dimensions(chain, dimens); //! build optimal order ch15::MatrixChainOrder<RangeType> order(dimens); order.build(); order.print_optimal(1,chain.size()); std::cout << std::endl; //! lambda to do the real job recursively //! @note ex15.2-2 std::function<ch15::Matrix<T>(SizeType,SizeType)> multiply = [&](SizeType head, SizeType tail) { //! @attention below is the pseudocode for ex15.2-2 if(head == tail) return chain[head - 1]; else return multiply(head, order.s(head - 1,tail - 2)) * multiply(order.s(head - 1,tail - 2) + 1, tail); }; //! return the product return multiply(1, chain.size()); } }//namepspace #endif // MATRIX_CHAIN_MUTIPLY_HPP //! test: build_chain //! : build_dimensions //#include <iostream> //#include <boost/numeric/ublas/io.hpp> //#include "color.hpp" //#include "matrix.hpp" //#include "matrix_chain_mutiply.hpp" //#include "matrix_chain_order.hpp" //int main() //{ // std::vector<int> v = {30,35,15,5,10,20,25}; // ch15::Chain<int> chain; // ch15::build_chain(chain, v, 2); // ch15::print_matrix_chain(chain); // std::vector<int> dimens; // ch15::build_dimensions(chain, dimens); // for(auto d : dimens) // std::cout << d << " "; // std::cout << color::red("\nend\n"); // return 0; //} //! @test matrix_chain_multiply //! ex15.2-2 //#include <iostream> //#include <boost/numeric/ublas/io.hpp> //#include "color.hpp" //#include "matrix.hpp" //#include "matrix_chain_mutiply.hpp" //#include "matrix_chain_order.hpp" //int main() //{ // std::vector<int> v = {30,35,15,5,10,20,25}; // ch15::Chain<int> chain; // ch15::build_chain(chain, v, 2); // std::cout << ch15::matrix_chain_multiply(chain) << std::endl; // std::cout << color::red("\nend\n"); // return 0; //} <|endoftext|>
<commit_before>// Time: O(max(r, c) * wlogw) // Space: O(w^2) class Solution { public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; int result = -1; priority_queue<node, vector<node>, greater<node>> heap; unordered_set<int> visited; heap.emplace(0, start); while (!heap.empty()) { int dist = 0; vector<int> node; tie(dist, node) = heap.top(); heap.pop(); if (visited.count(hash(maze, node))) { continue; } if (node[0] == destination[0] && node[1] == destination[1]) { result = result != -1 ? min(result, dist) : dist; } visited.emplace(hash(maze, node)); for (const auto& dir : dirs) { int neighbor_dist = 0; vector<int> neighbor; tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); heap.emplace(dist + neighbor_dist, neighbor); } } return result; } private: using node = pair<int, vector<int>>; node findNeighbor(const vector<vector<int>>& maze, const vector<int>& node, const vector<int>& dir) { vector<int> cur_node = node; int dist = 0; while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { cur_node[0] += dir[0]; cur_node[1] += dir[1]; ++dist; } return {dist, cur_node}; } int hash(const vector<vector<int>>& maze, const vector<int>& node) { return node[0] * maze[0].size() + node[1]; } }; <commit_msg>Update the-maze-ii.cpp<commit_after>// Time: O(max(r, c) * wlogw) // Space: O(w^2) class Solution { public: int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) { static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; priority_queue<node, vector<node>, greater<node>> heap; unordered_set<int> visited; heap.emplace(0, start); while (!heap.empty()) { int dist = 0; vector<int> node; tie(dist, node) = heap.top(); heap.pop(); if (visited.count(hash(maze, node))) { continue; } if (node[0] == destination[0] && node[1] == destination[1]) { return dist; } visited.emplace(hash(maze, node)); for (const auto& dir : dirs) { int neighbor_dist = 0; vector<int> neighbor; tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); heap.emplace(dist + neighbor_dist, neighbor); } } return -1; } private: using node = pair<int, vector<int>>; node findNeighbor(const vector<vector<int>>& maze, const vector<int>& node, const vector<int>& dir) { vector<int> cur_node = node; int dist = 0; while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { cur_node[0] += dir[0]; cur_node[1] += dir[1]; ++dist; } return {dist, cur_node}; } int hash(const vector<vector<int>>& maze, const vector<int>& node) { return node[0] * maze[0].size() + node[1]; } }; <|endoftext|>
<commit_before>/* Copyright (c) 2009-2014, 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. */ #include "libtorrent/bandwidth_manager.hpp" #include "libtorrent/time.hpp" namespace libtorrent { bandwidth_manager::bandwidth_manager(int channel #ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT , bool log #endif ) : m_queued_bytes(0) , m_channel(channel) , m_abort(false) { #ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT if (log) m_log.open("bandwidth_limiter.log", std::ios::trunc); m_start = time_now(); #endif } void bandwidth_manager::close() { m_abort = true; m_queue.clear(); m_queued_bytes = 0; } #if TORRENT_USE_ASSERTS bool bandwidth_manager::is_queued(bandwidth_socket const* peer) const { for (queue_t::const_iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { if (i->peer.get() == peer) return true; } return false; } #endif int bandwidth_manager::queue_size() const { return m_queue.size(); } int bandwidth_manager::queued_bytes() const { return m_queued_bytes; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds int bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer , int blk, int priority , bandwidth_channel* chan1 , bandwidth_channel* chan2 , bandwidth_channel* chan3 , bandwidth_channel* chan4 , bandwidth_channel* chan5 ) { INVARIANT_CHECK; if (m_abort) return 0; TORRENT_ASSERT(blk > 0); TORRENT_ASSERT(priority > 0); TORRENT_ASSERT(!is_queued(peer.get())); bw_request bwr(peer, blk, priority); int i = 0; if (chan1 && chan1->throttle() > 0 && chan1->need_queueing(blk)) bwr.channel[i++] = chan1; if (chan2 && chan2->throttle() > 0 && chan2->need_queueing(blk)) bwr.channel[i++] = chan2; if (chan3 && chan3->throttle() > 0 && chan3->need_queueing(blk)) bwr.channel[i++] = chan3; if (chan4 && chan4->throttle() > 0 && chan4->need_queueing(blk)) bwr.channel[i++] = chan4; if (chan5 && chan5->throttle() > 0 && chan5->need_queueing(blk)) bwr.channel[i++] = chan5; if (i == 0) { // the connection is not rate limited by any of its // bandwidth channels, or it doesn't belong to any // channels. There's no point in adding it to // the queue, just satisfy the request immediately return blk; } m_queued_bytes += blk; m_queue.push_back(bwr); return 0; } #if TORRENT_USE_INVARIANT_CHECKS void bandwidth_manager::check_invariant() const { boost::int64_t queued = 0; for (queue_t::const_iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { queued += i->request_size - i->assigned; } TORRENT_ASSERT(queued == m_queued_bytes); } #endif void bandwidth_manager::update_quotas(time_duration const& dt) { if (m_abort) return; if (m_queue.empty()) return; INVARIANT_CHECK; int dt_milliseconds = total_milliseconds(dt); if (dt_milliseconds > 3000) dt_milliseconds = 3000; // for each bandwidth channel, call update_quota(dt) std::vector<bandwidth_channel*> channels; queue_t tm; for (queue_t::iterator i = m_queue.begin(); i != m_queue.end();) { if (i->peer->is_disconnecting()) { m_queued_bytes -= i->request_size - i->assigned; // return all assigned quota to all the // bandwidth channels this peer belongs to for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; bwc->return_quota(i->assigned); } i->assigned = 0; tm.push_back(*i); i = m_queue.erase(i); continue; } for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; bwc->tmp = 0; } ++i; } for (queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; if (bwc->tmp == 0) channels.push_back(bwc); TORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority); bwc->tmp += i->priority; } } for (std::vector<bandwidth_channel*>::iterator i = channels.begin() , end(channels.end()); i != end; ++i) { (*i)->update_quota(dt_milliseconds); } for (queue_t::iterator i = m_queue.begin(); i != m_queue.end();) { int a = i->assign_bandwidth(); if (i->assigned == i->request_size || (i->ttl <= 0 && i->assigned > 0)) { a += i->request_size - i->assigned; TORRENT_ASSERT(i->assigned <= i->request_size); tm.push_back(*i); i = m_queue.erase(i); } else { ++i; } m_queued_bytes -= a; } while (!tm.empty()) { bw_request& bwr = tm.back(); bwr.peer->assign_bandwidth(m_channel, bwr.assigned); tm.pop_back(); } } } <commit_msg>back-port shutdown assert fix<commit_after>/* Copyright (c) 2009-2014, 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. */ #include "libtorrent/bandwidth_manager.hpp" #include "libtorrent/time.hpp" namespace libtorrent { bandwidth_manager::bandwidth_manager(int channel #ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT , bool log #endif ) : m_queued_bytes(0) , m_channel(channel) , m_abort(false) { #ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT if (log) m_log.open("bandwidth_limiter.log", std::ios::trunc); m_start = time_now(); #endif } void bandwidth_manager::close() { m_abort = true; queue_t tm; tm.swap(m_queue); m_queued_bytes = 0; while (!tm.empty()) { bw_request& bwr = tm.back(); bwr.peer->assign_bandwidth(m_channel, bwr.assigned); tm.pop_back(); } } #if TORRENT_USE_ASSERTS bool bandwidth_manager::is_queued(bandwidth_socket const* peer) const { for (queue_t::const_iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { if (i->peer.get() == peer) return true; } return false; } #endif int bandwidth_manager::queue_size() const { return m_queue.size(); } int bandwidth_manager::queued_bytes() const { return m_queued_bytes; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds int bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer , int blk, int priority , bandwidth_channel* chan1 , bandwidth_channel* chan2 , bandwidth_channel* chan3 , bandwidth_channel* chan4 , bandwidth_channel* chan5 ) { INVARIANT_CHECK; if (m_abort) return 0; TORRENT_ASSERT(blk > 0); TORRENT_ASSERT(priority > 0); TORRENT_ASSERT(!is_queued(peer.get())); bw_request bwr(peer, blk, priority); int i = 0; if (chan1 && chan1->throttle() > 0 && chan1->need_queueing(blk)) bwr.channel[i++] = chan1; if (chan2 && chan2->throttle() > 0 && chan2->need_queueing(blk)) bwr.channel[i++] = chan2; if (chan3 && chan3->throttle() > 0 && chan3->need_queueing(blk)) bwr.channel[i++] = chan3; if (chan4 && chan4->throttle() > 0 && chan4->need_queueing(blk)) bwr.channel[i++] = chan4; if (chan5 && chan5->throttle() > 0 && chan5->need_queueing(blk)) bwr.channel[i++] = chan5; if (i == 0) { // the connection is not rate limited by any of its // bandwidth channels, or it doesn't belong to any // channels. There's no point in adding it to // the queue, just satisfy the request immediately return blk; } m_queued_bytes += blk; m_queue.push_back(bwr); return 0; } #if TORRENT_USE_INVARIANT_CHECKS void bandwidth_manager::check_invariant() const { boost::int64_t queued = 0; for (queue_t::const_iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { queued += i->request_size - i->assigned; } TORRENT_ASSERT(queued == m_queued_bytes); } #endif void bandwidth_manager::update_quotas(time_duration const& dt) { if (m_abort) return; if (m_queue.empty()) return; INVARIANT_CHECK; int dt_milliseconds = total_milliseconds(dt); if (dt_milliseconds > 3000) dt_milliseconds = 3000; // for each bandwidth channel, call update_quota(dt) std::vector<bandwidth_channel*> channels; queue_t tm; for (queue_t::iterator i = m_queue.begin(); i != m_queue.end();) { if (i->peer->is_disconnecting()) { m_queued_bytes -= i->request_size - i->assigned; // return all assigned quota to all the // bandwidth channels this peer belongs to for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; bwc->return_quota(i->assigned); } i->assigned = 0; tm.push_back(*i); i = m_queue.erase(i); continue; } for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; bwc->tmp = 0; } ++i; } for (queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { for (int j = 0; j < bw_request::max_bandwidth_channels && i->channel[j]; ++j) { bandwidth_channel* bwc = i->channel[j]; if (bwc->tmp == 0) channels.push_back(bwc); TORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority); bwc->tmp += i->priority; } } for (std::vector<bandwidth_channel*>::iterator i = channels.begin() , end(channels.end()); i != end; ++i) { (*i)->update_quota(dt_milliseconds); } for (queue_t::iterator i = m_queue.begin(); i != m_queue.end();) { int a = i->assign_bandwidth(); if (i->assigned == i->request_size || (i->ttl <= 0 && i->assigned > 0)) { a += i->request_size - i->assigned; TORRENT_ASSERT(i->assigned <= i->request_size); tm.push_back(*i); i = m_queue.erase(i); } else { ++i; } m_queued_bytes -= a; } while (!tm.empty()) { bw_request& bwr = tm.back(); bwr.peer->assign_bandwidth(m_channel, bwr.assigned); tm.pop_back(); } } } <|endoftext|>
<commit_before>#include "app.h" #include <cassert> #include <fstream> #include <regex> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <dependency_graph/port.inl> #include <dependency_graph/node.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/nodes_iterator.inl> #include <actions/actions.h> #include <possumwood_sdk/gl.h> #include <possumwood_sdk/metadata.h> #include "config.inl" namespace possumwood { App* App::s_instance = NULL; App::App() : m_mainWindow(NULL), m_time(0.0f) { assert(s_instance == nullptr); s_instance = this; //////////////////////// // scene configuration m_sceneConfig.addItem(Config::Item("start_time", "timeline", 0.0f, Config::Item::kNoFlags, "Start of the timeline (seconds)")); m_sceneConfig.addItem(Config::Item("end_time", "timeline", 5.0f, Config::Item::kNoFlags, "End of the timeline (seconds)")); m_sceneConfig.addItem(Config::Item("fps", "timeline", 24.0f, Config::Item::kNoFlags, "Scene's frames-per-second value")); /////////////////////// // expressions // find the config file boost::filesystem::path full_path(boost::filesystem::current_path()); while(!full_path.empty()) { if(boost::filesystem::exists(full_path / "possumwood.conf")) break; full_path = full_path.parent_path(); } if(!full_path.empty()) { std::ifstream cfg(((full_path / "possumwood.conf").string())); while(!cfg.eof() && cfg.good()) { std::string line; std::getline(cfg, line); if(!line.empty()) { std::string key; std::string value; int state = 0; for(std::size_t c=0;c<line.length(); ++c) { if(state == 0) { if(line[c] != ' ' && line[c] != '\t') key.push_back(line[c]); else state = 1; } if(state == 1) { if(line[c] != ' ' && line[c] != '\t') state = 2; } if(state == 2) value.push_back(line[c]); } boost::filesystem::path path(value); if(path.is_relative()) path = full_path / path; m_pathVariables[key] = path.string(); } } } else std::cout << "Warning: configuration file 'possumwood.conf' not found!" << std::endl; } App::~App() { assert(s_instance == this); s_instance = nullptr; } App& App::instance() { assert(s_instance != nullptr); return *s_instance; } const boost::filesystem::path& App::filename() const { return m_filename; } void App::newFile() { graph().clear(); m_filename = ""; } void App::loadFile(const possumwood::io::json& json) { // read the graph graph().clear(); undoStack().clear(); dependency_graph::Selection selection; // throwaway possumwood::actions::fromJson(graph(), selection, json); undoStack().clear(); // and read the scene config if(json.find("scene_config") != json.end()) { auto& config = json["scene_config"]; for(auto it = config.begin(); it != config.end(); ++it) { auto& item = possumwood::App::instance().sceneConfig()[it.key()]; if(item.is<int>()) item = it.value().get<int>(); else if(item.is<float>()) item = it.value().get<float>(); else if(item.is<std::string>()) item = it.value().get<std::string>(); else assert(false); } } // read the UI configuration if(QCoreApplication::instance() != nullptr) { if(json.find("ui_geometry") != json.end()) mainWindow()->restoreGeometry( QByteArray::fromBase64(json["ui_geometry"].get<std::string>().c_str())); if(json.find("ui_state") != json.end()) mainWindow()->restoreState( QByteArray::fromBase64(json["ui_state"].get<std::string>().c_str())); } } void App::loadFile(const boost::filesystem::path& filename) { if(!boost::filesystem::exists(filename)) throw std::runtime_error("Cannot open " + filename.string() + " - file not found."); // read the json file std::ifstream in(filename.string()); possumwood::io::json json; in >> json; // update the opened filename const boost::filesystem::path oldFilename = m_filename; m_filename = filename; try { loadFile(json); } catch(...) { // something bad happened - return back the filename value m_filename = oldFilename; throw; } } void App::saveFile() { assert(!m_filename.empty()); saveFile(m_filename); } void App::saveFile(possumwood::io::json& json, bool saveSceneConfig) { // make a json instance containing the graph json = possumwood::actions::toJson(); // save scene config into the json object if(saveSceneConfig) { auto& config = json["scene_config"]; for(auto& i : possumwood::App::instance().sceneConfig()) if(i.is<int>()) config[i.name()] = i.as<int>(); else if(i.is<float>()) config[i.name()] = i.as<float>(); else if(i.is<std::string>()) config[i.name()] = i.as<std::string>(); else assert(false); } // and save the UI configuration if(QCoreApplication::instance() != nullptr) { json["ui_geometry"] = mainWindow()->saveGeometry().toBase64().data(); json["ui_state"] = mainWindow()->saveState().toBase64().data(); } } void App::saveFile(const boost::filesystem::path& fn) { possumwood::io::json json; saveFile(json); // save the json to the file std::ofstream out(fn.string()); out << std::setw(4) << json; // and update the filename m_filename = fn; } QMainWindow* App::mainWindow() const { return m_mainWindow; } void App::setMainWindow(QMainWindow* win) { assert(m_mainWindow == NULL && "setMainWindow is called only once at the beginning of an application"); m_mainWindow = win; } void App::draw(const possumwood::ViewportState& viewport, std::function<void(const dependency_graph::NodeBase&)> stateChangedCallback) { GL_CHECK_ERR; for(auto it = graph().nodes().begin(dependency_graph::Nodes::kRecursive); it != graph().nodes().end(); ++it) { GL_CHECK_ERR; boost::optional<possumwood::Drawable&> drawable = possumwood::Metadata::getDrawable(*it); if(drawable) { const auto currentDrawState = drawable->drawState(); GL_CHECK_ERR; drawable->doDraw(viewport); GL_CHECK_ERR; if(drawable->drawState() != currentDrawState && stateChangedCallback) stateChangedCallback(*it); } GL_CHECK_ERR; } GL_CHECK_ERR; } void App::setTime(float time) { if(m_time != time) { m_time = time; m_timeChanged(time); // TERRIBLE HACK - a special node type that outputs time is handled here for(dependency_graph::Nodes::iterator i = graph().nodes().begin(dependency_graph::Nodes::kRecursive); i != graph().nodes().end(); ++i) if(i->metadata()->type() == "time") i->port(0).set<float>(time); } } float App::time() const { return m_time; } boost::signals2::connection App::onTimeChanged(std::function<void(float)> fn) { return m_timeChanged.connect(fn); } Config& App::sceneConfig() { return m_sceneConfig; } boost::filesystem::path App::expandPath(const boost::filesystem::path& path) const { std::string p = path.string(); const std::regex var("\\$[A-Z]+"); std::smatch match; while(std::regex_search(p, match, var)) { auto it = m_pathVariables.find(match.str().substr(1)); if(it != m_pathVariables.end()) p = match.prefix().str() + it->second.string() + match.suffix().str(); else break; } return p; } boost::filesystem::path App::shrinkPath(const boost::filesystem::path& path) const { std::string p = path.string(); bool cont = true; while(cont) { cont = false; for(auto& i : m_pathVariables) { auto it = p.find(i.second.string()); if(it != std::string::npos) { cont = true; p = p.substr(0, it) + "$" + i.first + p.substr(it + i.second.string().length()); } } } return p; } } <commit_msg>Resolve configuration paths using POSSUMWOOD_CONF_PATH compiler variable<commit_after>#include "app.h" #include <cassert> #include <fstream> #include <regex> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <dependency_graph/port.inl> #include <dependency_graph/node.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/nodes_iterator.inl> #include <actions/actions.h> #include <possumwood_sdk/gl.h> #include <possumwood_sdk/metadata.h> #include "config.inl" #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) namespace possumwood { App* App::s_instance = NULL; App::App() : m_mainWindow(NULL), m_time(0.0f) { assert(s_instance == nullptr); s_instance = this; //////////////////////// // scene configuration m_sceneConfig.addItem(Config::Item("start_time", "timeline", 0.0f, Config::Item::kNoFlags, "Start of the timeline (seconds)")); m_sceneConfig.addItem(Config::Item("end_time", "timeline", 5.0f, Config::Item::kNoFlags, "End of the timeline (seconds)")); m_sceneConfig.addItem(Config::Item("fps", "timeline", 24.0f, Config::Item::kNoFlags, "Scene's frames-per-second value")); /////////////////////// // resolving paths from possumwood.conf boost::filesystem::path conf_path; // conf path can be explicitly defined during the build (at which point we just use it) #ifdef POSSUMWOOD_CONF_PATH conf_path = boost::filesystem::path(TOSTRING(POSSUMWOOD_CONF_PATH)); // however, if that path doesn't exist (for development only) if(!boost::filesystem::exists(conf_path)) { #endif // find the config file in the current or parent directories conf_path = boost::filesystem::path(boost::filesystem::current_path()); while(!conf_path.empty()) { if(boost::filesystem::exists(conf_path / "possumwood.conf")) { conf_path = conf_path / "possumwood.conf"; break; } else conf_path = conf_path.parent_path(); } #ifdef POSSUMWOOD_CONF_PATH } #endif if(!conf_path.empty()) { // parent directory for the config file - used for resolving relative paths const boost::filesystem::path full_path = conf_path.parent_path(); std::ifstream cfg(conf_path.string()); while(!cfg.eof() && cfg.good()) { std::string line; std::getline(cfg, line); if(!line.empty()) { // read the key/value pair of key->path from the file std::string key; std::string value; int state = 0; for(std::size_t c=0;c<line.length(); ++c) { if(state == 0) { if(line[c] != ' ' && line[c] != '\t') key.push_back(line[c]); else state = 1; } if(state == 1) { if(line[c] != ' ' && line[c] != '\t') state = 2; } if(state == 2) value.push_back(line[c]); } boost::filesystem::path path(value); // resolve relative paths to absolute if(path.is_relative()) path = full_path / path; // store this path variable m_pathVariables[key] = path.string(); } } } else std::cout << "Warning: configuration file 'possumwood.conf' not found!" << std::endl; } App::~App() { assert(s_instance == this); s_instance = nullptr; } App& App::instance() { assert(s_instance != nullptr); return *s_instance; } const boost::filesystem::path& App::filename() const { return m_filename; } void App::newFile() { graph().clear(); m_filename = ""; } void App::loadFile(const possumwood::io::json& json) { // read the graph graph().clear(); undoStack().clear(); dependency_graph::Selection selection; // throwaway possumwood::actions::fromJson(graph(), selection, json); undoStack().clear(); // and read the scene config if(json.find("scene_config") != json.end()) { auto& config = json["scene_config"]; for(auto it = config.begin(); it != config.end(); ++it) { auto& item = possumwood::App::instance().sceneConfig()[it.key()]; if(item.is<int>()) item = it.value().get<int>(); else if(item.is<float>()) item = it.value().get<float>(); else if(item.is<std::string>()) item = it.value().get<std::string>(); else assert(false); } } // read the UI configuration if(QCoreApplication::instance() != nullptr) { if(json.find("ui_geometry") != json.end()) mainWindow()->restoreGeometry( QByteArray::fromBase64(json["ui_geometry"].get<std::string>().c_str())); if(json.find("ui_state") != json.end()) mainWindow()->restoreState( QByteArray::fromBase64(json["ui_state"].get<std::string>().c_str())); } } void App::loadFile(const boost::filesystem::path& filename) { if(!boost::filesystem::exists(filename)) throw std::runtime_error("Cannot open " + filename.string() + " - file not found."); // read the json file std::ifstream in(filename.string()); possumwood::io::json json; in >> json; // update the opened filename const boost::filesystem::path oldFilename = m_filename; m_filename = filename; try { loadFile(json); } catch(...) { // something bad happened - return back the filename value m_filename = oldFilename; throw; } } void App::saveFile() { assert(!m_filename.empty()); saveFile(m_filename); } void App::saveFile(possumwood::io::json& json, bool saveSceneConfig) { // make a json instance containing the graph json = possumwood::actions::toJson(); // save scene config into the json object if(saveSceneConfig) { auto& config = json["scene_config"]; for(auto& i : possumwood::App::instance().sceneConfig()) if(i.is<int>()) config[i.name()] = i.as<int>(); else if(i.is<float>()) config[i.name()] = i.as<float>(); else if(i.is<std::string>()) config[i.name()] = i.as<std::string>(); else assert(false); } // and save the UI configuration if(QCoreApplication::instance() != nullptr) { json["ui_geometry"] = mainWindow()->saveGeometry().toBase64().data(); json["ui_state"] = mainWindow()->saveState().toBase64().data(); } } void App::saveFile(const boost::filesystem::path& fn) { possumwood::io::json json; saveFile(json); // save the json to the file std::ofstream out(fn.string()); out << std::setw(4) << json; // and update the filename m_filename = fn; } QMainWindow* App::mainWindow() const { return m_mainWindow; } void App::setMainWindow(QMainWindow* win) { assert(m_mainWindow == NULL && "setMainWindow is called only once at the beginning of an application"); m_mainWindow = win; } void App::draw(const possumwood::ViewportState& viewport, std::function<void(const dependency_graph::NodeBase&)> stateChangedCallback) { GL_CHECK_ERR; for(auto it = graph().nodes().begin(dependency_graph::Nodes::kRecursive); it != graph().nodes().end(); ++it) { GL_CHECK_ERR; boost::optional<possumwood::Drawable&> drawable = possumwood::Metadata::getDrawable(*it); if(drawable) { const auto currentDrawState = drawable->drawState(); GL_CHECK_ERR; drawable->doDraw(viewport); GL_CHECK_ERR; if(drawable->drawState() != currentDrawState && stateChangedCallback) stateChangedCallback(*it); } GL_CHECK_ERR; } GL_CHECK_ERR; } void App::setTime(float time) { if(m_time != time) { m_time = time; m_timeChanged(time); // TERRIBLE HACK - a special node type that outputs time is handled here for(dependency_graph::Nodes::iterator i = graph().nodes().begin(dependency_graph::Nodes::kRecursive); i != graph().nodes().end(); ++i) if(i->metadata()->type() == "time") i->port(0).set<float>(time); } } float App::time() const { return m_time; } boost::signals2::connection App::onTimeChanged(std::function<void(float)> fn) { return m_timeChanged.connect(fn); } Config& App::sceneConfig() { return m_sceneConfig; } boost::filesystem::path App::expandPath(const boost::filesystem::path& path) const { std::string p = path.string(); const std::regex var("\\$[A-Z]+"); std::smatch match; while(std::regex_search(p, match, var)) { auto it = m_pathVariables.find(match.str().substr(1)); if(it != m_pathVariables.end()) p = match.prefix().str() + it->second.string() + match.suffix().str(); else break; } return p; } boost::filesystem::path App::shrinkPath(const boost::filesystem::path& path) const { std::string p = path.string(); bool cont = true; while(cont) { cont = false; for(auto& i : m_pathVariables) { auto it = p.find(i.second.string()); if(it != std::string::npos) { cont = true; p = p.substr(0, it) + "$" + i.first + p.substr(it + i.second.string().length()); } } } return p; } } <|endoftext|>
<commit_before>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This transform is designed to eliminate unreachable internal globals from the // program. It uses an aggressive algorithm, searching out globals that are // known to be alive. After it finds all of the globals which are needed, it // deletes whatever is left over. This allows it to delete recursive chunks of // the program which are unreachable. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Utils/CtorUtils.h" #include "llvm/Transforms/Utils/GlobalStatus.h" using namespace llvm; #define DEBUG_TYPE "globaldce" STATISTIC(NumAliases , "Number of global aliases removed"); STATISTIC(NumFunctions, "Number of functions removed"); STATISTIC(NumIFuncs, "Number of indirect functions removed"); STATISTIC(NumVariables, "Number of global variables removed"); namespace { class GlobalDCELegacyPass : public ModulePass { public: static char ID; // Pass identification, replacement for typeid GlobalDCELegacyPass() : ModulePass(ID) { initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry()); } // run - Do the GlobalDCE pass on the specified module, optionally updating // the specified callgraph to reflect the changes. // bool runOnModule(Module &M) override { if (skipModule(M)) return false; // We need a minimally functional dummy module analysis manager. It needs // to at least know about the possibility of proxying a function analysis // manager. FunctionAnalysisManager DummyFAM; ModuleAnalysisManager DummyMAM; DummyMAM.registerPass( [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); }); auto PA = Impl.run(M, DummyMAM); return !PA.areAllPreserved(); } private: GlobalDCEPass Impl; }; } char GlobalDCELegacyPass::ID = 0; INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination", false, false) // Public interface to the GlobalDCEPass. ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCELegacyPass(); } /// Returns true if F contains only a single "ret" instruction. static bool isEmptyFunction(Function *F) { BasicBlock &Entry = F->getEntryBlock(); if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front())) return false; ReturnInst &RI = cast<ReturnInst>(Entry.front()); return RI.getReturnValue() == nullptr; } /// Compute the set of GlobalValue that depends from V. /// The recursion stops as soon as a GlobalValue is met. void GlobalDCEPass::ComputeDependencies(Value *V, SmallPtrSetImpl<GlobalValue *> &Deps) { if (auto *I = dyn_cast<Instruction>(V)) { Function *Parent = I->getParent()->getParent(); Deps.insert(Parent); } else if (auto *GV = dyn_cast<GlobalValue>(V)) { Deps.insert(GV); } else if (auto *CE = dyn_cast<Constant>(V)) { // Avoid walking the whole tree of a big ConstantExprs multiple times. auto Where = ConstantDependenciesCache.find(CE); if (Where != ConstantDependenciesCache.end()) { auto const &K = Where->second; Deps.insert(K.begin(), K.end()); } else { SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE]; for (User *CEUser : CE->users()) ComputeDependencies(CEUser, LocalDeps); Deps.insert(LocalDeps.begin(), LocalDeps.end()); } } } void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) { SmallPtrSet<GlobalValue *, 8> Deps; for (User *User : GV.users()) ComputeDependencies(User, Deps); Deps.erase(&GV); // Remove self-reference. for (GlobalValue *GVU : Deps) { GVDependencies[GVU].insert(&GV); } } /// Mark Global value as Live void GlobalDCEPass::MarkLive(GlobalValue &GV, SmallVectorImpl<GlobalValue *> *Updates) { auto const Ret = AliveGlobals.insert(&GV); if (!Ret.second) return; if (Updates) Updates->push_back(&GV); if (Comdat *C = GV.getComdat()) { for (auto &&CM : make_range(ComdatMembers.equal_range(C))) MarkLive(*CM.second, Updates); // Recursion depth is only two because only // globals in the same comdat are visited. } } PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) { bool Changed = false; // The algorithm first computes the set L of global variables that are // trivially live. Then it walks the initialization of these variables to // compute the globals used to initialize them, which effectively builds a // directed graph where nodes are global variables, and an edge from A to B // means B is used to initialize A. Finally, it propagates the liveness // information through the graph starting from the nodes in L. Nodes note // marked as alive are discarded. // Remove empty functions from the global ctors list. Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); // Collect the set of members for each comdat. for (Function &F : M) if (Comdat *C = F.getComdat()) ComdatMembers.insert(std::make_pair(C, &F)); for (GlobalVariable &GV : M.globals()) if (Comdat *C = GV.getComdat()) ComdatMembers.insert(std::make_pair(C, &GV)); for (GlobalAlias &GA : M.aliases()) if (Comdat *C = GA.getComdat()) ComdatMembers.insert(std::make_pair(C, &GA)); // Loop over the module, adding globals which are obviously necessary. for (GlobalObject &GO : M.global_objects()) { Changed |= RemoveUnusedGlobalValue(GO); // Functions with external linkage are needed if they have a body. // Externally visible & appending globals are needed, if they have an // initializer. if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage()) if (!GO.isDiscardableIfUnused()) MarkLive(GO); UpdateGVDependencies(GO); } // Compute direct dependencies of aliases. for (GlobalAlias &GA : M.aliases()) { Changed |= RemoveUnusedGlobalValue(GA); // Externally visible aliases are needed. if (!GA.isDiscardableIfUnused()) MarkLive(GA); UpdateGVDependencies(GA); } // Compute direct dependencies of ifuncs. for (GlobalIFunc &GIF : M.ifuncs()) { Changed |= RemoveUnusedGlobalValue(GIF); // Externally visible ifuncs are needed. if (!GIF.isDiscardableIfUnused()) MarkLive(GIF); UpdateGVDependencies(GIF); } // Propagate liveness from collected Global Values through the computed // dependencies. SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(), AliveGlobals.end()}; while (!NewLiveGVs.empty()) { GlobalValue *LGV = NewLiveGVs.pop_back_val(); for (auto *GVD : GVDependencies[LGV]) MarkLive(*GVD, &NewLiveGVs); } // Now that all globals which are needed are in the AliveGlobals set, we loop // through the program, deleting those which are not alive. // // The first pass is to drop initializers of global variables which are dead. std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals for (GlobalVariable &GV : M.globals()) if (!AliveGlobals.count(&GV)) { DeadGlobalVars.push_back(&GV); // Keep track of dead globals if (GV.hasInitializer()) { Constant *Init = GV.getInitializer(); GV.setInitializer(nullptr); if (isSafeToDestroyConstant(Init)) Init->destroyConstant(); } } // The second pass drops the bodies of functions which are dead... std::vector<Function *> DeadFunctions; for (Function &F : M) if (!AliveGlobals.count(&F)) { DeadFunctions.push_back(&F); // Keep track of dead globals if (!F.isDeclaration()) F.deleteBody(); } // The third pass drops targets of aliases which are dead... std::vector<GlobalAlias*> DeadAliases; for (GlobalAlias &GA : M.aliases()) if (!AliveGlobals.count(&GA)) { DeadAliases.push_back(&GA); GA.setAliasee(nullptr); } // The fourth pass drops targets of ifuncs which are dead... std::vector<GlobalIFunc*> DeadIFuncs; for (GlobalIFunc &GIF : M.ifuncs()) if (!AliveGlobals.count(&GIF)) { DeadIFuncs.push_back(&GIF); GIF.setResolver(nullptr); } // Now that all interferences have been dropped, delete the actual objects // themselves. auto EraseUnusedGlobalValue = [&](GlobalValue *GV) { RemoveUnusedGlobalValue(*GV); GV->eraseFromParent(); Changed = true; }; NumFunctions += DeadFunctions.size(); for (Function *F : DeadFunctions) EraseUnusedGlobalValue(F); NumVariables += DeadGlobalVars.size(); for (GlobalVariable *GV : DeadGlobalVars) EraseUnusedGlobalValue(GV); NumAliases += DeadAliases.size(); for (GlobalAlias *GA : DeadAliases) EraseUnusedGlobalValue(GA); NumIFuncs += DeadIFuncs.size(); for (GlobalIFunc *GIF : DeadIFuncs) EraseUnusedGlobalValue(GIF); // Make sure that all memory is released AliveGlobals.clear(); ConstantDependenciesCache.clear(); GVDependencies.clear(); ComdatMembers.clear(); if (Changed) return PreservedAnalyses::none(); return PreservedAnalyses::all(); } // RemoveUnusedGlobalValue - Loop over all of the uses of the specified // GlobalValue, looking for the constant pointer ref that may be pointing to it. // If found, check to see if the constant pointer ref is safe to destroy, and if // so, nuke it. This will reduce the reference count on the global value, which // might make it deader. // bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { if (GV.use_empty()) return false; GV.removeDeadConstantUsers(); return GV.use_empty(); } <commit_msg>[GlobalDCE] AvailableExternal linkage is checked in isDiscardableIfUnused [NFC].<commit_after>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This transform is designed to eliminate unreachable internal globals from the // program. It uses an aggressive algorithm, searching out globals that are // known to be alive. After it finds all of the globals which are needed, it // deletes whatever is left over. This allows it to delete recursive chunks of // the program which are unreachable. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Utils/CtorUtils.h" #include "llvm/Transforms/Utils/GlobalStatus.h" using namespace llvm; #define DEBUG_TYPE "globaldce" STATISTIC(NumAliases , "Number of global aliases removed"); STATISTIC(NumFunctions, "Number of functions removed"); STATISTIC(NumIFuncs, "Number of indirect functions removed"); STATISTIC(NumVariables, "Number of global variables removed"); namespace { class GlobalDCELegacyPass : public ModulePass { public: static char ID; // Pass identification, replacement for typeid GlobalDCELegacyPass() : ModulePass(ID) { initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry()); } // run - Do the GlobalDCE pass on the specified module, optionally updating // the specified callgraph to reflect the changes. // bool runOnModule(Module &M) override { if (skipModule(M)) return false; // We need a minimally functional dummy module analysis manager. It needs // to at least know about the possibility of proxying a function analysis // manager. FunctionAnalysisManager DummyFAM; ModuleAnalysisManager DummyMAM; DummyMAM.registerPass( [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); }); auto PA = Impl.run(M, DummyMAM); return !PA.areAllPreserved(); } private: GlobalDCEPass Impl; }; } char GlobalDCELegacyPass::ID = 0; INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination", false, false) // Public interface to the GlobalDCEPass. ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCELegacyPass(); } /// Returns true if F contains only a single "ret" instruction. static bool isEmptyFunction(Function *F) { BasicBlock &Entry = F->getEntryBlock(); if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front())) return false; ReturnInst &RI = cast<ReturnInst>(Entry.front()); return RI.getReturnValue() == nullptr; } /// Compute the set of GlobalValue that depends from V. /// The recursion stops as soon as a GlobalValue is met. void GlobalDCEPass::ComputeDependencies(Value *V, SmallPtrSetImpl<GlobalValue *> &Deps) { if (auto *I = dyn_cast<Instruction>(V)) { Function *Parent = I->getParent()->getParent(); Deps.insert(Parent); } else if (auto *GV = dyn_cast<GlobalValue>(V)) { Deps.insert(GV); } else if (auto *CE = dyn_cast<Constant>(V)) { // Avoid walking the whole tree of a big ConstantExprs multiple times. auto Where = ConstantDependenciesCache.find(CE); if (Where != ConstantDependenciesCache.end()) { auto const &K = Where->second; Deps.insert(K.begin(), K.end()); } else { SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE]; for (User *CEUser : CE->users()) ComputeDependencies(CEUser, LocalDeps); Deps.insert(LocalDeps.begin(), LocalDeps.end()); } } } void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) { SmallPtrSet<GlobalValue *, 8> Deps; for (User *User : GV.users()) ComputeDependencies(User, Deps); Deps.erase(&GV); // Remove self-reference. for (GlobalValue *GVU : Deps) { GVDependencies[GVU].insert(&GV); } } /// Mark Global value as Live void GlobalDCEPass::MarkLive(GlobalValue &GV, SmallVectorImpl<GlobalValue *> *Updates) { auto const Ret = AliveGlobals.insert(&GV); if (!Ret.second) return; if (Updates) Updates->push_back(&GV); if (Comdat *C = GV.getComdat()) { for (auto &&CM : make_range(ComdatMembers.equal_range(C))) MarkLive(*CM.second, Updates); // Recursion depth is only two because only // globals in the same comdat are visited. } } PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) { bool Changed = false; // The algorithm first computes the set L of global variables that are // trivially live. Then it walks the initialization of these variables to // compute the globals used to initialize them, which effectively builds a // directed graph where nodes are global variables, and an edge from A to B // means B is used to initialize A. Finally, it propagates the liveness // information through the graph starting from the nodes in L. Nodes note // marked as alive are discarded. // Remove empty functions from the global ctors list. Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); // Collect the set of members for each comdat. for (Function &F : M) if (Comdat *C = F.getComdat()) ComdatMembers.insert(std::make_pair(C, &F)); for (GlobalVariable &GV : M.globals()) if (Comdat *C = GV.getComdat()) ComdatMembers.insert(std::make_pair(C, &GV)); for (GlobalAlias &GA : M.aliases()) if (Comdat *C = GA.getComdat()) ComdatMembers.insert(std::make_pair(C, &GA)); // Loop over the module, adding globals which are obviously necessary. for (GlobalObject &GO : M.global_objects()) { Changed |= RemoveUnusedGlobalValue(GO); // Functions with external linkage are needed if they have a body. // Externally visible & appending globals are needed, if they have an // initializer. if (!GO.isDeclaration()) if (!GO.isDiscardableIfUnused()) MarkLive(GO); UpdateGVDependencies(GO); } // Compute direct dependencies of aliases. for (GlobalAlias &GA : M.aliases()) { Changed |= RemoveUnusedGlobalValue(GA); // Externally visible aliases are needed. if (!GA.isDiscardableIfUnused()) MarkLive(GA); UpdateGVDependencies(GA); } // Compute direct dependencies of ifuncs. for (GlobalIFunc &GIF : M.ifuncs()) { Changed |= RemoveUnusedGlobalValue(GIF); // Externally visible ifuncs are needed. if (!GIF.isDiscardableIfUnused()) MarkLive(GIF); UpdateGVDependencies(GIF); } // Propagate liveness from collected Global Values through the computed // dependencies. SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(), AliveGlobals.end()}; while (!NewLiveGVs.empty()) { GlobalValue *LGV = NewLiveGVs.pop_back_val(); for (auto *GVD : GVDependencies[LGV]) MarkLive(*GVD, &NewLiveGVs); } // Now that all globals which are needed are in the AliveGlobals set, we loop // through the program, deleting those which are not alive. // // The first pass is to drop initializers of global variables which are dead. std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals for (GlobalVariable &GV : M.globals()) if (!AliveGlobals.count(&GV)) { DeadGlobalVars.push_back(&GV); // Keep track of dead globals if (GV.hasInitializer()) { Constant *Init = GV.getInitializer(); GV.setInitializer(nullptr); if (isSafeToDestroyConstant(Init)) Init->destroyConstant(); } } // The second pass drops the bodies of functions which are dead... std::vector<Function *> DeadFunctions; for (Function &F : M) if (!AliveGlobals.count(&F)) { DeadFunctions.push_back(&F); // Keep track of dead globals if (!F.isDeclaration()) F.deleteBody(); } // The third pass drops targets of aliases which are dead... std::vector<GlobalAlias*> DeadAliases; for (GlobalAlias &GA : M.aliases()) if (!AliveGlobals.count(&GA)) { DeadAliases.push_back(&GA); GA.setAliasee(nullptr); } // The fourth pass drops targets of ifuncs which are dead... std::vector<GlobalIFunc*> DeadIFuncs; for (GlobalIFunc &GIF : M.ifuncs()) if (!AliveGlobals.count(&GIF)) { DeadIFuncs.push_back(&GIF); GIF.setResolver(nullptr); } // Now that all interferences have been dropped, delete the actual objects // themselves. auto EraseUnusedGlobalValue = [&](GlobalValue *GV) { RemoveUnusedGlobalValue(*GV); GV->eraseFromParent(); Changed = true; }; NumFunctions += DeadFunctions.size(); for (Function *F : DeadFunctions) EraseUnusedGlobalValue(F); NumVariables += DeadGlobalVars.size(); for (GlobalVariable *GV : DeadGlobalVars) EraseUnusedGlobalValue(GV); NumAliases += DeadAliases.size(); for (GlobalAlias *GA : DeadAliases) EraseUnusedGlobalValue(GA); NumIFuncs += DeadIFuncs.size(); for (GlobalIFunc *GIF : DeadIFuncs) EraseUnusedGlobalValue(GIF); // Make sure that all memory is released AliveGlobals.clear(); ConstantDependenciesCache.clear(); GVDependencies.clear(); ComdatMembers.clear(); if (Changed) return PreservedAnalyses::none(); return PreservedAnalyses::all(); } // RemoveUnusedGlobalValue - Loop over all of the uses of the specified // GlobalValue, looking for the constant pointer ref that may be pointing to it. // If found, check to see if the constant pointer ref is safe to destroy, and if // so, nuke it. This will reduce the reference count on the global value, which // might make it deader. // bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { if (GV.use_empty()) return false; GV.removeDeadConstantUsers(); return GV.use_empty(); } <|endoftext|>
<commit_before>//===- InputFiles.cpp -----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Chunks.h" #include "Error.h" #include "InputFiles.h" #include "Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Object/COFF.h" #include "llvm/Support/COFF.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" using namespace llvm::object; using namespace llvm::support::endian; using llvm::COFF::ImportHeader; using llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; using llvm::RoundUpToAlignment; using llvm::sys::fs::identify_magic; using llvm::sys::fs::file_magic; namespace lld { namespace coff { // Returns the last element of a path, which is supposed to be a filename. static StringRef getBasename(StringRef Path) { size_t Pos = Path.find_last_of("\\/"); if (Pos == StringRef::npos) return Path; return Path.substr(Pos + 1); } // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)". std::string InputFile::getShortName() { if (ParentName == "") return getName().lower(); std::string Res = (getBasename(ParentName) + "(" + getBasename(getName()) + ")").str(); return StringRef(Res).lower(); } std::error_code ArchiveFile::parse() { // Parse a MemoryBufferRef as an archive file. auto ArchiveOrErr = Archive::create(MB); if (auto EC = ArchiveOrErr.getError()) return EC; File = std::move(ArchiveOrErr.get()); // Allocate a buffer for Lazy objects. size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy); Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>()); // Read the symbol table to construct Lazy objects. uint32_t I = 0; for (const Archive::Symbol &Sym : File->symbols()) { // Skip special symbol exists in import library files. if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR") continue; SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym)); } return std::error_code(); } // Returns a buffer pointing to a member file containing a given symbol. ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) { auto ItOrErr = Sym->getMember(); if (auto EC = ItOrErr.getError()) return EC; Archive::child_iterator It = ItOrErr.get(); // Return an empty buffer if we have already returned the same buffer. const char *StartAddr = It->getBuffer().data(); auto Pair = Seen.insert(StartAddr); if (!Pair.second) return MemoryBufferRef(); return It->getMemoryBufferRef(); } std::error_code ObjectFile::parse() { // Parse a memory buffer as a COFF file. auto BinOrErr = createBinary(MB); if (auto EC = BinOrErr.getError()) return EC; std::unique_ptr<Binary> Bin = std::move(BinOrErr.get()); if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) { Bin.release(); COFFObj.reset(Obj); } else { llvm::errs() << getName() << " is not a COFF file.\n"; return make_error_code(LLDError::InvalidFile); } // Read section and symbol tables. if (auto EC = initializeChunks()) return EC; return initializeSymbols(); } SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) { return SparseSymbolBodies[SymbolIndex]->getReplacement(); } std::error_code ObjectFile::initializeChunks() { uint32_t NumSections = COFFObj->getNumberOfSections(); Chunks.reserve(NumSections); SparseChunks.resize(NumSections + 1); for (uint32_t I = 1; I < NumSections + 1; ++I) { const coff_section *Sec; StringRef Name; if (auto EC = COFFObj->getSection(I, Sec)) { llvm::errs() << "getSection failed: " << Name << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } if (auto EC = COFFObj->getSectionName(Sec, Name)) { llvm::errs() << "getSectionName failed: " << Name << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } if (Name == ".drectve") { ArrayRef<uint8_t> Data; COFFObj->getSectionContents(Sec, Data); Directives = StringRef((const char *)Data.data(), Data.size()).trim(); continue; } if (Name.startswith(".debug")) continue; if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE) continue; auto *C = new (Alloc) SectionChunk(this, Sec, I); Chunks.push_back(C); SparseChunks[I] = C; } return std::error_code(); } std::error_code ObjectFile::initializeSymbols() { uint32_t NumSymbols = COFFObj->getNumberOfSymbols(); SymbolBodies.reserve(NumSymbols); SparseSymbolBodies.resize(NumSymbols); int32_t LastSectionNumber = 0; for (uint32_t I = 0; I < NumSymbols; ++I) { // Get a COFFSymbolRef object. auto SymOrErr = COFFObj->getSymbol(I); if (auto EC = SymOrErr.getError()) { llvm::errs() << "broken object file: " << getName() << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } COFFSymbolRef Sym = SymOrErr.get(); const void *AuxP = nullptr; if (Sym.getNumberOfAuxSymbols()) AuxP = COFFObj->getSymbol(I + 1)->getRawPtr(); bool IsFirst = (LastSectionNumber != Sym.getSectionNumber()); SymbolBody *Body = createSymbolBody(Sym, AuxP, IsFirst); if (Body) { SymbolBodies.push_back(Body); SparseSymbolBodies[I] = Body; } I += Sym.getNumberOfAuxSymbols(); LastSectionNumber = Sym.getSectionNumber(); } return std::error_code(); } SymbolBody *ObjectFile::createSymbolBody(COFFSymbolRef Sym, const void *AuxP, bool IsFirst) { StringRef Name; if (Sym.isUndefined()) { COFFObj->getSymbolName(Sym, Name); return new (Alloc) Undefined(Name); } if (Sym.isCommon()) { Chunk *C = new (Alloc) CommonChunk(Sym); Chunks.push_back(C); return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C); } if (Sym.isAbsolute()) { COFFObj->getSymbolName(Sym, Name); // Skip special symbols. if (Name == "@comp.id" || Name == "@feat.00") return nullptr; return new (Alloc) DefinedAbsolute(Name, Sym.getValue()); } // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS if (Sym.isWeakExternal()) { COFFObj->getSymbolName(Sym, Name); auto *Aux = (const coff_aux_weak_external *)AuxP; return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]); } // Handle associative sections if (IsFirst && AuxP) { if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) { auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP); if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) { auto *Parent = (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]); if (Parent) Parent->addAssociative((SectionChunk *)C); } } } if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C); return nullptr; } std::error_code ImportFile::parse() { const char *Buf = MB.getBufferStart(); const char *End = MB.getBufferEnd(); const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf); // Check if the total size is valid. if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) { llvm::errs() << "broken import library\n"; return make_error_code(LLDError::BrokenFile); } // Read names and create an __imp_ symbol. StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr))); StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name); StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1); StringRef ExternalName = Name; if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL) ExternalName = ""; auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName, Hdr); SymbolBodies.push_back(ImpSym); // If type is function, we need to create a thunk which jump to an // address pointed by the __imp_ symbol. (This allows you to call // DLL functions just like regular non-DLL functions.) if (Hdr->getType() == llvm::COFF::IMPORT_CODE) SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym)); return std::error_code(); } std::error_code BitcodeFile::parse() { std::string Err; M.reset(LTOModule::createFromBuffer(MB.getBufferStart(), MB.getBufferSize(), llvm::TargetOptions(), Err)); if (!Err.empty()) { llvm::errs() << Err << '\n'; return make_error_code(LLDError::BrokenFile); } llvm::BumpPtrStringSaver Saver(Alloc); for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) { lto_symbol_attributes Attrs = M->getSymbolAttributes(I); if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; StringRef SymName = Saver.save(M->getSymbolName(I)); int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK; if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) { SymbolBodies.push_back(new (Alloc) Undefined(SymName)); } else { bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || (Attrs & LTO_SYMBOL_COMDAT)); SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName, Replaceable)); const llvm::GlobalValue *GV = M->getSymbolGV(I); if (GV && GV->hasDLLExportStorageClass()) { Directives += " /export:"; Directives += SymName; if (!GV->getValueType()->isFunctionTy()) Directives += ",data"; } } } // Extract any linker directives from the bitcode file, which are represented // as module flags with the key "Linker Options". llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags; M->getModule().getModuleFlagsMetadata(Flags); for (auto &&Flag : Flags) { if (Flag.Key->getString() != "Linker Options") continue; for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) { for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) { Directives += " "; Directives += cast<llvm::MDString>(InnerOp)->getString(); } } } return std::error_code(); } } // namespace coff } // namespace lld <commit_msg>COFF: Cache Archive::Symbol::getName(). NFC.<commit_after>//===- InputFiles.cpp -----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Chunks.h" #include "Error.h" #include "InputFiles.h" #include "Writer.h" #include "llvm/ADT/STLExtras.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Object/COFF.h" #include "llvm/Support/COFF.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" using namespace llvm::object; using namespace llvm::support::endian; using llvm::COFF::ImportHeader; using llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; using llvm::RoundUpToAlignment; using llvm::sys::fs::identify_magic; using llvm::sys::fs::file_magic; namespace lld { namespace coff { // Returns the last element of a path, which is supposed to be a filename. static StringRef getBasename(StringRef Path) { size_t Pos = Path.find_last_of("\\/"); if (Pos == StringRef::npos) return Path; return Path.substr(Pos + 1); } // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)". std::string InputFile::getShortName() { if (ParentName == "") return getName().lower(); std::string Res = (getBasename(ParentName) + "(" + getBasename(getName()) + ")").str(); return StringRef(Res).lower(); } std::error_code ArchiveFile::parse() { // Parse a MemoryBufferRef as an archive file. auto ArchiveOrErr = Archive::create(MB); if (auto EC = ArchiveOrErr.getError()) return EC; File = std::move(ArchiveOrErr.get()); // Allocate a buffer for Lazy objects. size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy); Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>()); // Read the symbol table to construct Lazy objects. uint32_t I = 0; for (const Archive::Symbol &Sym : File->symbols()) { auto *B = new (&Buf[I++]) Lazy(this, Sym); // Skip special symbol exists in import library files. if (B->getName() != "__NULL_IMPORT_DESCRIPTOR") SymbolBodies.push_back(B); } return std::error_code(); } // Returns a buffer pointing to a member file containing a given symbol. ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) { auto ItOrErr = Sym->getMember(); if (auto EC = ItOrErr.getError()) return EC; Archive::child_iterator It = ItOrErr.get(); // Return an empty buffer if we have already returned the same buffer. const char *StartAddr = It->getBuffer().data(); auto Pair = Seen.insert(StartAddr); if (!Pair.second) return MemoryBufferRef(); return It->getMemoryBufferRef(); } std::error_code ObjectFile::parse() { // Parse a memory buffer as a COFF file. auto BinOrErr = createBinary(MB); if (auto EC = BinOrErr.getError()) return EC; std::unique_ptr<Binary> Bin = std::move(BinOrErr.get()); if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) { Bin.release(); COFFObj.reset(Obj); } else { llvm::errs() << getName() << " is not a COFF file.\n"; return make_error_code(LLDError::InvalidFile); } // Read section and symbol tables. if (auto EC = initializeChunks()) return EC; return initializeSymbols(); } SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) { return SparseSymbolBodies[SymbolIndex]->getReplacement(); } std::error_code ObjectFile::initializeChunks() { uint32_t NumSections = COFFObj->getNumberOfSections(); Chunks.reserve(NumSections); SparseChunks.resize(NumSections + 1); for (uint32_t I = 1; I < NumSections + 1; ++I) { const coff_section *Sec; StringRef Name; if (auto EC = COFFObj->getSection(I, Sec)) { llvm::errs() << "getSection failed: " << Name << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } if (auto EC = COFFObj->getSectionName(Sec, Name)) { llvm::errs() << "getSectionName failed: " << Name << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } if (Name == ".drectve") { ArrayRef<uint8_t> Data; COFFObj->getSectionContents(Sec, Data); Directives = StringRef((const char *)Data.data(), Data.size()).trim(); continue; } if (Name.startswith(".debug")) continue; if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE) continue; auto *C = new (Alloc) SectionChunk(this, Sec, I); Chunks.push_back(C); SparseChunks[I] = C; } return std::error_code(); } std::error_code ObjectFile::initializeSymbols() { uint32_t NumSymbols = COFFObj->getNumberOfSymbols(); SymbolBodies.reserve(NumSymbols); SparseSymbolBodies.resize(NumSymbols); int32_t LastSectionNumber = 0; for (uint32_t I = 0; I < NumSymbols; ++I) { // Get a COFFSymbolRef object. auto SymOrErr = COFFObj->getSymbol(I); if (auto EC = SymOrErr.getError()) { llvm::errs() << "broken object file: " << getName() << ": " << EC.message() << "\n"; return make_error_code(LLDError::BrokenFile); } COFFSymbolRef Sym = SymOrErr.get(); const void *AuxP = nullptr; if (Sym.getNumberOfAuxSymbols()) AuxP = COFFObj->getSymbol(I + 1)->getRawPtr(); bool IsFirst = (LastSectionNumber != Sym.getSectionNumber()); SymbolBody *Body = createSymbolBody(Sym, AuxP, IsFirst); if (Body) { SymbolBodies.push_back(Body); SparseSymbolBodies[I] = Body; } I += Sym.getNumberOfAuxSymbols(); LastSectionNumber = Sym.getSectionNumber(); } return std::error_code(); } SymbolBody *ObjectFile::createSymbolBody(COFFSymbolRef Sym, const void *AuxP, bool IsFirst) { StringRef Name; if (Sym.isUndefined()) { COFFObj->getSymbolName(Sym, Name); return new (Alloc) Undefined(Name); } if (Sym.isCommon()) { Chunk *C = new (Alloc) CommonChunk(Sym); Chunks.push_back(C); return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C); } if (Sym.isAbsolute()) { COFFObj->getSymbolName(Sym, Name); // Skip special symbols. if (Name == "@comp.id" || Name == "@feat.00") return nullptr; return new (Alloc) DefinedAbsolute(Name, Sym.getValue()); } // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS if (Sym.isWeakExternal()) { COFFObj->getSymbolName(Sym, Name); auto *Aux = (const coff_aux_weak_external *)AuxP; return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]); } // Handle associative sections if (IsFirst && AuxP) { if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) { auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP); if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) { auto *Parent = (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]); if (Parent) Parent->addAssociative((SectionChunk *)C); } } } if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C); return nullptr; } std::error_code ImportFile::parse() { const char *Buf = MB.getBufferStart(); const char *End = MB.getBufferEnd(); const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf); // Check if the total size is valid. if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) { llvm::errs() << "broken import library\n"; return make_error_code(LLDError::BrokenFile); } // Read names and create an __imp_ symbol. StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr))); StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name); StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1); StringRef ExternalName = Name; if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL) ExternalName = ""; auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName, Hdr); SymbolBodies.push_back(ImpSym); // If type is function, we need to create a thunk which jump to an // address pointed by the __imp_ symbol. (This allows you to call // DLL functions just like regular non-DLL functions.) if (Hdr->getType() == llvm::COFF::IMPORT_CODE) SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym)); return std::error_code(); } std::error_code BitcodeFile::parse() { std::string Err; M.reset(LTOModule::createFromBuffer(MB.getBufferStart(), MB.getBufferSize(), llvm::TargetOptions(), Err)); if (!Err.empty()) { llvm::errs() << Err << '\n'; return make_error_code(LLDError::BrokenFile); } llvm::BumpPtrStringSaver Saver(Alloc); for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) { lto_symbol_attributes Attrs = M->getSymbolAttributes(I); if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL) continue; StringRef SymName = Saver.save(M->getSymbolName(I)); int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK; if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) { SymbolBodies.push_back(new (Alloc) Undefined(SymName)); } else { bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || (Attrs & LTO_SYMBOL_COMDAT)); SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName, Replaceable)); const llvm::GlobalValue *GV = M->getSymbolGV(I); if (GV && GV->hasDLLExportStorageClass()) { Directives += " /export:"; Directives += SymName; if (!GV->getValueType()->isFunctionTy()) Directives += ",data"; } } } // Extract any linker directives from the bitcode file, which are represented // as module flags with the key "Linker Options". llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags; M->getModule().getModuleFlagsMetadata(Flags); for (auto &&Flag : Flags) { if (Flag.Key->getString() != "Linker Options") continue; for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) { for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) { Directives += " "; Directives += cast<llvm::MDString>(InnerOp)->getString(); } } } return std::error_code(); } } // namespace coff } // namespace lld <|endoftext|>
<commit_before>/* This file is part of SWGANH. For more information, visit http://swganh.com Copyright (c) 2006 - 2011 The SWG:ANH Team 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 "mysql_character_provider.h" #include <boost/lexical_cast.hpp> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include "anh/crc.h" #include "swganh/app/swganh_kernel.h" #include "anh/database/database_manager.h" #include "anh/service/service_directory.h" #include <cppconn/connection.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include <cppconn/sqlstring.h> #include "swganh/messages/delete_character_reply_message.h" #include "swganh/character/character_data.h" #include "swganh/messages/delete_character_message.h" #include "swganh/messages/client_create_character.h" #include "swganh/messages/client_create_character_success.h" #include "swganh/messages/client_create_character_failed.h" #include "swganh/messages/client_random_name_request.h" #include "swganh/messages/client_random_name_response.h" #include "swganh/object/player/player.h" #include "anh/logger.h" using namespace std; using namespace anh; using namespace anh::app; using namespace anh::database; using namespace plugins::mysql_character; using namespace swganh::character; using namespace swganh::messages; MysqlCharacterProvider::MysqlCharacterProvider(KernelInterface* kernel) : CharacterProviderInterface() , kernel_(kernel) {} vector<CharacterData> MysqlCharacterProvider::GetCharactersForAccount(uint64_t account_id) { vector<CharacterData> characters; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("CALL sp_ReturnAccountCharacters(?);") ); statement->setInt64(1, account_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); uint16_t chars_count = result_set->rowsCount(); if (chars_count > 0) { // this is needed to ensure we don't get commands out of sync errors while (result_set->next()) { CharacterData character; character.character_id = result_set->getUInt64("id"); string custom_name = result_set->getString("custom_name"); character.name = std::wstring(custom_name.begin(), custom_name.end()); std::string non_shared_template = result_set->getString("iff_template"); if (non_shared_template.size() > 30) { non_shared_template.erase(23, 7); } character.race_crc = anh::memcrc(non_shared_template); character.galaxy_id = kernel_->GetServiceDirectory()->galaxy().id(); character.status = 1; characters.push_back(character); } while (statement->getMoreResults()); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return characters; } bool MysqlCharacterProvider::DeleteCharacter(uint64_t character_id, uint64_t account_id){ // this actually just archives the character and all their data so it can still be retrieved at a later time string sql = "CALL sp_CharacterDelete(?,?);"; int rows_updated = 0; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement(sql)); statement->setUInt64(1, character_id); statement->setUInt64(2, account_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { rows_updated = result_set->getInt(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return rows_updated > 0; } std::wstring MysqlCharacterProvider::GetRandomNameRequest(const std::string& base_model) { try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("CALL sp_CharacterNameCreate(?);") ); statement->setString(1, base_model); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { std::string str = result_set->getString(1); std::wstring wstr(str.begin(), str.end()); return wstr; } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return L""; } uint16_t MysqlCharacterProvider::GetMaxCharacters(uint64_t player_id) { uint16_t max_chars = 2; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("SELECT max_characters from player_account where id = ?") ); statement->setUInt64(1, player_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { max_chars = result_set->getUInt(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return max_chars; } tuple<uint64_t, string> MysqlCharacterProvider::CreateCharacter(const ClientCreateCharacter& character_info, uint32_t account_id) { try { // A regular expression that searches for a first name and optional sirname. // Only letters, and the ' and - characters are allowed. Only 3 instances // of the ' and - characters may be in the entire name, which must be between // 3 and 16 characters long. const wregex p( L"(?!['-])" // confirm the first character is not ' or - L"(?!(.*['-]){4,})" // Confirm that no more than 3 instances of ' or - appear L"([a-zA-Z][a-z'-]{2,15})" // Firstname capture group: 3-16 chars must be a-zA-Z or ' or - L"(\\s([a-zA-Z][a-z'-]{2,15}))?" // Optional sirname group, same restrictions as sirname ); wsmatch m; if (! regex_match(character_info.character_name, m, p)) { LOG(warning) << "Invalid character name [" << std::string(character_info.character_name.begin(), character_info.character_name.end()) << "]"; return make_tuple(0,"name_declined_syntax"); } std::wstring first_name = m[2].str(); std::wstring last_name = m[4].str(); std::wstring custom_name = first_name; if (!last_name.empty()) { custom_name += L" " + last_name; } auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); std::unique_ptr<sql::PreparedStatement> statement(conn->prepareStatement( "CALL sp_CharacterCreate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @output)")); LOG(warning) << "Creating character with location " << account_id; statement->setUInt(1, account_id); statement->setUInt(2, kernel_->GetServiceDirectory()->galaxy().id()); statement->setString(3, string(first_name.begin(), first_name.end())); statement->setString(4, string(last_name.begin(), last_name.end())); statement->setString(5, string(custom_name.begin(), custom_name.end())); statement->setString(6, character_info.starting_profession); statement->setString(7, character_info.start_location); statement->setDouble(8, character_info.height); statement->setString(9, character_info.biography); statement->setString(10, character_info.character_customization); statement->setString(11, character_info.hair_object); statement->setString(12, character_info.hair_customization); statement->setString(13, character_info.player_race_iff); statement->execute(); statement.reset(conn->prepareStatement("SELECT @output as _object_id")); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { uint64_t char_id = result_set->getUInt64(1); if (char_id < 1002) { // if we get a special character_id back it means there was an error. /// @TODO Change this to return a separate output value for the error code return make_tuple(0, setCharacterCreateErrorCode_(static_cast<uint32_t>(char_id))); } return make_tuple(char_id, ""); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return make_tuple(0, "name_declined_internal_error"); } std::string MysqlCharacterProvider::setCharacterCreateErrorCode_(uint32_t error_code) { std::string error_string; switch(error_code) { case 0: error_string = "name_declined_developer"; break; case 1: error_string = "name_declined_empty"; break; case 2: error_string = "name_declined_fictionally_reserved"; break; case 3: error_string = "name_declined_in_use"; break; case 4: error_string = "name_declined_internal_error"; break; case 5: error_string = "name_declined_no_name_generator"; break; case 6: error_string = "name_declined_no_template"; break; case 7: error_string = "name_declined_not_authorized_for_species"; break; case 8: error_string = "name_declined_not_creature_template"; break; case 9: error_string = "name_declined_not_authorized_for_species"; break; case 10: error_string = "name_declined_number"; break; case 11: error_string = "name_declined_profane"; break; case 12: error_string = "name_declined_racially_inappropriate"; break; case 13: error_string = "name_declined_reserved"; break; case 14: error_string = "name_declined_retry"; break; case 15: error_string = "name_declined_syntax"; break; case 16: error_string = "name_declined_too_fast"; break; case 17: error_string = "name_declined_cant_create_avatar"; break; default: error_string = "name_declined_internal_error"; break; } return error_string; } uint64_t MysqlCharacterProvider::GetCharacterIdByName(const string& name) { uint64_t character_id = 0; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::unique_ptr<sql::PreparedStatement>( conn->prepareStatement("SELECT id FROM object where custom_name like ? and type_id = ?;") ); statement->setString(1, name + '%'); statement->setUInt(2, swganh::object::player::Player::type); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { character_id = result_set->getUInt64(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return character_id; }<commit_msg>Fixes issue with missing regex using's.<commit_after>/* This file is part of SWGANH. For more information, visit http://swganh.com Copyright (c) 2006 - 2011 The SWG:ANH Team 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 "mysql_character_provider.h" #include <boost/lexical_cast.hpp> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include "anh/crc.h" #include "swganh/app/swganh_kernel.h" #include "anh/database/database_manager.h" #include "anh/service/service_directory.h" #include <cppconn/connection.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include <cppconn/sqlstring.h> #include "swganh/messages/delete_character_reply_message.h" #include "swganh/character/character_data.h" #include "swganh/messages/delete_character_message.h" #include "swganh/messages/client_create_character.h" #include "swganh/messages/client_create_character_success.h" #include "swganh/messages/client_create_character_failed.h" #include "swganh/messages/client_random_name_request.h" #include "swganh/messages/client_random_name_response.h" #include "swganh/object/player/player.h" #include "anh/logger.h" using namespace std; using namespace anh; using namespace anh::app; using namespace anh::database; using namespace plugins::mysql_character; using namespace swganh::character; using namespace swganh::messages; #ifdef WIN32 using std::wregex; using std::wsmatch; using std::regex_match; #else using boost::wregex; using boost::wsmatch; using boost::regex_match; #endif MysqlCharacterProvider::MysqlCharacterProvider(KernelInterface* kernel) : CharacterProviderInterface() , kernel_(kernel) {} vector<CharacterData> MysqlCharacterProvider::GetCharactersForAccount(uint64_t account_id) { vector<CharacterData> characters; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("CALL sp_ReturnAccountCharacters(?);") ); statement->setInt64(1, account_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); uint16_t chars_count = result_set->rowsCount(); if (chars_count > 0) { // this is needed to ensure we don't get commands out of sync errors while (result_set->next()) { CharacterData character; character.character_id = result_set->getUInt64("id"); string custom_name = result_set->getString("custom_name"); character.name = std::wstring(custom_name.begin(), custom_name.end()); std::string non_shared_template = result_set->getString("iff_template"); if (non_shared_template.size() > 30) { non_shared_template.erase(23, 7); } character.race_crc = anh::memcrc(non_shared_template); character.galaxy_id = kernel_->GetServiceDirectory()->galaxy().id(); character.status = 1; characters.push_back(character); } while (statement->getMoreResults()); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return characters; } bool MysqlCharacterProvider::DeleteCharacter(uint64_t character_id, uint64_t account_id){ // this actually just archives the character and all their data so it can still be retrieved at a later time string sql = "CALL sp_CharacterDelete(?,?);"; int rows_updated = 0; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = shared_ptr<sql::PreparedStatement>(conn->prepareStatement(sql)); statement->setUInt64(1, character_id); statement->setUInt64(2, account_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { rows_updated = result_set->getInt(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return rows_updated > 0; } std::wstring MysqlCharacterProvider::GetRandomNameRequest(const std::string& base_model) { try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("CALL sp_CharacterNameCreate(?);") ); statement->setString(1, base_model); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { std::string str = result_set->getString(1); std::wstring wstr(str.begin(), str.end()); return wstr; } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return L""; } uint16_t MysqlCharacterProvider::GetMaxCharacters(uint64_t player_id) { uint16_t max_chars = 2; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::shared_ptr<sql::PreparedStatement>( conn->prepareStatement("SELECT max_characters from player_account where id = ?") ); statement->setUInt64(1, player_id); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { max_chars = result_set->getUInt(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return max_chars; } tuple<uint64_t, string> MysqlCharacterProvider::CreateCharacter(const ClientCreateCharacter& character_info, uint32_t account_id) { try { // A regular expression that searches for a first name and optional sirname. // Only letters, and the ' and - characters are allowed. Only 3 instances // of the ' and - characters may be in the entire name, which must be between // 3 and 16 characters long. const wregex p( L"(?!['-])" // confirm the first character is not ' or - L"(?!(.*['-]){4,})" // Confirm that no more than 3 instances of ' or - appear L"([a-zA-Z][a-z'-]{2,15})" // Firstname capture group: 3-16 chars must be a-zA-Z or ' or - L"(\\s([a-zA-Z][a-z'-]{2,15}))?" // Optional sirname group, same restrictions as sirname ); wsmatch m; if (! regex_match(character_info.character_name, m, p)) { LOG(warning) << "Invalid character name [" << std::string(character_info.character_name.begin(), character_info.character_name.end()) << "]"; return make_tuple(0,"name_declined_syntax"); } std::wstring first_name = m[2].str(); std::wstring last_name = m[4].str(); std::wstring custom_name = first_name; if (!last_name.empty()) { custom_name += L" " + last_name; } auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); std::unique_ptr<sql::PreparedStatement> statement(conn->prepareStatement( "CALL sp_CharacterCreate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @output)")); LOG(warning) << "Creating character with location " << account_id; statement->setUInt(1, account_id); statement->setUInt(2, kernel_->GetServiceDirectory()->galaxy().id()); statement->setString(3, string(first_name.begin(), first_name.end())); statement->setString(4, string(last_name.begin(), last_name.end())); statement->setString(5, string(custom_name.begin(), custom_name.end())); statement->setString(6, character_info.starting_profession); statement->setString(7, character_info.start_location); statement->setDouble(8, character_info.height); statement->setString(9, character_info.biography); statement->setString(10, character_info.character_customization); statement->setString(11, character_info.hair_object); statement->setString(12, character_info.hair_customization); statement->setString(13, character_info.player_race_iff); statement->execute(); statement.reset(conn->prepareStatement("SELECT @output as _object_id")); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { uint64_t char_id = result_set->getUInt64(1); if (char_id < 1002) { // if we get a special character_id back it means there was an error. /// @TODO Change this to return a separate output value for the error code return make_tuple(0, setCharacterCreateErrorCode_(static_cast<uint32_t>(char_id))); } return make_tuple(char_id, ""); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return make_tuple(0, "name_declined_internal_error"); } std::string MysqlCharacterProvider::setCharacterCreateErrorCode_(uint32_t error_code) { std::string error_string; switch(error_code) { case 0: error_string = "name_declined_developer"; break; case 1: error_string = "name_declined_empty"; break; case 2: error_string = "name_declined_fictionally_reserved"; break; case 3: error_string = "name_declined_in_use"; break; case 4: error_string = "name_declined_internal_error"; break; case 5: error_string = "name_declined_no_name_generator"; break; case 6: error_string = "name_declined_no_template"; break; case 7: error_string = "name_declined_not_authorized_for_species"; break; case 8: error_string = "name_declined_not_creature_template"; break; case 9: error_string = "name_declined_not_authorized_for_species"; break; case 10: error_string = "name_declined_number"; break; case 11: error_string = "name_declined_profane"; break; case 12: error_string = "name_declined_racially_inappropriate"; break; case 13: error_string = "name_declined_reserved"; break; case 14: error_string = "name_declined_retry"; break; case 15: error_string = "name_declined_syntax"; break; case 16: error_string = "name_declined_too_fast"; break; case 17: error_string = "name_declined_cant_create_avatar"; break; default: error_string = "name_declined_internal_error"; break; } return error_string; } uint64_t MysqlCharacterProvider::GetCharacterIdByName(const string& name) { uint64_t character_id = 0; try { auto conn = kernel_->GetDatabaseManager()->getConnection("galaxy"); auto statement = std::unique_ptr<sql::PreparedStatement>( conn->prepareStatement("SELECT id FROM object where custom_name like ? and type_id = ?;") ); statement->setString(1, name + '%'); statement->setUInt(2, swganh::object::player::Player::type); auto result_set = std::unique_ptr<sql::ResultSet>(statement->executeQuery()); if (result_set->next()) { character_id = result_set->getUInt64(1); } } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } return character_id; }<|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <crypto/ripemd160.h> #include <crypto/sha1.h> #include <crypto/sha256.h> #include <crypto/sha3.h> #include <crypto/sha512.h> #include <crypto/siphash.h> #include <hash.h> #include <random.h> #include <uint256.h> #include <string> /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000 * 1000; static void RIPEMD160(benchmark::Bench &bench) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CRIPEMD160().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA1(benchmark::Bench &bench) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA1().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA256(benchmark::Bench &bench) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA256().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA3_256_1M(benchmark::Bench &bench) { uint8_t hash[SHA3_256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { SHA3_256().Write(in).Finalize(hash); }); } static void SHA256_32b(benchmark::Bench &bench) { std::vector<uint8_t> in(32, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA256().Write(in.data(), in.size()).Finalize(in.data()); }); } static void SHA256D64_1024(benchmark::Bench &bench) { std::vector<uint8_t> in(64 * 1024, 0); bench.batch(in.size()).unit("byte").run( [&] { SHA256D64(in.data(), in.data(), 1024); }); } static void SHA512(benchmark::Bench &bench) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA512().Write(in.data(), in.size()).Finalize(hash); }); } static void SipHash_32b(benchmark::Bench &bench) { uint256 x; uint64_t k1 = 0; bench.run([&] { uint64_t hash64 = SipHashUint256(0, ++k1, x); std::memcpy(x.begin(), &hash64, sizeof(hash64)); }); } static void FastRandom_32bit(benchmark::Bench &bench) { FastRandomContext rng(true); bench.run([&] { rng.rand32(); }); } static void FastRandom_1bit(benchmark::Bench &bench) { FastRandomContext rng(true); bench.run([&] { rng.randbool(); }); } BENCHMARK(RIPEMD160); BENCHMARK(SHA1); BENCHMARK(SHA256); BENCHMARK(SHA512); BENCHMARK(SHA3_256_1M); BENCHMARK(SHA256_32b); BENCHMARK(SipHash_32b); BENCHMARK(SHA256D64_1024); BENCHMARK(FastRandom_32bit); BENCHMARK(FastRandom_1bit); <commit_msg>bench: Add Muhash benchmarks<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <crypto/muhash.h> #include <crypto/ripemd160.h> #include <crypto/sha1.h> #include <crypto/sha256.h> #include <crypto/sha3.h> #include <crypto/sha512.h> #include <crypto/siphash.h> #include <hash.h> #include <random.h> #include <uint256.h> #include <string> /* Number of bytes to hash per iteration */ static const uint64_t BUFFER_SIZE = 1000 * 1000; static void RIPEMD160(benchmark::Bench &bench) { uint8_t hash[CRIPEMD160::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CRIPEMD160().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA1(benchmark::Bench &bench) { uint8_t hash[CSHA1::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA1().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA256(benchmark::Bench &bench) { uint8_t hash[CSHA256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA256().Write(in.data(), in.size()).Finalize(hash); }); } static void SHA3_256_1M(benchmark::Bench &bench) { uint8_t hash[SHA3_256::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { SHA3_256().Write(in).Finalize(hash); }); } static void SHA256_32b(benchmark::Bench &bench) { std::vector<uint8_t> in(32, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA256().Write(in.data(), in.size()).Finalize(in.data()); }); } static void SHA256D64_1024(benchmark::Bench &bench) { std::vector<uint8_t> in(64 * 1024, 0); bench.batch(in.size()).unit("byte").run( [&] { SHA256D64(in.data(), in.data(), 1024); }); } static void SHA512(benchmark::Bench &bench) { uint8_t hash[CSHA512::OUTPUT_SIZE]; std::vector<uint8_t> in(BUFFER_SIZE, 0); bench.batch(in.size()).unit("byte").run( [&] { CSHA512().Write(in.data(), in.size()).Finalize(hash); }); } static void SipHash_32b(benchmark::Bench &bench) { uint256 x; uint64_t k1 = 0; bench.run([&] { uint64_t hash64 = SipHashUint256(0, ++k1, x); std::memcpy(x.begin(), &hash64, sizeof(hash64)); }); } static void FastRandom_32bit(benchmark::Bench &bench) { FastRandomContext rng(true); bench.run([&] { rng.rand32(); }); } static void FastRandom_1bit(benchmark::Bench &bench) { FastRandomContext rng(true); bench.run([&] { rng.randbool(); }); } static void MuHash(benchmark::Bench &bench) { MuHash3072 acc; uint8_t key[32] = {0}; int i = 0; bench.run([&] { key[0] = ++i; acc *= MuHash3072(key); }); } static void MuHashMul(benchmark::Bench &bench) { MuHash3072 acc; FastRandomContext rng(true); MuHash3072 muhash{rng.randbytes(32)}; bench.run([&] { acc *= muhash; }); } static void MuHashDiv(benchmark::Bench &bench) { MuHash3072 acc; FastRandomContext rng(true); MuHash3072 muhash{rng.randbytes(32)}; for (size_t i = 0; i < bench.epochIterations(); ++i) { acc *= muhash; } bench.run([&] { acc /= muhash; }); } static void MuHashPrecompute(benchmark::Bench &bench) { MuHash3072 acc; FastRandomContext rng(true); std::vector<uint8_t> key{rng.randbytes(32)}; bench.run([&] { MuHash3072{key}; }); } BENCHMARK(RIPEMD160); BENCHMARK(SHA1); BENCHMARK(SHA256); BENCHMARK(SHA512); BENCHMARK(SHA3_256_1M); BENCHMARK(SHA256_32b); BENCHMARK(SipHash_32b); BENCHMARK(SHA256D64_1024); BENCHMARK(FastRandom_32bit); BENCHMARK(FastRandom_1bit); BENCHMARK(MuHash); BENCHMARK(MuHashMul); BENCHMARK(MuHashDiv); BENCHMARK(MuHashPrecompute); <|endoftext|>
<commit_before>// // yas_processing_send_signal_processor.cpp // #include "yas_processing_send_signal_processor.h" #include "yas_processing_processor.h" #include "yas_processing_module.h" #include "yas_processing_channel.h" #include "yas_processing_signal_event.h" #include "yas_stl_utils.h" using namespace yas; template <typename T> processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<T> handler) { return [handler = std::move(handler)](time::range const &current_time_range, connector_map_t const &input_connectors, connector_map_t const &output_connectors, stream &stream) { if (handler) { for (auto const &connector_pair : output_connectors) { auto const &connector_key = connector_pair.first; auto const &connector = connector_pair.second; auto const &ch_idx = connector.channel_index; if (stream.has_channel(ch_idx)) { auto &channel = stream.channel(ch_idx); processing::time::range combined_time_range = current_time_range; auto predicate = [&current_time_range](auto const &pair) { time const &time = pair.first; auto const &time_range = time.get<time::range>(); if (time_range.can_combine(current_time_range)) { return true; } return false; }; auto const filtered_events = channel.filtered_events<T, signal_event>(predicate); if (filtered_events.size() > 0) { for (auto const &pair : filtered_events) { combined_time_range = *combined_time_range.combine(pair.first); } std::vector<T> vec(combined_time_range.length); for (auto const &pair : filtered_events) { auto const &time_range = pair.first; auto const length = time_range.length; auto const dst_idx = time_range.frame - combined_time_range.frame; auto *dst_ptr = &vec[dst_idx]; signal_event const signal = cast<processing::signal_event>(pair.second); signal.copy_to<T>(dst_ptr, length); } channel.erase_event_if<T, signal_event>(std::move(predicate)); handler(current_time_range, ch_idx, connector_key, &vec[current_time_range.frame - combined_time_range.frame]); channel.insert_event(time{combined_time_range}, signal_event{std::move(vec)}); return; } } else { stream.add_channel(ch_idx); } std::vector<T> vec(current_time_range.length); handler(current_time_range, ch_idx, connector_key, vec.data()); auto &channel = stream.channel(ch_idx); channel.insert_event(time{current_time_range}, signal_event{std::move(vec)}); } } }; } template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<double>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<float>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int8_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint8_t>); <commit_msg>fix send_signal_processor<commit_after>// // yas_processing_send_signal_processor.cpp // #include "yas_processing_send_signal_processor.h" #include "yas_processing_processor.h" #include "yas_processing_module.h" #include "yas_processing_channel.h" #include "yas_processing_signal_event.h" #include "yas_stl_utils.h" using namespace yas; template <typename T> processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<T> handler) { return [handler = std::move(handler)](time::range const &current_time_range, connector_map_t const &input_connectors, connector_map_t const &output_connectors, stream &stream) { if (handler) { for (auto const &connector_pair : output_connectors) { auto const &connector_key = connector_pair.first; auto const &connector = connector_pair.second; auto const &ch_idx = connector.channel_index; if (stream.has_channel(ch_idx)) { auto &channel = stream.channel(ch_idx); processing::time::range combined_time_range = current_time_range; auto predicate = [&current_time_range](auto const &pair) { if (pair.first.can_combine(current_time_range)) { return true; } return false; }; auto const filtered_events = channel.filtered_events<T, signal_event>(predicate); if (filtered_events.size() > 0) { for (auto const &pair : filtered_events) { combined_time_range = *combined_time_range.combine(pair.first); } std::vector<T> vec(combined_time_range.length); for (auto const &pair : filtered_events) { auto const &time_range = pair.first; auto const length = time_range.length; auto const dst_idx = time_range.frame - combined_time_range.frame; auto *dst_ptr = &vec[dst_idx]; signal_event const signal = cast<processing::signal_event>(pair.second); signal.copy_to<T>(dst_ptr, length); } channel.erase_event<T, signal_event>(std::move(predicate)); handler(current_time_range, ch_idx, connector_key, &vec[current_time_range.frame - combined_time_range.frame]); channel.insert_event(time{combined_time_range}, signal_event{std::move(vec)}); return; } } else { stream.add_channel(ch_idx); } std::vector<T> vec(current_time_range.length); handler(current_time_range, ch_idx, connector_key, vec.data()); auto &channel = stream.channel(ch_idx); channel.insert_event(time{current_time_range}, signal_event{std::move(vec)}); } } }; } template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<double>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<float>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<int8_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint64_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint32_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint16_t>); template processing::processor_f processing::make_send_signal_processor(processing::send_signal_process_f<uint8_t>); <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <boost/program_options.hpp> #include <iostream> #include <exception> #include <vector> #include <algorithm> #include <cstdlib> #include <set> #include <random> namespace po = boost::program_options; auto main(int argc, char * argv[]) -> int { try { po::options_description display_options{ "Program options" }; display_options.add_options() ("help", "Display help information") ("format", po::value<std::string>(), "Specify the format of the output") ; po::options_description all_options{ "All options" }; all_options.add_options() ("n", po::value<int>(), "The number of vertices") ("p", po::value<double>(), "The edge probability") ("s", po::value<int>(), "The seed") ; all_options.add(display_options); po::positional_options_description positional_options; positional_options .add("n", 1) .add("p", 1) .add("s", 1) ; po::variables_map options_vars; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), options_vars); po::notify(options_vars); /* --help? Show a message, and exit. */ if (options_vars.count("help")) { std::cout << "Usage: " << argv[0] << " [options] n p s" << std::endl; std::cout << std::endl; std::cout << display_options << std::endl; return EXIT_SUCCESS; } /* No n specified? Show a message and exit. */ if (! options_vars.count("n") || ! options_vars.count("p") || ! options_vars.count("s")) { std::cout << "Usage: " << argv[0] << " [options] n p s" << std::endl; return EXIT_FAILURE; } int n = options_vars["n"].as<int>(); double p = options_vars["p"].as<double>(); int s = options_vars["s"].as<int>(); std::mt19937 rand; rand.seed(s); std::uniform_real_distribution<double> dist(0.0, 1.0); std::function<void (int, int)> output_function; if (! options_vars.count("format") || options_vars["format"].as<std::string>() == "dimacs") { std::cout << "p edge " << n << " 0" << std::endl; output_function = [] (int e, int f) { std::cout << "e " << e << " " << f << std::endl; }; } else if (options_vars["format"].as<std::string>() == "pairs0") { std::cout << n << " 0" << std::endl; output_function = [] (int e, int f) { std::cout << e - 1 << " " << f - 1 << std::endl; }; } else if (options_vars["format"].as<std::string>() == "lad") { std::cout << n << std::endl; } else { std::cout << "Unknown format (try 'dimacs' or 'pairs0')" << std::endl; return EXIT_FAILURE; } if (options_vars["format"].as<std::string>() == "lad") { std::vector<std::vector<int> > adj = std::vector<std::vector<int> >(n, std::vector<int>(n, 0)); for (int e = 0 ; e < n ; ++e) for (int f = e + 1 ; f < n ; ++f) if (dist(rand) <= p) adj[e][f] = adj[f][e] = 1; for (int e = 0 ; e < n ; ++e) { int k = std::count(adj[e].begin(), adj[e].end(), 1); std::cout << k; for (int f = 0 ; f < n ; ++f) { if (adj[e][f]) std::cout << " " << f; } std::cout << std::endl; } } else { for (int e = 1 ; e <= n ; ++e) { for (int f = e + 1 ; f <= n ; ++f) { if (dist(rand) <= p) output_function(e, f); } } } return EXIT_SUCCESS; } catch (const po::error & e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Try " << argv[0] << " --help" << std::endl; return EXIT_FAILURE; } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } } <commit_msg>Don't barf with no --format<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <boost/program_options.hpp> #include <iostream> #include <exception> #include <vector> #include <algorithm> #include <cstdlib> #include <set> #include <random> namespace po = boost::program_options; auto main(int argc, char * argv[]) -> int { try { po::options_description display_options{ "Program options" }; display_options.add_options() ("help", "Display help information") ("format", po::value<std::string>(), "Specify the format of the output") ; po::options_description all_options{ "All options" }; all_options.add_options() ("n", po::value<int>(), "The number of vertices") ("p", po::value<double>(), "The edge probability") ("s", po::value<int>(), "The seed") ; all_options.add(display_options); po::positional_options_description positional_options; positional_options .add("n", 1) .add("p", 1) .add("s", 1) ; po::variables_map options_vars; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), options_vars); po::notify(options_vars); /* --help? Show a message, and exit. */ if (options_vars.count("help")) { std::cout << "Usage: " << argv[0] << " [options] n p s" << std::endl; std::cout << std::endl; std::cout << display_options << std::endl; return EXIT_SUCCESS; } /* No n specified? Show a message and exit. */ if (! options_vars.count("n") || ! options_vars.count("p") || ! options_vars.count("s")) { std::cout << "Usage: " << argv[0] << " [options] n p s" << std::endl; return EXIT_FAILURE; } int n = options_vars["n"].as<int>(); double p = options_vars["p"].as<double>(); int s = options_vars["s"].as<int>(); std::mt19937 rand; rand.seed(s); std::uniform_real_distribution<double> dist(0.0, 1.0); std::function<void (int, int)> output_function; if (! options_vars.count("format") || options_vars["format"].as<std::string>() == "dimacs") { std::cout << "p edge " << n << " 0" << std::endl; output_function = [] (int e, int f) { std::cout << "e " << e << " " << f << std::endl; }; } else if (options_vars["format"].as<std::string>() == "pairs0") { std::cout << n << " 0" << std::endl; output_function = [] (int e, int f) { std::cout << e - 1 << " " << f - 1 << std::endl; }; } else if (options_vars["format"].as<std::string>() == "lad") { std::cout << n << std::endl; } else { std::cout << "Unknown format (try 'dimacs' or 'pairs0')" << std::endl; return EXIT_FAILURE; } if (options_vars.count("format") && options_vars["format"].as<std::string>() == "lad") { std::vector<std::vector<int> > adj = std::vector<std::vector<int> >(n, std::vector<int>(n, 0)); for (int e = 0 ; e < n ; ++e) for (int f = e + 1 ; f < n ; ++f) if (dist(rand) <= p) adj[e][f] = adj[f][e] = 1; for (int e = 0 ; e < n ; ++e) { int k = std::count(adj[e].begin(), adj[e].end(), 1); std::cout << k; for (int f = 0 ; f < n ; ++f) { if (adj[e][f]) std::cout << " " << f; } std::cout << std::endl; } } else { for (int e = 1 ; e <= n ; ++e) { for (int f = e + 1 ; f <= n ; ++f) { if (dist(rand) <= p) output_function(e, f); } } } return EXIT_SUCCESS; } catch (const po::error & e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Try " << argv[0] << " --help" << std::endl; return EXIT_FAILURE; } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#include "ebc/BitcodeRetriever.h" #include "ebc/BitcodeArchive.h" #include "ebc/BitcodeContainer.h" #include "ebc/EbcError.h" #include "llvm/ADT/Triple.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/MachO.h" #include "llvm/Object/MachOUniversal.h" #include <algorithm> #include <memory> #include <string> using namespace llvm; using namespace llvm::object; namespace ebc { /// Strip path from file name. static std::string StripFileName(std::string fileName) { auto pos = fileName.rfind('/'); return pos == std::string::npos ? fileName : fileName.substr(pos + 1); } BitcodeRetriever::BitcodeRetriever(std::string objectPath) : _objectPath(std::move(objectPath)) {} std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers() { auto binaryOrErr = createBinary(_objectPath); if (!binaryOrErr) { throw EbcError("Invalid binary"); } auto &binary = *binaryOrErr.get().getBinary(); return GetBitcodeContainers(binary); } std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers( const llvm::object::Binary &binary) { auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>(); if (const auto *universalBinary = dyn_cast<MachOUniversalBinary>(&binary)) { // Iterate over all objects (i.e. architectures): for (auto object : universalBinary->objects()) { if (auto machOObject = object.getAsObjectFile()) { auto container = GetBitcodeContainerFromMachO(machOObject->get()); if (container) { bitcodeContainers.push_back(std::move(container)); } } else if (const auto archive = object.getAsArchive()) { auto containers = GetBitcodeContainersFromArchive(*(archive.get())); // We have to move all containers so we can continue with the next architecture. bitcodeContainers.reserve(bitcodeContainers.size() + containers.size()); std::move(std::begin(containers), std::end(containers), std::back_inserter(bitcodeContainers)); } else { throw EbcError("Unrecognized MachO universal binary"); } } } else if (const auto machOObjectFile = dyn_cast<MachOObjectFile>(&binary)) { auto container = GetBitcodeContainerFromMachO(machOObjectFile); if (container) { bitcodeContainers.push_back(std::move(container)); } } else if (const auto object = dyn_cast<ObjectFile>(&binary)) { auto container = GetBitcodeContainerFromObject(object); if (container) { bitcodeContainers.push_back(std::move(container)); } } else if (const auto archive = dyn_cast<Archive>(&binary)) { // We can return early to prevent moving all containers in the vector. return GetBitcodeContainersFromArchive(*archive); } else { throw EbcError("Unsupported binary"); } return bitcodeContainers; } std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainersFromArchive( const Archive &archive) { auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>(); for (const auto &child : archive.children()) { auto childOrErr = child->getAsBinary(); if (childOrErr) { auto containers = GetBitcodeContainers(*(childOrErr.get())); bitcodeContainers.reserve(bitcodeContainers.size() + containers.size()); std::move(std::begin(containers), std::end(containers), std::back_inserter(bitcodeContainers)); } } return bitcodeContainers; } std::unique_ptr<BitcodeContainer> BitcodeRetriever::GetBitcodeContainerFromObject( const llvm::object::ObjectFile *objectFile) { BitcodeContainer *bitcodeContainer = nullptr; std::vector<std::string> commands; for (const SectionRef &section : objectFile->sections()) { StringRef sectName; section.getName(sectName); if (sectName == ".llvmbc") { auto data = GetSectionData(section); bitcodeContainer = new BitcodeContainer(data.first, data.second); } else if (sectName == ".llvmcmd") { commands = GetCommands(section); } } if (bitcodeContainer == nullptr) { throw EbcError("No bitcode section in " + objectFile->getFileName().str()); } // Set commands bitcodeContainer->SetCommands(commands); // Set binary metadata bitcodeContainer->GetBinaryMetadata().SetFileName(StripFileName(objectFile->getFileName())); bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName()); bitcodeContainer->GetBinaryMetadata().SetArch( llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()))); return std::unique_ptr<BitcodeContainer>(bitcodeContainer); } std::unique_ptr<BitcodeContainer> BitcodeRetriever::GetBitcodeContainerFromMachO( const llvm::object::MachOObjectFile *objectFile) { BitcodeContainer *bitcodeContainer = nullptr; const std::string name = objectFile->getFileFormatName().str(); std::vector<std::string> commands; for (const SectionRef &section : objectFile->sections()) { // Get section name DataRefImpl dataRef = section.getRawDataRefImpl(); StringRef segName = objectFile->getSectionFinalSegmentName(dataRef); if (segName == "__LLVM") { StringRef sectName; section.getName(sectName); if (sectName == "__bundle") { // Embedded bitcode in universal binary. auto data = GetSectionData(section); bitcodeContainer = new BitcodeArchive(data.first, data.second); } else if (sectName == "__bitcode") { // Embedded bitcode in single MachO object. auto data = GetSectionData(section); bitcodeContainer = new BitcodeContainer(data.first, data.second); } else if (sectName == "__cmd" || sectName == "__cmdline") { commands = GetCommands(section); } } } if (bitcodeContainer == nullptr) { throw EbcError("No bitcode section in " + objectFile->getFileName().str()); } // Set commands bitcodeContainer->SetCommands(commands); // Set binary metadata bitcodeContainer->GetBinaryMetadata().SetFileName(StripFileName(objectFile->getFileName())); bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName()); bitcodeContainer->GetBinaryMetadata().SetArch( llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()))); bitcodeContainer->GetBinaryMetadata().SetUuid(objectFile->getUuid().data()); return std::unique_ptr<BitcodeContainer>(bitcodeContainer); } std::pair<const char *, std::uint32_t> BitcodeRetriever::GetSectionData(const llvm::object::SectionRef &section) { StringRef bytesStr; section.getContents(bytesStr); const char *sect = reinterpret_cast<const char *>(bytesStr.data()); uint32_t sect_size = bytesStr.size(); return std::make_pair(sect, sect_size); } std::vector<std::string> BitcodeRetriever::GetCommands(const llvm::object::SectionRef &section) { auto data = GetSectionData(section); const char *p = data.first; const char *end = data.first + data.second; // Create list of strings from commands separated by null bytes. std::vector<std::string> cmds; do { // Creating a string from p consumes data until next null byte. cmds.push_back(std::string(p)); // Continue after the null byte. p += cmds.back().size() + 1; } while (p < end); return cmds; } } // namespace ebc <commit_msg>Another issue with 3.9 fixed<commit_after>#include "ebc/BitcodeRetriever.h" #include "ebc/BitcodeArchive.h" #include "ebc/BitcodeContainer.h" #include "ebc/EbcError.h" #include "llvm/ADT/Triple.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/MachO.h" #include "llvm/Object/MachOUniversal.h" #include <algorithm> #include <memory> #include <string> using namespace llvm; using namespace llvm::object; namespace ebc { /// Strip path from file name. static std::string StripFileName(std::string fileName) { auto pos = fileName.rfind('/'); return pos == std::string::npos ? fileName : fileName.substr(pos + 1); } BitcodeRetriever::BitcodeRetriever(std::string objectPath) : _objectPath(std::move(objectPath)) {} std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers() { auto binaryOrErr = createBinary(_objectPath); if (!binaryOrErr) { throw EbcError("Invalid binary"); } auto &binary = *binaryOrErr.get().getBinary(); return GetBitcodeContainers(binary); } std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers( const llvm::object::Binary &binary) { auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>(); if (const auto *universalBinary = dyn_cast<MachOUniversalBinary>(&binary)) { // Iterate over all objects (i.e. architectures): for (auto object : universalBinary->objects()) { if (const auto archive = object.getAsArchive()) { auto containers = GetBitcodeContainersFromArchive(*(archive.get())); // We have to move all containers so we can continue with the next architecture. bitcodeContainers.reserve(bitcodeContainers.size() + containers.size()); std::move(std::begin(containers), std::end(containers), std::back_inserter(bitcodeContainers)); } else if (auto machOObject = object.getAsObjectFile()) { auto container = GetBitcodeContainerFromMachO(machOObject->get()); if (container) { bitcodeContainers.push_back(std::move(container)); } } else { throw EbcError("Unrecognized MachO universal binary"); } } } else if (const auto machOObjectFile = dyn_cast<MachOObjectFile>(&binary)) { auto container = GetBitcodeContainerFromMachO(machOObjectFile); if (container) { bitcodeContainers.push_back(std::move(container)); } } else if (const auto object = dyn_cast<ObjectFile>(&binary)) { auto container = GetBitcodeContainerFromObject(object); if (container) { bitcodeContainers.push_back(std::move(container)); } } else if (const auto archive = dyn_cast<Archive>(&binary)) { // We can return early to prevent moving all containers in the vector. return GetBitcodeContainersFromArchive(*archive); } else { throw EbcError("Unsupported binary"); } return bitcodeContainers; } std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainersFromArchive( const Archive &archive) { auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>(); for (const auto &child : archive.children()) { auto childOrErr = child->getAsBinary(); if (childOrErr) { auto containers = GetBitcodeContainers(*(childOrErr.get())); bitcodeContainers.reserve(bitcodeContainers.size() + containers.size()); std::move(std::begin(containers), std::end(containers), std::back_inserter(bitcodeContainers)); } } return bitcodeContainers; } std::unique_ptr<BitcodeContainer> BitcodeRetriever::GetBitcodeContainerFromObject( const llvm::object::ObjectFile *objectFile) { BitcodeContainer *bitcodeContainer = nullptr; std::vector<std::string> commands; for (const SectionRef &section : objectFile->sections()) { StringRef sectName; section.getName(sectName); if (sectName == ".llvmbc") { auto data = GetSectionData(section); bitcodeContainer = new BitcodeContainer(data.first, data.second); } else if (sectName == ".llvmcmd") { commands = GetCommands(section); } } if (bitcodeContainer == nullptr) { throw EbcError("No bitcode section in " + objectFile->getFileName().str()); } // Set commands bitcodeContainer->SetCommands(commands); // Set binary metadata bitcodeContainer->GetBinaryMetadata().SetFileName(StripFileName(objectFile->getFileName())); bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName()); bitcodeContainer->GetBinaryMetadata().SetArch( llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()))); return std::unique_ptr<BitcodeContainer>(bitcodeContainer); } std::unique_ptr<BitcodeContainer> BitcodeRetriever::GetBitcodeContainerFromMachO( const llvm::object::MachOObjectFile *objectFile) { BitcodeContainer *bitcodeContainer = nullptr; const std::string name = objectFile->getFileFormatName().str(); std::vector<std::string> commands; for (const SectionRef &section : objectFile->sections()) { // Get section name DataRefImpl dataRef = section.getRawDataRefImpl(); StringRef segName = objectFile->getSectionFinalSegmentName(dataRef); if (segName == "__LLVM") { StringRef sectName; section.getName(sectName); if (sectName == "__bundle") { // Embedded bitcode in universal binary. auto data = GetSectionData(section); bitcodeContainer = new BitcodeArchive(data.first, data.second); } else if (sectName == "__bitcode") { // Embedded bitcode in single MachO object. auto data = GetSectionData(section); bitcodeContainer = new BitcodeContainer(data.first, data.second); } else if (sectName == "__cmd" || sectName == "__cmdline") { commands = GetCommands(section); } } } if (bitcodeContainer == nullptr) { throw EbcError("No bitcode section in " + objectFile->getFileName().str()); } // Set commands bitcodeContainer->SetCommands(commands); // Set binary metadata bitcodeContainer->GetBinaryMetadata().SetFileName(StripFileName(objectFile->getFileName())); bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName()); bitcodeContainer->GetBinaryMetadata().SetArch( llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()))); bitcodeContainer->GetBinaryMetadata().SetUuid(objectFile->getUuid().data()); return std::unique_ptr<BitcodeContainer>(bitcodeContainer); } std::pair<const char *, std::uint32_t> BitcodeRetriever::GetSectionData(const llvm::object::SectionRef &section) { StringRef bytesStr; section.getContents(bytesStr); const char *sect = reinterpret_cast<const char *>(bytesStr.data()); uint32_t sect_size = bytesStr.size(); return std::make_pair(sect, sect_size); } std::vector<std::string> BitcodeRetriever::GetCommands(const llvm::object::SectionRef &section) { auto data = GetSectionData(section); const char *p = data.first; const char *end = data.first + data.second; // Create list of strings from commands separated by null bytes. std::vector<std::string> cmds; do { // Creating a string from p consumes data until next null byte. cmds.push_back(std::string(p)); // Continue after the null byte. p += cmds.back().size() + 1; } while (p < end); return cmds; } } // namespace ebc <|endoftext|>
<commit_before>// -*- coding: utf-8 -*- // Copyright (C) 2012-2014 MUJIN Inc. <rosen.diankov@mujin.co.jp> // // 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 "common.h" #include "controllerclientimpl.h" #include "binpickingtaskzmq.h" #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include "mujincontrollerclient/mujinzmq.h" #include <algorithm> // find #include "logging.h" MUJIN_LOGGER("mujin.controllerclientcpp.binpickingtask.zmq"); namespace { void ConvertTimestampToFloat(const std::string& in, std::stringstream& outss) { const std::size_t len = in.size(); std::size_t processed = 0; while (processed != std::string::npos && processed < len) { const std::size_t deltabegin = in.substr(processed, len).find("\"timestamp\":"); if (deltabegin == std::string::npos) { outss << in.substr(processed, len); return; } const std::size_t timestampbegin = processed + deltabegin; const std::size_t comma = in.substr(timestampbegin, len).find(","); const std::size_t closingCurly = in.substr(timestampbegin, len).find("}"); if (comma == std::string::npos && closingCurly == std::string::npos) { throw mujinclient::MujinException(boost::str(boost::format("error while converting timestamp value format for %s")%in), mujinclient::MEC_Failed); } const std::size_t timestampend = timestampbegin + (comma < closingCurly ? comma : closingCurly); if (timestampend == std::string::npos) { throw mujinclient::MujinException(boost::str(boost::format("error while converting timestamp value format for %s")%in), mujinclient::MEC_Failed); } const std::size_t period = in.substr(timestampbegin, len).find("."); if (period == std::string::npos || timestampbegin + period > timestampend) { // no comma, assume this is in integet format. so add period to make it a float format. outss << in.substr(processed, timestampend - processed) << "."; } else { // already floating format. keep it that way outss << in.substr(processed, timestampend - processed); } processed = timestampend; } } } namespace mujinclient { using namespace utils; class ZmqMujinControllerClient : public mujinzmq::ZmqClient { public: ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port); virtual ~ZmqMujinControllerClient(); }; ZmqMujinControllerClient::ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port) : ZmqClient(host, port) { _InitializeSocket(context); } ZmqMujinControllerClient::~ZmqMujinControllerClient() { // _DestroySocket() is called in ~ZmqClient() } BinPickingTaskZmqResource::BinPickingTaskZmqResource(ControllerClientPtr c, const std::string& pk, const std::string& scenepk, const std::string& tasktype) : BinPickingTaskResource(c, pk, scenepk, tasktype) { } BinPickingTaskZmqResource::~BinPickingTaskZmqResource() { } void BinPickingTaskZmqResource::Initialize(const std::string& defaultTaskParameters, const int zmqPort, const int heartbeatPort, boost::shared_ptr<zmq::context_t> zmqcontext, const bool initializezmq, const double reinitializetimeout, const double timeout, const std::string& userinfo, const std::string& slaverequestid) { BinPickingTaskResource::Initialize(defaultTaskParameters, zmqPort, heartbeatPort, zmqcontext, initializezmq, reinitializetimeout, timeout, userinfo, slaverequestid); if (initializezmq) { InitializeZMQ(reinitializetimeout, timeout); } _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } if (!_pHeartbeatMonitorThread) { _bShutdownHeartbeatMonitor = false; if (reinitializetimeout > 0 ) { _pHeartbeatMonitorThread.reset(new boost::thread(boost::bind(&BinPickingTaskZmqResource::_HeartbeatMonitorThread, this, reinitializetimeout, timeout))); } } } boost::property_tree::ptree BinPickingTaskZmqResource::ExecuteCommand(const std::string& taskparameters, const double timeout /* [sec] */, const bool getresult) { if (!_bIsInitialized) { throw MujinException("BinPicking task is not initialized, please call Initialzie() first.", MEC_Failed); } if (!_zmqmujincontrollerclient) { MUJIN_LOG_ERROR("zmqcontrollerclient is not initialized! initialize"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); } std::stringstream ss; ss << "{\"fnname\": \""; if (_tasktype == "binpicking") { ss << "binpicking."; } ss << "RunCommand\", \"taskparams\": {\"tasktype\": \"" << _tasktype << "\", "; ss << "\"taskparameters\": " << taskparameters << ", "; ss << "\"sceneparams\": " << _sceneparams_json << "}, "; ss << "\"userinfo\": " << _userinfo_json; if (_slaverequestid != "") { ss << ", " << GetJsonString("slaverequestid", _slaverequestid); } ss << "}"; std::string command = ss.str(); // std::cout << "Sending " << command << " from " << __func__ << std::endl; //std::string task = "{\"tasktype\": \"binpicking\", \"taskparameters\": " + command + "}"; boost::property_tree::ptree pt; if (getresult) { std::stringstream result_ss; try{ result_ss << _zmqmujincontrollerclient->Call(command, timeout); } catch (const MujinException& e) { MUJIN_LOG_ERROR(e.what()); if (e.GetCode() == MEC_ZMQNoResponse) { MUJIN_LOG_INFO("reinitializing zmq connection with the slave"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } } } try { // temporary fix until we move on to rapid json std::stringstream result_ss_float_timestamp; ConvertTimestampToFloat(result_ss.str(), result_ss_float_timestamp); std::cout << result_ss.str() << std::endl << result_ss_float_timestamp.str() << std::endl; boost::property_tree::read_json(result_ss_float_timestamp, pt); boost::property_tree::ptree::const_assoc_iterator iterror = pt.find("error"); if( iterror != pt.not_found() ) { boost::optional<std::string> erroroptional = iterror->second.get_optional<std::string>("errorcode"); boost::optional<std::string> descriptionoptional = iterror->second.get_optional<std::string>("description"); if (!!erroroptional && erroroptional.get().size() > 0 ) { std::string serror; if (!!descriptionoptional && descriptionoptional.get().size() > 0 ) { serror = descriptionoptional.get(); } else { serror = erroroptional.get(); } if( serror.size() > 1000 ) { MUJIN_LOG_ERROR(str(boost::format("truncated original error message from %d")%serror.size())); serror = serror.substr(0,1000); } throw MujinException(str(boost::format("Error when calling binpicking.RunCommand: %s")%serror), MEC_BinPickingError); } } } catch (boost::property_tree::ptree_error& e) { throw MujinException(boost::str(boost::format("Failed to parse json which is received from mujin controller: \nreceived message: %s \nerror message: %s")%result_ss.str()%e.what()), MEC_Failed); } } else { try{ _zmqmujincontrollerclient->Call(command, timeout); // TODO since not getting response, internal zmq will be in a bad state, have to recreate } catch (const MujinException& e) { MUJIN_LOG_ERROR(e.what()); if (e.GetCode() == MEC_ZMQNoResponse) { MUJIN_LOG_INFO("reinitializing zmq connection with the slave"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } } } } return pt; } void BinPickingTaskZmqResource::InitializeZMQ(const double reinitializetimeout, const double timeout) { } void BinPickingTaskZmqResource::_HeartbeatMonitorThread(const double reinitializetimeout, const double commandtimeout) { boost::shared_ptr<zmq::socket_t> socket; boost::property_tree::ptree pt; BinPickingTaskResource::ResultHeartBeat heartbeat; heartbeat._slaverequestid = _slaverequestid; while (!_bShutdownHeartbeatMonitor) { if (!!socket) { socket->close(); socket.reset(); } socket.reset(new zmq::socket_t((*_zmqcontext.get()),ZMQ_SUB)); std::stringstream ss; ss << _heartbeatPort; socket->connect (("tcp://"+ _mujinControllerIp+":"+ss.str()).c_str()); socket->setsockopt(ZMQ_SUBSCRIBE, "", 0); zmq::pollitem_t pollitem; memset(&pollitem, 0, sizeof(zmq::pollitem_t)); pollitem.socket = socket->operator void*(); pollitem.events = ZMQ_POLLIN; unsigned long long lastheartbeat = GetMilliTime(); while (!_bShutdownHeartbeatMonitor && (GetMilliTime() - lastheartbeat) / 1000.0f < reinitializetimeout) { zmq::poll(&pollitem,1, 50); // wait 50 ms for message if (pollitem.revents & ZMQ_POLLIN) { zmq::message_t reply; socket->recv(&reply); std::string replystring((char *) reply.data (), (size_t) reply.size()); #ifdef _WIN32 // sometimes buffer can container \n or \\, which windows boost property_tree does not like std::string newbuffer; std::vector< std::pair<std::string, std::string> > serachpairs(1); serachpairs[0].first = "\\"; serachpairs[0].second = ""; SearchAndReplace(newbuffer, replystring, serachpairs); std::stringstream replystring_ss(newbuffer); #else std::stringstream replystring_ss(replystring); #endif try{ boost::property_tree::read_json(replystring_ss, pt); } catch (std::exception const &e) { MUJIN_LOG_ERROR("HeartBeat reply is not JSON"); MUJIN_LOG_ERROR(e.what()); continue; } heartbeat.Parse(pt); { boost::mutex::scoped_lock lock(_mutexTaskState); _taskstate = heartbeat.taskstate; } //BINPICKING_LOG_ERROR(replystring); if (heartbeat.status != std::string("lost") && heartbeat.status.size() > 1) { lastheartbeat = GetMilliTime(); } } } if (!_bShutdownHeartbeatMonitor) { std::stringstream ss; ss << (double)((GetMilliTime() - lastheartbeat)/1000.0f) << " seconds passed since last heartbeat signal, re-intializing ZMQ server."; MUJIN_LOG_INFO(ss.str()); } } } } // end namespace mujinclient <commit_msg>windows fix<commit_after>// -*- coding: utf-8 -*- // Copyright (C) 2012-2014 MUJIN Inc. <rosen.diankov@mujin.co.jp> // // 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 "common.h" #include "controllerclientimpl.h" #include "binpickingtaskzmq.h" #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include "mujincontrollerclient/mujinzmq.h" #include <algorithm> // find #include "logging.h" MUJIN_LOGGER("mujin.controllerclientcpp.binpickingtask.zmq"); namespace { void ConvertTimestampToFloat(const std::string& in, std::stringstream& outss) { const std::size_t len = in.size(); std::size_t processed = 0; while (processed != std::string::npos && processed < len) { const std::size_t deltabegin = in.substr(processed, len).find("\"timestamp\":"); if (deltabegin == std::string::npos) { outss << in.substr(processed, len); return; } const std::size_t timestampbegin = processed + deltabegin; const std::size_t comma = in.substr(timestampbegin, len).find(","); const std::size_t closingCurly = in.substr(timestampbegin, len).find("}"); if (comma == std::string::npos && closingCurly == std::string::npos) { throw mujinclient::MujinException(boost::str(boost::format("error while converting timestamp value format for %s")%in), mujinclient::MEC_Failed); } const std::size_t timestampend = timestampbegin + (comma < closingCurly ? comma : closingCurly); if (timestampend == std::string::npos) { throw mujinclient::MujinException(boost::str(boost::format("error while converting timestamp value format for %s")%in), mujinclient::MEC_Failed); } const std::size_t period = in.substr(timestampbegin, len).find("."); if (period == std::string::npos || timestampbegin + period > timestampend) { // no comma, assume this is in integet format. so add period to make it a float format. outss << in.substr(processed, timestampend - processed) << "."; } else { // already floating format. keep it that way outss << in.substr(processed, timestampend - processed); } processed = timestampend; } } } namespace mujinclient { using namespace utils; class ZmqMujinControllerClient : public mujinzmq::ZmqClient { public: ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port); virtual ~ZmqMujinControllerClient(); }; ZmqMujinControllerClient::ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port) : ZmqClient(host, port) { _InitializeSocket(context); } ZmqMujinControllerClient::~ZmqMujinControllerClient() { // _DestroySocket() is called in ~ZmqClient() } BinPickingTaskZmqResource::BinPickingTaskZmqResource(ControllerClientPtr c, const std::string& pk, const std::string& scenepk, const std::string& tasktype) : BinPickingTaskResource(c, pk, scenepk, tasktype) { } BinPickingTaskZmqResource::~BinPickingTaskZmqResource() { } void BinPickingTaskZmqResource::Initialize(const std::string& defaultTaskParameters, const int zmqPort, const int heartbeatPort, boost::shared_ptr<zmq::context_t> zmqcontext, const bool initializezmq, const double reinitializetimeout, const double timeout, const std::string& userinfo, const std::string& slaverequestid) { BinPickingTaskResource::Initialize(defaultTaskParameters, zmqPort, heartbeatPort, zmqcontext, initializezmq, reinitializetimeout, timeout, userinfo, slaverequestid); if (initializezmq) { InitializeZMQ(reinitializetimeout, timeout); } _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } if (!_pHeartbeatMonitorThread) { _bShutdownHeartbeatMonitor = false; if (reinitializetimeout > 0 ) { _pHeartbeatMonitorThread.reset(new boost::thread(boost::bind(&BinPickingTaskZmqResource::_HeartbeatMonitorThread, this, reinitializetimeout, timeout))); } } } boost::property_tree::ptree BinPickingTaskZmqResource::ExecuteCommand(const std::string& taskparameters, const double timeout /* [sec] */, const bool getresult) { if (!_bIsInitialized) { throw MujinException("BinPicking task is not initialized, please call Initialzie() first.", MEC_Failed); } if (!_zmqmujincontrollerclient) { MUJIN_LOG_ERROR("zmqcontrollerclient is not initialized! initialize"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); } std::stringstream ss; ss << "{\"fnname\": \""; if (_tasktype == "binpicking") { ss << "binpicking."; } ss << "RunCommand\", \"taskparams\": {\"tasktype\": \"" << _tasktype << "\", "; ss << "\"taskparameters\": " << taskparameters << ", "; ss << "\"sceneparams\": " << _sceneparams_json << "}, "; ss << "\"userinfo\": " << _userinfo_json; if (_slaverequestid != "") { ss << ", " << GetJsonString("slaverequestid", _slaverequestid); } ss << "}"; std::string command = ss.str(); // std::cout << "Sending " << command << " from " << __func__ << std::endl; //std::string task = "{\"tasktype\": \"binpicking\", \"taskparameters\": " + command + "}"; boost::property_tree::ptree pt; if (getresult) { std::stringstream result_ss; try{ result_ss << _zmqmujincontrollerclient->Call(command, timeout); } catch (const MujinException& e) { MUJIN_LOG_ERROR(e.what()); if (e.GetCode() == MEC_ZMQNoResponse) { MUJIN_LOG_INFO("reinitializing zmq connection with the slave"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } } } try { // temporary fix until we move on to rapid json std::stringstream result_ss_float_timestamp; ConvertTimestampToFloat(result_ss.str(), result_ss_float_timestamp); #ifdef _WIN32 // sometimes buffer can container \n or \\, which windows boost property_tree does not like std::string newbuffer; std::vector< std::pair<std::string, std::string> > serachpairs(2); serachpairs[0].first = "\n"; serachpairs[0].second = ""; serachpairs[1].first = "\\"; serachpairs[1].second = ""; SearchAndReplace(newbuffer, result_ss_float_timestamp.str(), serachpairs); std::stringstream newss(newbuffer); boost::property_tree::read_json(newss, pt); #else boost::property_tree::read_json(result_ss_float_timestamp, pt); #endif boost::property_tree::ptree::const_assoc_iterator iterror = pt.find("error"); if( iterror != pt.not_found() ) { boost::optional<std::string> erroroptional = iterror->second.get_optional<std::string>("errorcode"); boost::optional<std::string> descriptionoptional = iterror->second.get_optional<std::string>("description"); if (!!erroroptional && erroroptional.get().size() > 0 ) { std::string serror; if (!!descriptionoptional && descriptionoptional.get().size() > 0 ) { serror = descriptionoptional.get(); } else { serror = erroroptional.get(); } if( serror.size() > 1000 ) { MUJIN_LOG_ERROR(str(boost::format("truncated original error message from %d")%serror.size())); serror = serror.substr(0,1000); } throw MujinException(str(boost::format("Error when calling binpicking.RunCommand: %s")%serror), MEC_BinPickingError); } } } catch (boost::property_tree::ptree_error& e) { throw MujinException(boost::str(boost::format("Failed to parse json which is received from mujin controller: \nreceived message: %s \nerror message: %s")%result_ss.str()%e.what()), MEC_Failed); } } else { try{ _zmqmujincontrollerclient->Call(command, timeout); // TODO since not getting response, internal zmq will be in a bad state, have to recreate } catch (const MujinException& e) { MUJIN_LOG_ERROR(e.what()); if (e.GetCode() == MEC_ZMQNoResponse) { MUJIN_LOG_INFO("reinitializing zmq connection with the slave"); _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort)); if (!_zmqmujincontrollerclient) { throw MujinException(boost::str(boost::format("Failed to establish ZMQ connection to mujin controller at %s:%d")%_mujinControllerIp%_zmqPort), MEC_Failed); } } } } return pt; } void BinPickingTaskZmqResource::InitializeZMQ(const double reinitializetimeout, const double timeout) { } void BinPickingTaskZmqResource::_HeartbeatMonitorThread(const double reinitializetimeout, const double commandtimeout) { boost::shared_ptr<zmq::socket_t> socket; boost::property_tree::ptree pt; BinPickingTaskResource::ResultHeartBeat heartbeat; heartbeat._slaverequestid = _slaverequestid; while (!_bShutdownHeartbeatMonitor) { if (!!socket) { socket->close(); socket.reset(); } socket.reset(new zmq::socket_t((*_zmqcontext.get()),ZMQ_SUB)); std::stringstream ss; ss << _heartbeatPort; socket->connect (("tcp://"+ _mujinControllerIp+":"+ss.str()).c_str()); socket->setsockopt(ZMQ_SUBSCRIBE, "", 0); zmq::pollitem_t pollitem; memset(&pollitem, 0, sizeof(zmq::pollitem_t)); pollitem.socket = socket->operator void*(); pollitem.events = ZMQ_POLLIN; unsigned long long lastheartbeat = GetMilliTime(); while (!_bShutdownHeartbeatMonitor && (GetMilliTime() - lastheartbeat) / 1000.0f < reinitializetimeout) { zmq::poll(&pollitem,1, 50); // wait 50 ms for message if (pollitem.revents & ZMQ_POLLIN) { zmq::message_t reply; socket->recv(&reply); std::string replystring((char *) reply.data (), (size_t) reply.size()); #ifdef _WIN32 // sometimes buffer can container \n or \\, which windows boost property_tree does not like std::string newbuffer; std::vector< std::pair<std::string, std::string> > serachpairs(1); serachpairs[0].first = "\\"; serachpairs[0].second = ""; SearchAndReplace(newbuffer, replystring, serachpairs); std::stringstream replystring_ss(newbuffer); #else std::stringstream replystring_ss(replystring); #endif try{ boost::property_tree::read_json(replystring_ss, pt); } catch (std::exception const &e) { MUJIN_LOG_ERROR("HeartBeat reply is not JSON"); MUJIN_LOG_ERROR(e.what()); continue; } heartbeat.Parse(pt); { boost::mutex::scoped_lock lock(_mutexTaskState); _taskstate = heartbeat.taskstate; } //BINPICKING_LOG_ERROR(replystring); if (heartbeat.status != std::string("lost") && heartbeat.status.size() > 1) { lastheartbeat = GetMilliTime(); } } } if (!_bShutdownHeartbeatMonitor) { std::stringstream ss; ss << (double)((GetMilliTime() - lastheartbeat)/1000.0f) << " seconds passed since last heartbeat signal, re-intializing ZMQ server."; MUJIN_LOG_INFO(ss.str()); } } } } // end namespace mujinclient <|endoftext|>
<commit_before>/* * This file is part of qasmtools. * * Copyright (c) 2019 - 2021 softwareQ Inc. All rights reserved. * * MIT License * * 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. * * Adapted from Bruno Schmitt's Tweedledee library */ /** * \file qasmtools/parser/preprocessor.hpp * \brief Manages includes for OpenQASM parsing */ #pragma once #include "lexer.hpp" #include <fstream> #include <sstream> #include <vector> namespace qasmtools { namespace parser { #if USE_OPENQASM2_SPECS /** * \brief OpenQASM 2.0 standard library (qelib1.inc) as a string constant */ static const std::string std_include = "gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }\n" "gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }\n" "gate u1(lambda) q { U(0,0,lambda) q; }\n" "gate cx c,t { CX c,t; }\n" "gate id a { U(0,0,0) a; }\n" "gate u0(gamma) q { U(0,0,0) q; }\n" "gate x a { u3(pi,0,pi) a; }\n" "gate y a { u3(pi,pi/2,pi/2) a; }\n" "gate z a { u1(pi) a; }\n" "gate h a { u2(0,pi) a; }\n" "gate s a { u1(pi/2) a; }\n" "gate sdg a { u1(-pi/2) a; }\n" "gate t a { u1(pi/4) a; }\n" "gate tdg a { u1(-pi/4) a; }\n" "gate rx(theta) a { u3(theta, -pi/2,pi/2) a; }\n" "gate ry(theta) a { u3(theta,0,0) a; }\n" "gate rz(phi) a { u1(phi) a; }\n" "gate cz a,b { h b; cx a,b; h b; }\n" "gate cy a,b { sdg b; cx a,b; s b; }\n" "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n" "gate ch a,b { h b; sdg b;cx a,b;h b; t b;cx a,b;t b; h b; s b; x b; s " "a;}\n" "gate ccx a,b,c{ h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t " "b; t c; h c; cx a,b; t a; tdg b; cx a,b;}\n" "gate crz(lambda) a,b{ u1(lambda/2) b; cx a,b; u1(-lambda/2) b; cx a,b;}\n" "gate cu1(lambda) a,b{ u1(lambda/2) a; cx a,b; u1(-lambda/2) b; cx a,b; " "u1(lambda/2) b;}\n" "gate cu3(theta,phi,lambda) c,t { u1((lambda-phi)/2) t; cx c,t; " "u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t;}\n"; #else /** * \brief OpenQASM 2.0 standard library + r and cswap gates, as a string * constant, as defined by Qiskit in * https://github.com/Qiskit/qiskit-terra/tree/master/qiskit/circuit/library/standard_gates */ static const std::string std_include = "gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }\n" "gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }\n" "gate u1(lambda) q { U(0,0,lambda) q; }\n" "gate cx c,t { CX c,t; }\n" "gate id a { U(0,0,0) a; }\n" "gate u0(gamma) q { U(0,0,0) q; }\n" "gate x a { u3(pi,0,pi) a; }\n" "gate y a { u3(pi,pi/2,pi/2) a; }\n" "gate z a { u1(pi) a; }\n" "gate h a { u2(0,pi) a; }\n" "gate s a { u1(pi/2) a; }\n" "gate sdg a { u1(-pi/2) a; }\n" "gate t a { u1(pi/4) a; }\n" "gate tdg a { u1(-pi/4) a; }\n" "gate r(theta, phi) a { u3(theta,phi-pi/2,-phi+pi/2) a; }\n" "gate rx(theta) a { r(theta,0) a; } \n" "gate ry(theta) a { r(theta,pi/2) a; }\n" /** * Rz = e^{-i*phi/2} U1 * This differs from the docstring here: * https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/rz.py#L65 */ "gate rz(phi) a { u1(phi) a; x a; u1(-phi/2) a; x a; u1(-phi/2) a; } \n" "gate cz a,b { h b; cx a,b; h b; }\n" "gate cy a,b { sdg b; cx a,b; s b; }\n" "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n" "gate ch a,b { s b; h b; t b; cx a,b; tdg b; h b; sdg b; }\n" "gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; " "t b; t c; h c; cx a,b; t a; tdg b; cx a,b; }\n" "gate cswap a,b,c { cx c,b; ccx a,b,c; cx c,b; }\n" "gate crz(lambda) a,b { u1(lambda/2) b; cx a,b; u1(-lambda/2) b; cx a,b; " "}\n" "gate cu1(lambda) a,b { u1(lambda/2) a; cx a,b; u1(-lambda/2) b; cx a,b; " "u1(lambda/2) b; }\n" "gate cu3(theta,phi,lambda) c,t { u1((lambda+phi)/2) c; " "u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; " "u3(theta/2,phi,0) t; }\n"; #endif /** * \class qasmtools::parser::Preprocessor * \brief OpenQASM preprocessor class * \see qasmtools::parser::Lexer * * The preprocessor acts as a wrapper around the lexer, providing a token stream * that matches the stream produced by explicitly inserting included code. * Effectively, the preprocessor acts as the lexer on preprocessed code. */ class Preprocessor { using LexerPtr = std::unique_ptr<Lexer>; std::vector<LexerPtr> lexer_stack_{}; ///< owning stack of lexers LexerPtr current_lexer_ = nullptr; ///< current lexer bool std_include_ = false; ///< whether qelib1 has been included public: /** * \brief Default constructor */ Preprocessor() = default; /** * \brief Inserts a file into the current lexing context * * Buffers the given file, then pushes the current buffer onto * the stack and sets the new buffer as the current buffer * * \param file_path The file to insert * \return True on success */ bool add_target_file(const std::string& file_path) { std::shared_ptr<std::ifstream> ifs(new std::ifstream); ifs->open(file_path, std::ifstream::in); if (!ifs->good()) { return false; } if (current_lexer_ != nullptr) { lexer_stack_.push_back(std::move(current_lexer_)); } current_lexer_ = std::unique_ptr<Lexer>(new Lexer(ifs, file_path)); return true; } /** * \brief Inserts a buffer into the current lexing context * * Pushes the current buffer onto the stack and sets the new buffer as the * current buffer * * \param buffer Shared pointer to an input buffer * \param fname Filename associated with the buffer (optional) */ void add_target_stream(std::shared_ptr<std::istream> buffer, const std::string& fname = "") { if (current_lexer_ != nullptr) { lexer_stack_.push_back(std::move(current_lexer_)); } current_lexer_ = std::unique_ptr<Lexer>(new Lexer(buffer, fname)); } /** * \brief Gets the next token in the current buffer * \note Returns unknown token if there is no buffer to lex * * Lexes and returns the next token from the current buffer, * popping the next buffer off the stack if necessary * * \return The next lexed token */ Token next_token() { if (current_lexer_ == nullptr) { return Token(Position(), Token::Kind::eof, ""); } auto token = current_lexer_->next_token(); if (token.is(Token::Kind::kw_include)) { handle_include(); token = current_lexer_->next_token(); } else if (token.is(Token::Kind::eof)) { if (!lexer_stack_.empty()) { current_lexer_ = std::move(lexer_stack_.back()); lexer_stack_.pop_back(); token = current_lexer_->next_token(); } else { current_lexer_ = nullptr; } } return token; } /** * \brief Prints and consumes all tokens buffered */ void print_all_tokens() { Token current = next_token(); while (!current.is(Token::Kind::eof)) { std::cout << current.position() << ": " << current << " " << current.raw() << "\n"; current = next_token(); } } bool includes_stdlib() { return std_include_; } private: /** * \brief Handles include statements * \note Expects STRING SEMICOLON * * Reads a filename from a string token and attempts to open and switch * lexing context to the file */ void handle_include() { auto token = current_lexer_->next_token(); if (token.is_not(Token::Kind::string)) { std::cerr << "Error: Include must be followed by a file name\n"; return; } auto target = token.as_string(); if (target == "qelib1.inc") std_include_ = true; token = current_lexer_->next_token(); if (token.is_not(Token::Kind::semicolon)) { std::cerr << "Warning: Missing a ';'\n"; } if (add_target_file(target)) { return; } else if (target == "qelib1.inc") { add_target_stream(std::shared_ptr<std::istream>( new std::stringstream(std_include)), "qelib1.inc"); return; } else { std::cerr << "Error: Couldn't open file " << target << "\n"; } } }; } // namespace parser } // namespace qasmtools <commit_msg>better rz definition<commit_after>/* * This file is part of qasmtools. * * Copyright (c) 2019 - 2021 softwareQ Inc. All rights reserved. * * MIT License * * 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. * * Adapted from Bruno Schmitt's Tweedledee library */ /** * \file qasmtools/parser/preprocessor.hpp * \brief Manages includes for OpenQASM parsing */ #pragma once #include "lexer.hpp" #include <fstream> #include <sstream> #include <vector> namespace qasmtools { namespace parser { #if USE_OPENQASM2_SPECS /** * \brief OpenQASM 2.0 standard library (qelib1.inc) as a string constant */ static const std::string std_include = "gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }\n" "gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }\n" "gate u1(lambda) q { U(0,0,lambda) q; }\n" "gate cx c,t { CX c,t; }\n" "gate id a { U(0,0,0) a; }\n" "gate u0(gamma) q { U(0,0,0) q; }\n" "gate x a { u3(pi,0,pi) a; }\n" "gate y a { u3(pi,pi/2,pi/2) a; }\n" "gate z a { u1(pi) a; }\n" "gate h a { u2(0,pi) a; }\n" "gate s a { u1(pi/2) a; }\n" "gate sdg a { u1(-pi/2) a; }\n" "gate t a { u1(pi/4) a; }\n" "gate tdg a { u1(-pi/4) a; }\n" "gate rx(theta) a { u3(theta, -pi/2,pi/2) a; }\n" "gate ry(theta) a { u3(theta,0,0) a; }\n" "gate rz(phi) a { u1(phi) a; }\n" "gate cz a,b { h b; cx a,b; h b; }\n" "gate cy a,b { sdg b; cx a,b; s b; }\n" "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n" "gate ch a,b { h b; sdg b;cx a,b;h b; t b;cx a,b;t b; h b; s b; x b; s " "a;}\n" "gate ccx a,b,c{ h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; t " "b; t c; h c; cx a,b; t a; tdg b; cx a,b;}\n" "gate crz(lambda) a,b{ u1(lambda/2) b; cx a,b; u1(-lambda/2) b; cx a,b;}\n" "gate cu1(lambda) a,b{ u1(lambda/2) a; cx a,b; u1(-lambda/2) b; cx a,b; " "u1(lambda/2) b;}\n" "gate cu3(theta,phi,lambda) c,t { u1((lambda-phi)/2) t; cx c,t; " "u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t;}\n"; #else /** * \brief OpenQASM 2.0 standard library + r and cswap gates, as a string * constant, as defined by Qiskit in * https://github.com/Qiskit/qiskit-terra/tree/master/qiskit/circuit/library/standard_gates */ static const std::string std_include = "gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }\n" "gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }\n" "gate u1(lambda) q { U(0,0,lambda) q; }\n" "gate cx c,t { CX c,t; }\n" "gate id a { U(0,0,0) a; }\n" "gate u0(gamma) q { U(0,0,0) q; }\n" "gate x a { u3(pi,0,pi) a; }\n" "gate y a { u3(pi,pi/2,pi/2) a; }\n" "gate z a { u1(pi) a; }\n" "gate h a { u2(0,pi) a; }\n" "gate s a { u1(pi/2) a; }\n" "gate sdg a { u1(-pi/2) a; }\n" "gate t a { u1(pi/4) a; }\n" "gate tdg a { u1(-pi/4) a; }\n" "gate r(theta, phi) a { u3(theta,phi-pi/2,-phi+pi/2) a; }\n" "gate rx(theta) a { r(theta,0) a; } \n" "gate ry(theta) a { r(theta,pi/2) a; }\n" /** * Rz = e^{-i*phi/2} U1 * This differs from the docstring here: * https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/rz.py#L65 */ "gate rz(phi) a { x a; u1(-phi/2) a; x a; u1(phi/2) a; } \n" "gate cz a,b { h b; cx a,b; h b; }\n" "gate cy a,b { sdg b; cx a,b; s b; }\n" "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n" "gate ch a,b { s b; h b; t b; cx a,b; tdg b; h b; sdg b; }\n" "gate ccx a,b,c { h c; cx b,c; tdg c; cx a,c; t c; cx b,c; tdg c; cx a,c; " "t b; t c; h c; cx a,b; t a; tdg b; cx a,b; }\n" "gate cswap a,b,c { cx c,b; ccx a,b,c; cx c,b; }\n" "gate crz(lambda) a,b { u1(lambda/2) b; cx a,b; u1(-lambda/2) b; cx a,b; " "}\n" "gate cu1(lambda) a,b { u1(lambda/2) a; cx a,b; u1(-lambda/2) b; cx a,b; " "u1(lambda/2) b; }\n" "gate cu3(theta,phi,lambda) c,t { u1((lambda+phi)/2) c; " "u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; " "u3(theta/2,phi,0) t; }\n"; #endif /** * \class qasmtools::parser::Preprocessor * \brief OpenQASM preprocessor class * \see qasmtools::parser::Lexer * * The preprocessor acts as a wrapper around the lexer, providing a token stream * that matches the stream produced by explicitly inserting included code. * Effectively, the preprocessor acts as the lexer on preprocessed code. */ class Preprocessor { using LexerPtr = std::unique_ptr<Lexer>; std::vector<LexerPtr> lexer_stack_{}; ///< owning stack of lexers LexerPtr current_lexer_ = nullptr; ///< current lexer bool std_include_ = false; ///< whether qelib1 has been included public: /** * \brief Default constructor */ Preprocessor() = default; /** * \brief Inserts a file into the current lexing context * * Buffers the given file, then pushes the current buffer onto * the stack and sets the new buffer as the current buffer * * \param file_path The file to insert * \return True on success */ bool add_target_file(const std::string& file_path) { std::shared_ptr<std::ifstream> ifs(new std::ifstream); ifs->open(file_path, std::ifstream::in); if (!ifs->good()) { return false; } if (current_lexer_ != nullptr) { lexer_stack_.push_back(std::move(current_lexer_)); } current_lexer_ = std::unique_ptr<Lexer>(new Lexer(ifs, file_path)); return true; } /** * \brief Inserts a buffer into the current lexing context * * Pushes the current buffer onto the stack and sets the new buffer as the * current buffer * * \param buffer Shared pointer to an input buffer * \param fname Filename associated with the buffer (optional) */ void add_target_stream(std::shared_ptr<std::istream> buffer, const std::string& fname = "") { if (current_lexer_ != nullptr) { lexer_stack_.push_back(std::move(current_lexer_)); } current_lexer_ = std::unique_ptr<Lexer>(new Lexer(buffer, fname)); } /** * \brief Gets the next token in the current buffer * \note Returns unknown token if there is no buffer to lex * * Lexes and returns the next token from the current buffer, * popping the next buffer off the stack if necessary * * \return The next lexed token */ Token next_token() { if (current_lexer_ == nullptr) { return Token(Position(), Token::Kind::eof, ""); } auto token = current_lexer_->next_token(); if (token.is(Token::Kind::kw_include)) { handle_include(); token = current_lexer_->next_token(); } else if (token.is(Token::Kind::eof)) { if (!lexer_stack_.empty()) { current_lexer_ = std::move(lexer_stack_.back()); lexer_stack_.pop_back(); token = current_lexer_->next_token(); } else { current_lexer_ = nullptr; } } return token; } /** * \brief Prints and consumes all tokens buffered */ void print_all_tokens() { Token current = next_token(); while (!current.is(Token::Kind::eof)) { std::cout << current.position() << ": " << current << " " << current.raw() << "\n"; current = next_token(); } } bool includes_stdlib() { return std_include_; } private: /** * \brief Handles include statements * \note Expects STRING SEMICOLON * * Reads a filename from a string token and attempts to open and switch * lexing context to the file */ void handle_include() { auto token = current_lexer_->next_token(); if (token.is_not(Token::Kind::string)) { std::cerr << "Error: Include must be followed by a file name\n"; return; } auto target = token.as_string(); if (target == "qelib1.inc") std_include_ = true; token = current_lexer_->next_token(); if (token.is_not(Token::Kind::semicolon)) { std::cerr << "Warning: Missing a ';'\n"; } if (add_target_file(target)) { return; } else if (target == "qelib1.inc") { add_target_stream(std::shared_ptr<std::istream>( new std::stringstream(std_include)), "qelib1.inc"); return; } else { std::cerr << "Error: Couldn't open file " << target << "\n"; } } }; } // namespace parser } // namespace qasmtools <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> #include <apr_pools.h> #include <apr_atomic.h> #include <apr_time.h> #include <assert.h> #include <log4cxx/helpers/threadspecificdata.h> using namespace log4cxx::helpers; using namespace log4cxx; bool APRInitializer::isDestructed = false; namespace { void tlsDestruct(void* ptr) { delete ((ThreadSpecificData*) ptr); } } APRInitializer::APRInitializer() { apr_initialize(); apr_pool_create(&p, NULL); apr_atomic_init(p); startTime = apr_time_now(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&tlsKey, tlsDestruct, p); assert(stat == APR_SUCCESS); #endif } APRInitializer::~APRInitializer() { apr_terminate(); isDestructed = true; } APRInitializer& APRInitializer::getInstance() { static APRInitializer init; return init; } log4cxx_time_t APRInitializer::initialize() { return getInstance().startTime; } apr_pool_t* APRInitializer::getRootPool() { return getInstance().p; } apr_threadkey_t* APRInitializer::getTlsKey() { return getInstance().tlsKey; } <commit_msg>LOGCXX-265: Ananchronism warnings<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxx/logstring.h> #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include <log4cxx/helpers/aprinitializer.h> #include <apr_pools.h> #include <apr_atomic.h> #include <apr_time.h> #include <assert.h> #include <log4cxx/helpers/threadspecificdata.h> using namespace log4cxx::helpers; using namespace log4cxx; bool APRInitializer::isDestructed = false; namespace { extern "C" void tlsDestruct(void* ptr) { delete ((ThreadSpecificData*) ptr); } } APRInitializer::APRInitializer() { apr_initialize(); apr_pool_create(&p, NULL); apr_atomic_init(p); startTime = apr_time_now(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&tlsKey, tlsDestruct, p); assert(stat == APR_SUCCESS); #endif } APRInitializer::~APRInitializer() { apr_terminate(); isDestructed = true; } APRInitializer& APRInitializer::getInstance() { static APRInitializer init; return init; } log4cxx_time_t APRInitializer::initialize() { return getInstance().startTime; } apr_pool_t* APRInitializer::getRootPool() { return getInstance().p; } apr_threadkey_t* APRInitializer::getTlsKey() { return getInstance().tlsKey; } <|endoftext|>
<commit_before>#ifndef _C4_STORAGE_GROWTH_HPP_ #define _C4_STORAGE_GROWTH_HPP_ /** @file growth.hpp Storage growth policies for dynamic containers. */ #include "c4/config.hpp" #include "c4/error.hpp" C4_BEGIN_NAMESPACE(c4) C4_BEGIN_NAMESPACE(stg) /** @defgroup storage_growth_policies Storage growth policies * These are policies which can be used in dynamic growth containers. */ //----------------------------------------------------------------------------- /** Grow by the least possible amount. * @ingroup storage_growth_policies */ struct growth_least { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { return at_least; } }; /** growth_least with watermark. * @ingroup storage_growth_policies */ struct growth_least_wm { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { if(at_least < curr) return curr; return at_least; } }; //----------------------------------------------------------------------------- /** Grow to the double of the current size if it is bigger than at_least; * if not, then just to at_least. * @ingroup storage_growth_policies */ struct growth_pot { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { size_t nxt = (curr << 1); return nxt > at_least ? nxt : at_least; } }; /** growth_pot with watermark. * @ingroup storage_growth_policies */ struct growth_pot_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_pot::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow by the Fibonacci ratio if the result is bigger than at_least; * if not, then just to at_least. * @ingroup storage_growth_policies */ struct growth_phi { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { if(at_least <= curr) return curr; size_t nxt = size_t(float(curr) * 1.618f); nxt = nxt > 0 ? nxt : 1; return nxt > at_least ? nxt : at_least; } }; /** growth_phi with watermark. * @ingroup storage_growth_policies */ struct growth_phi_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_phi::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow another growth policy in fixed chunk sizes; useful for SIMD buffers. The chunk size must be a power of two. * @ingroup storage_growth_policies */ template< class GrowthPolicy, size_t PowerOfTwoChunkSize > struct growth_chunks { C4_STATIC_ASSERT(PowerOfTwoChunkSize > 1); C4_STATIC_ASSERT_MSG((PowerOfTwoChunkSize & (PowerOfTwoChunkSize - 1)) == 0, "chunk size must be a power of two"); using growth_policy = GrowthPolicy; enum { chunk_size = PowerOfTwoChunkSize }; C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { size_t next = GrowthPolicy::next_size(curr, at_least); size_t rem = (next & (PowerOfTwoChunkSize - 1)); next += rem ? PowerOfTwoChunkSize - rem : 0; C4_ASSERT((next % PowerOfTwoChunkSize) == 0); C4_ASSERT(next >= at_least); return next; } }; /** growth_chunks with watermark. * @ingroup storage_growth_policies */ template< class GrowthPolicy, size_t PowerOfTwoChunkSize > struct growth_chunks_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_chunks< GrowthPolicy, PowerOfTwoChunkSize >::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow by powers of 2 until a threshold of 1024 bytes, then Fibonacci (golden) ratio * @ingroup storage_growth_policies */ struct growth_default { enum { threshold = 1024 }; C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { if(at_least*elm_size <= threshold) return growth_pot_wm::next_size(elm_size, curr, at_least); else return growth_phi_wm::next_size(elm_size, curr, at_least); } }; //----------------------------------------------------------------------------- /** @ingroup storage_growth_policies */ template< class SmallGrowthPolicy, class LargeGrowthPolicy, size_t BytesThreshold > struct growth_composed { using small_policy = SmallGrowthPolicy; using large_policy = LargeGrowthPolicy; enum { threshold = BytesThreshold }; C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { if(at_least*elm_size <= BytesThreshold) return SmallGrowthPolicy::next_size(elm_size, curr, at_least); else return LargeGrowthPolicy::next_size(elm_size, curr, at_least); } }; /** growth_composed with watermark. * @ingroup storage_growth_policies */ template< class SmallGrowthPolicy, class LargeGrowthPolicy, size_t BytesThreshold > struct growth_composed_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { using gc = growth_composed< SmallGrowthPolicy, LargeGrowthPolicy, BytesThreshold >; size_t ns = gc::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; C4_END_NAMESPACE(stg) C4_END_NAMESPACE(c4) #endif // _C4_STORAGE_GROWTH_HPP_ <commit_msg>growth policies: add watermark policy.<commit_after>#ifndef _C4_STORAGE_GROWTH_HPP_ #define _C4_STORAGE_GROWTH_HPP_ /** @file growth.hpp Storage growth policies for dynamic containers. */ #include "c4/config.hpp" #include "c4/error.hpp" C4_BEGIN_NAMESPACE(c4) C4_BEGIN_NAMESPACE(stg) /** @defgroup storage_growth_policies Storage growth policies * These are policies which can be used in dynamic growth containers. */ //----------------------------------------------------------------------------- /** Grow by the least possible amount. * @ingroup storage_growth_policies */ struct growth_least { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { return at_least; } }; /** growth_least with watermark. * @ingroup storage_growth_policies */ struct growth_least_wm { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { if(at_least < curr) return curr; return at_least; } }; //----------------------------------------------------------------------------- /** Grow to the double of the current size if it is bigger than at_least; * if not, then just to at_least. * @ingroup storage_growth_policies */ struct growth_pot { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { size_t nxt = (curr << 1); return nxt > at_least ? nxt : at_least; } }; /** growth_pot with watermark. * @ingroup storage_growth_policies */ struct growth_pot_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_pot::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow by the Fibonacci ratio if the result is bigger than at_least; * if not, then just to at_least. * @ingroup storage_growth_policies */ struct growth_phi { C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { if(at_least <= curr) return curr; size_t nxt = size_t(float(curr) * 1.618f); nxt = nxt > 0 ? nxt : 1; return nxt > at_least ? nxt : at_least; } }; /** growth_phi with watermark. * @ingroup storage_growth_policies */ struct growth_phi_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_phi::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow another growth policy in fixed chunk sizes; useful for SIMD buffers. The chunk size must be a power of two. * @ingroup storage_growth_policies */ template< class GrowthPolicy, size_t PowerOfTwoChunkSize > struct growth_chunks { C4_STATIC_ASSERT(PowerOfTwoChunkSize > 1); C4_STATIC_ASSERT_MSG((PowerOfTwoChunkSize & (PowerOfTwoChunkSize - 1)) == 0, "chunk size must be a power of two"); using growth_policy = GrowthPolicy; enum { chunk_size = PowerOfTwoChunkSize }; C4_ALWAYS_INLINE static size_t next_size(size_t /*elm_size*/, size_t curr, size_t at_least) noexcept { size_t next = GrowthPolicy::next_size(curr, at_least); size_t rem = (next & (PowerOfTwoChunkSize - 1)); next += rem ? PowerOfTwoChunkSize - rem : 0; C4_ASSERT((next % PowerOfTwoChunkSize) == 0); C4_ASSERT(next >= at_least); return next; } }; /** growth_chunks with watermark. * @ingroup storage_growth_policies */ template< class GrowthPolicy, size_t PowerOfTwoChunkSize > struct growth_chunks_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = growth_chunks< GrowthPolicy, PowerOfTwoChunkSize >::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** Grow by powers of 2 until a threshold of 1024 bytes, then Fibonacci (golden) ratio * @ingroup storage_growth_policies */ struct growth_default { enum { threshold = 1024 }; C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { if(at_least*elm_size <= threshold) return growth_pot_wm::next_size(elm_size, curr, at_least); else return growth_phi_wm::next_size(elm_size, curr, at_least); } }; //----------------------------------------------------------------------------- /** @ingroup storage_growth_policies */ template< class SmallGrowthPolicy, class LargeGrowthPolicy, size_t BytesThreshold > struct growth_composed { using small_policy = SmallGrowthPolicy; using large_policy = LargeGrowthPolicy; enum { threshold = BytesThreshold }; C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { if(at_least*elm_size <= BytesThreshold) return SmallGrowthPolicy::next_size(elm_size, curr, at_least); else return LargeGrowthPolicy::next_size(elm_size, curr, at_least); } }; /** growth_composed with watermark. * @ingroup storage_growth_policies */ template< class SmallGrowthPolicy, class LargeGrowthPolicy, size_t BytesThreshold > struct growth_composed_wm { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { using gc = growth_composed< SmallGrowthPolicy, LargeGrowthPolicy, BytesThreshold >; size_t ns = gc::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; //----------------------------------------------------------------------------- /** @ingroup storage_growth_policies */ template< class GrowthPolicy > struct growth_watermark { C4_ALWAYS_INLINE static size_t next_size(size_t elm_size, size_t curr, size_t at_least) noexcept { size_t ns = GrowthPolicy::next_size(elm_size, curr, at_least); if(ns <= curr) return curr; return ns; } }; C4_END_NAMESPACE(stg) C4_END_NAMESPACE(c4) #endif // _C4_STORAGE_GROWTH_HPP_ <|endoftext|>
<commit_before>#include "../cshared/shared.h" #include "../cshared/opcodes.h" #include "../cshared/opcodes_format.h" #include "../cshared/opcodes_debug.h" #include "../cshared/asm_stream.h" #include "../cshared/stream.h" struct Arg { uint64_t fixnum = 0; std::string string; Arg(uint64_t fixnum) : fixnum(fixnum) { } Arg(dab_register_t reg) : fixnum(reg.value()) { } Arg(std::vector<dab_register_t> regs) { (void)regs; } Arg(std::string string) : string(string) { } }; struct Op { size_t code; std::vector<Arg> data; uint16_t arg_uint16(size_t index) { return data[index].fixnum; } }; void read_stream(Stream &stream) { byte buffer[1024]; while (!feof(stdin)) { size_t bytes = fread(buffer, 1, 1024, stdin); if (bytes) { stream.append(buffer, bytes); } } } void parse_stream(Stream &stream, std::function<void(Op)> func) { while (!stream.eof()) { auto opcode = stream.read_uint8(); assert(opcode < countof(g_opcodes)); const auto &data = g_opcodes[opcode]; Op op; op.code = opcode; for (const auto &arg : data.args) { switch (arg) { case OpcodeArg::ARG_INT8: op.data.push_back(stream.read_int8()); break; case OpcodeArg::ARG_UINT8: op.data.push_back(stream.read_uint8()); break; case OpcodeArg::ARG_UINT16: op.data.push_back(stream.read_uint16()); break; case OpcodeArg::ARG_UINT64: op.data.push_back(stream.read_uint64()); break; case OpcodeArg::ARG_INT16: op.data.push_back(stream.read_int16()); break; case OpcodeArg::ARG_VLC: op.data.push_back(stream.read_vlc_string()); break; case OpcodeArg::ARG_UINT32: op.data.push_back(stream.read_uint32()); break; case OpcodeArg::ARG_INT32: op.data.push_back(stream.read_int32()); break; case OpcodeArg::ARG_INT64: op.data.push_back(stream.read_int64()); break; case OpcodeArg::ARG_REG: op.data.push_back(stream.read_reg()); break; case OpcodeArg::ARG_SYMBOL: op.data.push_back(stream.read_symbol()); break; case OpcodeArg::ARG_REGLIST: op.data.push_back(stream.read_reglist()); break; case OpcodeArg::ARG_STRING4: op.data.push_back(stream.read_string4()); break; case OpcodeArg::ARG_CSTRING: op.data.push_back(stream.read_cstring()); break; } } func(op); } }; int main() { std::map<uint64_t, std::string> files; std::map<uint64_t, std::set<uint64_t>> lines; Stream stream; read_stream(stream); auto header = stream.peek_header(); fprintf(stderr, "cdumpcov: %d sections\n", (int)header->section_count); for (size_t i = 0; i < header->section_count; i++) { auto section = header->sections[i]; fprintf(stderr, "cdumpcov: section[%d] '%s'\n", (int)i, section.name); std::string section_name = section.name; if (section_name == "cove") { auto size_of_cov_file = sizeof(uint64_t); auto number_of_cov_files = section.length / size_of_cov_file; fprintf(stderr, "cdumpcov: %d cov files\n", (int)number_of_cov_files); for (size_t j = 0; j < number_of_cov_files; j++) { auto ptr = section.pos + size_of_cov_file * j; auto data = stream.uint64_data(ptr); auto string = stream.cstring_data(data); fprintf(stderr, "cdumpcov: cov[%d] %p -> %p -> '%s'\n", (int)j, (void *)ptr, (void *)data, string.c_str()); files[j + 1] = string; } } if (section_name == "code") { auto substream = stream.section_stream(i); parse_stream(substream, [&files, &lines](Op op) { if (op.code == OP_COV) { lines[op.arg_uint16(0)].insert(op.arg_uint16(1)); } }); } } printf("["); int j = 0; for (auto f : files) { if (j++ > 0) printf(","); printf("{\"file\": \"%s\", \"lines\": [", f.second.c_str()); auto &file_lines = lines[f.first]; int i = 0; for (auto line : file_lines) { if (i++ > 0) printf(", "); printf("%d", (int)line); } printf("]}"); } printf("]\n"); return 0; } <commit_msg>vm: fix some numeric type cast issue<commit_after>#include "../cshared/shared.h" #include "../cshared/opcodes.h" #include "../cshared/opcodes_format.h" #include "../cshared/opcodes_debug.h" #include "../cshared/asm_stream.h" #include "../cshared/stream.h" struct Arg { uint64_t fixnum = 0; std::string string; Arg(uint64_t fixnum) : fixnum(fixnum) { } Arg(dab_register_t reg) : fixnum(reg.value()) { } Arg(std::vector<dab_register_t> regs) { (void)regs; } Arg(std::string string) : string(string) { } }; struct Op { size_t code; std::vector<Arg> data; uint16_t arg_uint16(size_t index) { return (uint16_t)data[index].fixnum; } }; void read_stream(Stream &stream) { byte buffer[1024]; while (!feof(stdin)) { size_t bytes = fread(buffer, 1, 1024, stdin); if (bytes) { stream.append(buffer, bytes); } } } void parse_stream(Stream &stream, std::function<void(Op)> func) { while (!stream.eof()) { auto opcode = stream.read_uint8(); assert(opcode < countof(g_opcodes)); const auto &data = g_opcodes[opcode]; Op op; op.code = opcode; for (const auto &arg : data.args) { switch (arg) { case OpcodeArg::ARG_INT8: op.data.push_back(stream.read_int8()); break; case OpcodeArg::ARG_UINT8: op.data.push_back(stream.read_uint8()); break; case OpcodeArg::ARG_UINT16: op.data.push_back(stream.read_uint16()); break; case OpcodeArg::ARG_UINT64: op.data.push_back(stream.read_uint64()); break; case OpcodeArg::ARG_INT16: op.data.push_back(stream.read_int16()); break; case OpcodeArg::ARG_VLC: op.data.push_back(stream.read_vlc_string()); break; case OpcodeArg::ARG_UINT32: op.data.push_back(stream.read_uint32()); break; case OpcodeArg::ARG_INT32: op.data.push_back(stream.read_int32()); break; case OpcodeArg::ARG_INT64: op.data.push_back(stream.read_int64()); break; case OpcodeArg::ARG_REG: op.data.push_back(stream.read_reg()); break; case OpcodeArg::ARG_SYMBOL: op.data.push_back(stream.read_symbol()); break; case OpcodeArg::ARG_REGLIST: op.data.push_back(stream.read_reglist()); break; case OpcodeArg::ARG_STRING4: op.data.push_back(stream.read_string4()); break; case OpcodeArg::ARG_CSTRING: op.data.push_back(stream.read_cstring()); break; } } func(op); } }; int main() { std::map<uint64_t, std::string> files; std::map<uint64_t, std::set<uint64_t>> lines; Stream stream; read_stream(stream); auto header = stream.peek_header(); fprintf(stderr, "cdumpcov: %d sections\n", (int)header->section_count); for (size_t i = 0; i < header->section_count; i++) { auto section = header->sections[i]; fprintf(stderr, "cdumpcov: section[%d] '%s'\n", (int)i, section.name); std::string section_name = section.name; if (section_name == "cove") { auto size_of_cov_file = sizeof(uint64_t); auto number_of_cov_files = section.length / size_of_cov_file; fprintf(stderr, "cdumpcov: %d cov files\n", (int)number_of_cov_files); for (size_t j = 0; j < number_of_cov_files; j++) { auto ptr = section.pos + size_of_cov_file * j; auto data = stream.uint64_data(ptr); auto string = stream.cstring_data(data); fprintf(stderr, "cdumpcov: cov[%d] %p -> %p -> '%s'\n", (int)j, (void *)ptr, (void *)data, string.c_str()); files[j + 1] = string; } } if (section_name == "code") { auto substream = stream.section_stream(i); parse_stream(substream, [&files, &lines](Op op) { if (op.code == OP_COV) { lines[op.arg_uint16(0)].insert(op.arg_uint16(1)); } }); } } printf("["); int j = 0; for (auto f : files) { if (j++ > 0) printf(","); printf("{\"file\": \"%s\", \"lines\": [", f.second.c_str()); auto &file_lines = lines[f.first]; int i = 0; for (auto line : file_lines) { if (i++ > 0) printf(", "); printf("%d", (int)line); } printf("]}"); } printf("]\n"); return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "chainoftrustmodel.h" #include <certificate.h> #include <extensions/securityevaluationextension.h> #include <securityevaluationmodel.h> struct ChainedCertificateNode { ChainedCertificateNode(Certificate* c) : m_pCertificate(c),m_pParent(nullptr),m_pChild(nullptr){} Certificate* m_pCertificate; ChainedCertificateNode* m_pParent; ChainedCertificateNode* m_pChild; }; class ChainOfTrustModelPrivate { public: Certificate* m_pCertificate; ChainedCertificateNode* m_pRoot; }; ChainOfTrustModel::ChainOfTrustModel(Certificate* c) : QAbstractItemModel(c), d_ptr(new ChainOfTrustModelPrivate()) { d_ptr->m_pCertificate = c; ChainedCertificateNode* n = nullptr; Certificate* cn = c; while (cn) { ChainedCertificateNode* prev = n; n = new ChainedCertificateNode(cn); n ->m_pChild = prev ; if (prev) prev->m_pParent = n ; cn = cn->signedBy(); } d_ptr->m_pRoot = n; emit layoutChanged(); } ChainOfTrustModel::~ChainOfTrustModel() { delete d_ptr; } QHash<int,QByteArray> ChainOfTrustModel::roleNames() const { static QHash<int,QByteArray> roles; if (roles.isEmpty()) { roles[(int) Role::OBJECT] = "object"; } return roles; } QVariant ChainOfTrustModel::data( const QModelIndex& index, int role ) const { if (!index.isValid()) return QVariant(); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(index.internalPointer()); switch(role) { case Qt::DisplayRole: return c->m_pCertificate->publicKeyId(); case Qt::DecorationRole: if (c->m_pCertificate->extension<SecurityEvaluationExtension>()) { return c->m_pCertificate->extension<SecurityEvaluationExtension>()->securityLevelIcon(c->m_pCertificate); } break; case (int) Role::OBJECT: return QVariant::fromValue(c->m_pCertificate); case (int) Role::SECURITY_LEVEL: if (c->m_pCertificate->extension<SecurityEvaluationExtension>()) { return QVariant::fromValue( c->m_pCertificate->extension<SecurityEvaluationExtension>()->securityLevel(c->m_pCertificate) ); } break; } return QVariant(); } bool ChainOfTrustModel::setData( const QModelIndex& index, const QVariant &value, int role ) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role ) return false; } int ChainOfTrustModel::rowCount( const QModelIndex& parent ) const { if (!parent.isValid()) return 1; ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(parent.internalPointer()); //The last node is the "leaf" certificate that is being viewed return c->m_pChild ? 1 : 0; } Qt::ItemFlags ChainOfTrustModel::flags( const QModelIndex& index ) const { return index.isValid() ? Qt::ItemIsEnabled | Qt::ItemIsSelectable : Qt::NoItemFlags; } int ChainOfTrustModel::columnCount( const QModelIndex& parent ) const { Q_UNUSED(parent) return 1; } QModelIndex ChainOfTrustModel::parent( const QModelIndex& idx ) const { if (!idx.isValid()) return QModelIndex(); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(idx.internalPointer()); //Root if (!c->m_pParent) return QModelIndex(); return createIndex(0,0,c->m_pParent); } QModelIndex ChainOfTrustModel::index( int row, int column, const QModelIndex& parent ) const { if (row || column) return QModelIndex(); if (!parent.isValid()) return createIndex(0,0,d_ptr->m_pRoot); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(parent.internalPointer()); return createIndex(0,0,c->m_pChild); } QVariant ChainOfTrustModel::headerData( int section, Qt::Orientation o, int role ) const { if ((!section) && role == Qt::DisplayRole && o == Qt::Horizontal) return tr("Chain of trust"); return QVariant(); }<commit_msg>chainoftrust: Prevent infinite loop for self signed certificates<commit_after>/**************************************************************************** * Copyright (C) 2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "chainoftrustmodel.h" #include <certificate.h> #include <extensions/securityevaluationextension.h> #include <securityevaluationmodel.h> struct ChainedCertificateNode { ChainedCertificateNode(Certificate* c) : m_pCertificate(c),m_pParent(nullptr),m_pChild(nullptr){} Certificate* m_pCertificate; ChainedCertificateNode* m_pParent; ChainedCertificateNode* m_pChild; }; class ChainOfTrustModelPrivate { public: Certificate* m_pCertificate; ChainedCertificateNode* m_pRoot; }; ChainOfTrustModel::ChainOfTrustModel(Certificate* c) : QAbstractItemModel(c), d_ptr(new ChainOfTrustModelPrivate()) { d_ptr->m_pCertificate = c; ChainedCertificateNode* n = nullptr; Certificate* cn = c; while (cn) { ChainedCertificateNode* prev = n; n = new ChainedCertificateNode(cn); n ->m_pChild = prev ; if (prev) prev->m_pParent = n ; Certificate* next = cn->signedBy(); //Prevent infinite loop of self signed certificates cn = next == cn ? nullptr : next; } d_ptr->m_pRoot = n; emit layoutChanged(); } ChainOfTrustModel::~ChainOfTrustModel() { delete d_ptr; } QHash<int,QByteArray> ChainOfTrustModel::roleNames() const { static QHash<int,QByteArray> roles; if (roles.isEmpty()) { roles[(int) Role::OBJECT] = "object"; } return roles; } QVariant ChainOfTrustModel::data( const QModelIndex& index, int role ) const { if (!index.isValid()) return QVariant(); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(index.internalPointer()); switch(role) { case Qt::DisplayRole: return c->m_pCertificate->publicKeyId(); case Qt::DecorationRole: if (c->m_pCertificate->extension<SecurityEvaluationExtension>()) { return c->m_pCertificate->extension<SecurityEvaluationExtension>()->securityLevelIcon(c->m_pCertificate); } break; case (int) Role::OBJECT: return QVariant::fromValue(c->m_pCertificate); case (int) Role::SECURITY_LEVEL: if (c->m_pCertificate->extension<SecurityEvaluationExtension>()) { return QVariant::fromValue( c->m_pCertificate->extension<SecurityEvaluationExtension>()->securityLevel(c->m_pCertificate) ); } break; } return QVariant(); } bool ChainOfTrustModel::setData( const QModelIndex& index, const QVariant &value, int role ) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role ) return false; } int ChainOfTrustModel::rowCount( const QModelIndex& parent ) const { if (!parent.isValid()) return 1; ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(parent.internalPointer()); //The last node is the "leaf" certificate that is being viewed return c->m_pChild ? 1 : 0; } Qt::ItemFlags ChainOfTrustModel::flags( const QModelIndex& index ) const { return index.isValid() ? Qt::ItemIsEnabled | Qt::ItemIsSelectable : Qt::NoItemFlags; } int ChainOfTrustModel::columnCount( const QModelIndex& parent ) const { Q_UNUSED(parent) return 1; } QModelIndex ChainOfTrustModel::parent( const QModelIndex& idx ) const { if (!idx.isValid()) return QModelIndex(); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(idx.internalPointer()); //Root if (!c->m_pParent) return QModelIndex(); return createIndex(0,0,c->m_pParent); } QModelIndex ChainOfTrustModel::index( int row, int column, const QModelIndex& parent ) const { if (row || column) return QModelIndex(); if (!parent.isValid()) return createIndex(0,0,d_ptr->m_pRoot); ChainedCertificateNode* c = static_cast<ChainedCertificateNode*>(parent.internalPointer()); return createIndex(0,0,c->m_pChild); } QVariant ChainOfTrustModel::headerData( int section, Qt::Orientation o, int role ) const { if ((!section) && role == Qt::DisplayRole && o == Qt::Horizontal) return tr("Chain of trust"); return QVariant(); }<|endoftext|>
<commit_before>/** * @file */ #pragma once /** * @def LIBBIRCH_ATOMIC_OPENMP * * Set to 1 for libbirch::Atomic use OpenMP, or 0 to use std::atomic. * * The advantage of the OpenMP implementation is assured memory model * consistency and the organic disabling of atomics when OpenMP, and thus * multithreading, is disabled (this can improve performance significantly for * single threading). The disadvantage is that OpenMP atomics do not support * compare-and-swap/compare-and-exchange, only swap/exchange, which can * require some clunkier client code, especially for read-write locks. */ #ifdef __APPLE__ /* on Mac, OpenMP atomics appear to cause crashes when release mode is * enabled */ #define LIBBIRCH_ATOMIC_OPENMP 0 #else #define LIBBIRCH_ATOMIC_OPENMP 1 #endif #if !LIBBIRCH_ATOMIC_OPENMP #include <atomic> #endif namespace libbirch { /** * Atomic value. * * @tparam Value type. */ template<class T> class Atomic { public: /** * Default constructor. Initializes the value, not necessarily atomically. */ Atomic() = default; /** * Constructor. * * @param value Initial value. * * Initializes the value, atomically. */ explicit Atomic(const T& value) { store(value); } /** * Load the value, atomically. */ T load() const { #if LIBBIRCH_ATOMIC_OPENMP T value; #pragma omp atomic read value = this->value; return value; #else return this->value.load(std::memory_order_relaxed); #endif } /** * Store the value, atomically. */ void store(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic write this->value = value; #else this->value.store(value, std::memory_order_relaxed); #endif } /** * Exchange the value with another, atomically. * * @param value New value. * * @return Old value. */ T exchange(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value = value; } return old; #else return this->value.exchange(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value &= value; } return old; #else return this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value |= value; } return old; #else return this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `and`, atomically. * * @param m Mask. */ void maskAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value &= value; #else this->value.fetch_and(value, std::memory_order_relaxed); #endif } /** * Apply a mask, with bitwise `or`, atomically. * * @param m Mask. */ void maskOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value |= value; #else this->value.fetch_or(value, std::memory_order_relaxed); #endif } /** * Increment the value by one, atomically, but without capturing the * current value. */ void increment() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update ++value; #else value.fetch_add(1, std::memory_order_relaxed); #endif } /** * Decrement the value by one, atomically, but without capturing the * current value. */ void decrement() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update --value; #else value.fetch_sub(1, std::memory_order_relaxed); #endif } /** * Add to the value, atomically, but without capturing the current value. */ template<class U> void add(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value += value; #else this->value.fetch_add(value, std::memory_order_relaxed); #endif } /** * Subtract from the value, atomically, but without capturing the current * value. */ template<class U> void subtract(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value -= value; #else this->value.fetch_sub(value, std::memory_order_relaxed); #endif } template<class U> T operator+=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value += value; result = this->value; } return result; #else return this->value.fetch_add(value, std::memory_order_relaxed) + value; #endif } template<class U> T operator-=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value -= value; result = this->value; } return result; #else return this->value.fetch_sub(value, std::memory_order_relaxed) - value; #endif } T operator++() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { ++this->value; result = this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed) + 1; #endif } T operator++(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; ++this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_relaxed); #endif } T operator--() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { --this->value; result = this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed) - 1; #endif } T operator--(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; --this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_relaxed); #endif } private: /** * Value. */ #if LIBBIRCH_ATOMIC_OPENMP T value; #else std::atomic<T> value; #endif }; } <commit_msg>Switched back to sequentially-consistent memory order for std::atomic.<commit_after>/** * @file */ #pragma once /** * @def LIBBIRCH_ATOMIC_OPENMP * * Set to 1 for libbirch::Atomic use OpenMP, or 0 to use std::atomic. * * The advantage of the OpenMP implementation is assured memory model * consistency and the organic disabling of atomics when OpenMP, and thus * multithreading, is disabled (this can improve performance significantly for * single threading). The disadvantage is that OpenMP atomics do not support * compare-and-swap/compare-and-exchange, only swap/exchange, which can * require some clunkier client code, especially for read-write locks. */ #ifdef __APPLE__ /* on Mac, OpenMP atomics appear to cause crashes when release mode is * enabled */ #define LIBBIRCH_ATOMIC_OPENMP 0 #else #define LIBBIRCH_ATOMIC_OPENMP 1 #endif #if !LIBBIRCH_ATOMIC_OPENMP #include <atomic> #endif namespace libbirch { /** * Atomic value. * * @tparam Value type. */ template<class T> class Atomic { public: /** * Default constructor. Initializes the value, not necessarily atomically. */ Atomic() = default; /** * Constructor. * * @param value Initial value. * * Initializes the value, atomically. */ explicit Atomic(const T& value) { store(value); } /** * Load the value, atomically. */ T load() const { #if LIBBIRCH_ATOMIC_OPENMP T value; #pragma omp atomic read value = this->value; return value; #else return this->value.load(std::memory_order_seq_cst); #endif } /** * Store the value, atomically. */ void store(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic write this->value = value; #else this->value.store(value, std::memory_order_seq_cst); #endif } /** * Exchange the value with another, atomically. * * @param value New value. * * @return Old value. */ T exchange(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value = value; } return old; #else return this->value.exchange(value, std::memory_order_seq_cst); #endif } /** * Apply a mask, with bitwise `and`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value &= value; } return old; #else return this->value.fetch_and(value, std::memory_order_seq_cst); #endif } /** * Apply a mask, with bitwise `or`, and return the previous value, * atomically. * * @param m Mask. * * @return Previous value. */ T exchangeOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP T old; #pragma omp atomic capture { old = this->value; this->value |= value; } return old; #else return this->value.fetch_or(value, std::memory_order_seq_cst); #endif } /** * Apply a mask, with bitwise `and`, atomically. * * @param m Mask. */ void maskAnd(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value &= value; #else this->value.fetch_and(value, std::memory_order_seq_cst); #endif } /** * Apply a mask, with bitwise `or`, atomically. * * @param m Mask. */ void maskOr(const T& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value |= value; #else this->value.fetch_or(value, std::memory_order_seq_cst); #endif } /** * Increment the value by one, atomically, but without capturing the * current value. */ void increment() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update ++value; #else value.fetch_add(1, std::memory_order_seq_cst); #endif } /** * Decrement the value by one, atomically, but without capturing the * current value. */ void decrement() { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update --value; #else value.fetch_sub(1, std::memory_order_seq_cst); #endif } /** * Add to the value, atomically, but without capturing the current value. */ template<class U> void add(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value += value; #else this->value.fetch_add(value, std::memory_order_seq_cst); #endif } /** * Subtract from the value, atomically, but without capturing the current * value. */ template<class U> void subtract(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP #pragma omp atomic update this->value -= value; #else this->value.fetch_sub(value, std::memory_order_seq_cst); #endif } template<class U> T operator+=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value += value; result = this->value; } return result; #else return this->value.fetch_add(value, std::memory_order_seq_cst) + value; #endif } template<class U> T operator-=(const U& value) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { this->value -= value; result = this->value; } return result; #else return this->value.fetch_sub(value, std::memory_order_seq_cst) - value; #endif } T operator++() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { ++this->value; result = this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_seq_cst) + 1; #endif } T operator++(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; ++this->value; } return result; #else return this->value.fetch_add(1, std::memory_order_seq_cst); #endif } T operator--() { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { --this->value; result = this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_seq_cst) - 1; #endif } T operator--(int) { #if LIBBIRCH_ATOMIC_OPENMP T result; #pragma omp atomic capture { result = this->value; --this->value; } return result; #else return this->value.fetch_sub(1, std::memory_order_seq_cst); #endif } private: /** * Value. */ #if LIBBIRCH_ATOMIC_OPENMP T value; #else std::atomic<T> value; #endif }; } <|endoftext|>