text
stringlengths
54
60.6k
<commit_before>c850fcf4-2e4e-11e5-9284-b827eb9e62be<commit_msg>c855f5ba-2e4e-11e5-9284-b827eb9e62be<commit_after>c855f5ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f180e270-2e4d-11e5-9284-b827eb9e62be<commit_msg>f185f288-2e4d-11e5-9284-b827eb9e62be<commit_after>f185f288-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a654b6e0-2e4e-11e5-9284-b827eb9e62be<commit_msg>a659c806-2e4e-11e5-9284-b827eb9e62be<commit_after>a659c806-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3c6558d0-2e4d-11e5-9284-b827eb9e62be<commit_msg>3c6a53f8-2e4d-11e5-9284-b827eb9e62be<commit_after>3c6a53f8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <Magick++.h> #include "Fractal/Accumulator.h" #include "Fractal/Geometry.h" #include "Fractal/GravityIterator.h" #include "Fractal/Utilities.h" #include "Fractal/VectorSampler.h" namespace { const int width = 1024; const int height = 1024; const int supersample = 2; const int accum_scale = 1; const double damping = 5e-2; const double da = 1e-1; const double distance_cutoff = 1e-2; const double image_exposure = 1; const double accumulator_exposure = 1; void ProduceGravityFractal(const std::vector<Fractal::Vector2>& source_list, Magick::Image& image, Magick::Image& accum) { Fractal::Vector2 top_left; top_left(0) = 0.0; top_left(1) = 0.0; Fractal::Vector2 top_edge_vector; top_edge_vector(0) = 1.0; top_edge_vector(1) = 0.0; Fractal::Vector2 left_edge_vector; left_edge_vector(0) = 0.0; left_edge_vector(1) = 1.0; Fractal::Vector2 bottom_right = top_left + top_edge_vector + left_edge_vector;; const Fractal::Matrix44 transform = Fractal::Geometry::CreateBoundsTransform(top_left, bottom_right); Fractal::Accumulator accumulator(accum, transform); Fractal::GravityIterator< Fractal::Vector2 > iterator(&accumulator, source_list, da, damping, distance_cutoff); Fractal::VectorSampler< Fractal::Vector2 > sampler(top_left, top_edge_vector, left_edge_vector, &iterator); sampler.Render(image, image_exposure); accumulator.Render(accum, accumulator_exposure); } const Fractal::Vector2 RandomVector(void) { Fractal::Vector2 result; result(0) = Fractal::Utilities::Random(); result(1) = Fractal::Utilities::Random(); return result; } } int main(int argc, char* argv[]) { std::ios::sync_with_stdio(false); std::vector<Fractal::Vector2> masses; //for (int i = 0; i < sources; i++) { // masses.push_back( RandomVector() ); //} { Fractal::Vector2 pos; pos(0) = 0.5; pos(1) = 0.5; masses.push_back(pos); } { Fractal::Vector2 pos; pos(0) = 0.6; pos(1) = 0.5; masses.push_back(pos); } { Fractal::Vector2 pos; pos(0) = 0.5; pos(1) = 0.6; masses.push_back(pos); } Magick::Image image(Magick::Geometry(width * supersample, height * supersample), Magick::ColorRGB(1.0, 0.0, 0.0)); Magick::Image accum(Magick::Geometry(width * supersample * accum_scale, height * supersample * accum_scale), Magick::ColorRGB(1.0, 0.0, 0.0)); ProduceGravityFractal(masses, image, accum); image.scale(Magick::Geometry(width, height)); accum.scale(Magick::Geometry(width * accum_scale, height * accum_scale)); image.write("images/gravity_image.png"); accum.write("images/gravity_accum.png"); return 0; } <commit_msg>Changed the section rendered in the gravity fractal.<commit_after>#include <Magick++.h> #include "Fractal/Accumulator.h" #include "Fractal/Geometry.h" #include "Fractal/GravityIterator.h" #include "Fractal/Utilities.h" #include "Fractal/VectorSampler.h" namespace { const int width = 1024; const int height = 768; const int supersample = 2; const int accum_scale = 1; const double damping = 5e-2; const double da = 1e-1; const double distance_cutoff = 1e-2; const double image_exposure = 1; const double accumulator_exposure = 1; void ProduceGravityFractal(const std::vector<Fractal::Vector2>& source_list, Magick::Image& image, Magick::Image& accum) { Fractal::Vector2 top_left; top_left(0) = 149 / 1024.0; top_left(1) = 602 / 1024.0; Fractal::Vector2 top_edge_vector; top_edge_vector(0) = 36 / 1024.0; top_edge_vector(1) = 0.0; Fractal::Vector2 left_edge_vector; left_edge_vector(0) = 0.0; left_edge_vector(1) = 27 / 1024.0; Fractal::Vector2 bottom_right = top_left + top_edge_vector + left_edge_vector;; const Fractal::Matrix44 transform = Fractal::Geometry::CreateBoundsTransform(top_left, bottom_right); Fractal::Accumulator accumulator(accum, transform); Fractal::GravityIterator< Fractal::Vector2 > iterator(&accumulator, source_list, da, damping, distance_cutoff); Fractal::VectorSampler< Fractal::Vector2 > sampler(top_left, top_edge_vector, left_edge_vector, &iterator); sampler.Render(image, image_exposure); accumulator.Render(accum, accumulator_exposure); } const Fractal::Vector2 RandomVector(void) { Fractal::Vector2 result; result(0) = Fractal::Utilities::Random(); result(1) = Fractal::Utilities::Random(); return result; } } int main(int argc, char* argv[]) { std::ios::sync_with_stdio(false); std::vector<Fractal::Vector2> masses; //for (int i = 0; i < sources; i++) { // masses.push_back( RandomVector() ); //} { Fractal::Vector2 pos; pos(0) = 0.5; pos(1) = 0.5; masses.push_back(pos); } { Fractal::Vector2 pos; pos(0) = 0.6; pos(1) = 0.5; masses.push_back(pos); } { Fractal::Vector2 pos; pos(0) = 0.5; pos(1) = 0.6; masses.push_back(pos); } Magick::Image image(Magick::Geometry(width * supersample, height * supersample), Magick::ColorRGB(1.0, 0.0, 0.0)); Magick::Image accum(Magick::Geometry(width * supersample * accum_scale, height * supersample * accum_scale), Magick::ColorRGB(1.0, 0.0, 0.0)); ProduceGravityFractal(masses, image, accum); image.scale(Magick::Geometry(width, height)); accum.scale(Magick::Geometry(width * accum_scale, height * accum_scale)); image.write("images/gravity_image.tga"); accum.write("images/gravity_accum.tga"); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "log.h" #include <string> #include <ctime> #include <cstring> #include <uv.h> #include "thread_local.h" namespace redc { Scoped_Log_Init::Scoped_Log_Init() noexcept { init_log(); } Scoped_Log_Init::~Scoped_Log_Init() noexcept { uninit_log(); } REDC_THREAD_LOCAL uv_loop_t* loop_ = nullptr; Log_Severity out_level_ = Log_Severity::Debug; Log_Severity file_level_ = Log_Severity::Debug; bool good_file_ = false; uv_file file_; void init_log() noexcept { if(loop_) return; loop_ = new uv_loop_t; uv_loop_init(loop_); } void uninit_log() noexcept { if(!loop_) return; uv_loop_close(loop_); delete loop_; } void flush_log() noexcept { uv_run(loop_, UV_RUN_NOWAIT); } void flush_log_full() noexcept { uv_run(loop_, UV_RUN_DEFAULT); } void set_out_log_level(Log_Severity level) noexcept { // TODO: Add a mutex or something so we don't get that 1-in-1000000 data // race. TODO On second thought if this ever comes up in practice buy a // lotto ticket! out_level_ = level; } void set_file_log_level(Log_Severity level) noexcept { file_level_ = level; } void set_log_file(std::string fn) noexcept { // This only attempts to initialize loop_, but won't do anything if we call // it multiple times. init_log(); uv_fs_t fs_req; auto err = uv_fs_open(loop_, &fs_req, fn.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR, NULL); // I still don't really get the usage of uv_fs_open in synchroneous mode. // It seems like the return value is the result in fs_res but also an error // code if it's negative. if(err < 0) { log_e("Error opening log file: %", uv_strerror(err)); good_file_ = false; } else { file_ = fs_req.result; good_file_ = true; } } std::string format_time(const std::string& format) { // Stringify current time. std::string time; time.resize(25); std::time_t t = std::time(NULL); std::size_t count = std::strftime(&time[0], time.size(), format.c_str(), std::localtime(&t)); if(count == 0) { time = "badtime"; } time.resize(count); return time; } std::string severity_string(Log_Severity severity) noexcept { switch(severity) { case Log_Severity::Debug: return "debug: "; case Log_Severity::Info: return "info: "; case Log_Severity::Warning: return "warning: "; case Log_Severity::Error: return "error: "; default: return ""; } } constexpr char const* const RESET_C = "\x1b[0m"; constexpr char const* const ERROR_C = "\x1b[95m"; constexpr char const* const WARNING_C = "\x1b[91m"; constexpr char const* const INFO_C = "\x1b[92m"; constexpr char const* const DEBUG_C = "\x1b[96m"; std::string severity_color(Log_Severity severity) noexcept { switch(severity) { case Log_Severity::Debug: return DEBUG_C; case Log_Severity::Info: return INFO_C; case Log_Severity::Warning: return WARNING_C; case Log_Severity::Error: return ERROR_C; default: //return RESET_C; return ""; } } struct write_req_t { uv_fs_t req; uv_buf_t buf; }; void after_log(uv_fs_t* fs_req) { write_req_t* req = (write_req_t*) fs_req; // Uninitialize actual uv request. uv_fs_req_cleanup(&req->req); // Deallocate buffer. delete[] req->buf.base; // Deallocate request subclass. delete req; } void log_out(char* msg, std::size_t size) noexcept { if(!loop_) { delete[] msg; return; } // Make the request. write_req_t* req = new write_req_t; req->buf = uv_buf_init(msg, size); uv_fs_write(loop_, &req->req, 1, &req->buf, 1, -1, after_log); } void log_file(char* msg, std::size_t size) noexcept { // Bad file descriptor or bad loop if(!loop_ || !good_file_) { delete[] msg; return; } write_req_t* req = new write_req_t; req->buf = uv_buf_init(msg, size); uv_fs_write(loop_, &req->req, file_, &req->buf, 1, -1, after_log); } void log(Log_Severity severity, std::string msg) noexcept { // Create the final message. std::string time = format_time("%F|%T"); std::string msg_file = "("+time+"): "+severity_string(severity)+msg+"\n"; // If the severity of this message is greater than the output minimum. if((unsigned int) severity >= (unsigned int) file_level_) { char* msg_buf = new char[msg_file.size()]; std::memcpy(msg_buf, msg_file.data(), msg_file.size()); log_file(msg_buf, msg_file.size()); } if((unsigned int) severity >= (unsigned int) out_level_) { std::string msg_term = severity_color(severity) + msg_file + RESET_C; char* msg_buf = new char[msg_term.size()]; std::memcpy(msg_buf, msg_term.data(), msg_term.size()); log_out(msg_buf, msg_term.size()); } } } <commit_msg>Flush log before uninitializing<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "log.h" #include <string> #include <ctime> #include <cstring> #include <uv.h> #include "thread_local.h" namespace redc { Scoped_Log_Init::Scoped_Log_Init() noexcept { init_log(); } Scoped_Log_Init::~Scoped_Log_Init() noexcept { flush_log_full(); uninit_log(); } REDC_THREAD_LOCAL uv_loop_t* loop_ = nullptr; Log_Severity out_level_ = Log_Severity::Debug; Log_Severity file_level_ = Log_Severity::Debug; bool good_file_ = false; uv_file file_; void init_log() noexcept { if(loop_) return; loop_ = new uv_loop_t; uv_loop_init(loop_); } void uninit_log() noexcept { if(!loop_) return; uv_loop_close(loop_); delete loop_; } void flush_log() noexcept { uv_run(loop_, UV_RUN_NOWAIT); } void flush_log_full() noexcept { uv_run(loop_, UV_RUN_DEFAULT); } void set_out_log_level(Log_Severity level) noexcept { // TODO: Add a mutex or something so we don't get that 1-in-1000000 data // race. TODO On second thought if this ever comes up in practice buy a // lotto ticket! out_level_ = level; } void set_file_log_level(Log_Severity level) noexcept { file_level_ = level; } void set_log_file(std::string fn) noexcept { // This only attempts to initialize loop_, but won't do anything if we call // it multiple times. init_log(); uv_fs_t fs_req; auto err = uv_fs_open(loop_, &fs_req, fn.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR, NULL); // I still don't really get the usage of uv_fs_open in synchroneous mode. // It seems like the return value is the result in fs_res but also an error // code if it's negative. if(err < 0) { log_e("Error opening log file: %", uv_strerror(err)); good_file_ = false; } else { file_ = fs_req.result; good_file_ = true; } } std::string format_time(const std::string& format) { // Stringify current time. std::string time; time.resize(25); std::time_t t = std::time(NULL); std::size_t count = std::strftime(&time[0], time.size(), format.c_str(), std::localtime(&t)); if(count == 0) { time = "badtime"; } time.resize(count); return time; } std::string severity_string(Log_Severity severity) noexcept { switch(severity) { case Log_Severity::Debug: return "debug: "; case Log_Severity::Info: return "info: "; case Log_Severity::Warning: return "warning: "; case Log_Severity::Error: return "error: "; default: return ""; } } constexpr char const* const RESET_C = "\x1b[0m"; constexpr char const* const ERROR_C = "\x1b[95m"; constexpr char const* const WARNING_C = "\x1b[91m"; constexpr char const* const INFO_C = "\x1b[92m"; constexpr char const* const DEBUG_C = "\x1b[96m"; std::string severity_color(Log_Severity severity) noexcept { switch(severity) { case Log_Severity::Debug: return DEBUG_C; case Log_Severity::Info: return INFO_C; case Log_Severity::Warning: return WARNING_C; case Log_Severity::Error: return ERROR_C; default: //return RESET_C; return ""; } } struct write_req_t { uv_fs_t req; uv_buf_t buf; }; void after_log(uv_fs_t* fs_req) { write_req_t* req = (write_req_t*) fs_req; // Uninitialize actual uv request. uv_fs_req_cleanup(&req->req); // Deallocate buffer. delete[] req->buf.base; // Deallocate request subclass. delete req; } void log_out(char* msg, std::size_t size) noexcept { if(!loop_) { delete[] msg; return; } // Make the request. write_req_t* req = new write_req_t; req->buf = uv_buf_init(msg, size); uv_fs_write(loop_, &req->req, 1, &req->buf, 1, -1, after_log); } void log_file(char* msg, std::size_t size) noexcept { // Bad file descriptor or bad loop if(!loop_ || !good_file_) { delete[] msg; return; } write_req_t* req = new write_req_t; req->buf = uv_buf_init(msg, size); uv_fs_write(loop_, &req->req, file_, &req->buf, 1, -1, after_log); } void log(Log_Severity severity, std::string msg) noexcept { // Create the final message. std::string time = format_time("%F|%T"); std::string msg_file = "("+time+"): "+severity_string(severity)+msg+"\n"; // If the severity of this message is greater than the output minimum. if((unsigned int) severity >= (unsigned int) file_level_) { char* msg_buf = new char[msg_file.size()]; std::memcpy(msg_buf, msg_file.data(), msg_file.size()); log_file(msg_buf, msg_file.size()); } if((unsigned int) severity >= (unsigned int) out_level_) { std::string msg_term = severity_color(severity) + msg_file + RESET_C; char* msg_buf = new char[msg_term.size()]; std::memcpy(msg_buf, msg_term.data(), msg_term.size()); log_out(msg_buf, msg_term.size()); } } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include "csv/export.h" using namespace flint; namespace { void usage() { std::cerr << "usage: csv2isd INPUT OUTPUT" << std::endl; } } // namespace int main(int argc, char *argv[]) { if (argc == 2) { usage(); if ( std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") ) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } if (argc != 3) { usage(); return EXIT_FAILURE; } return (ExportIsdFromCsv(argv[1], argv[2])) ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>Fix csv2isd to exit with 0 at --help<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include "csv/export.h" using namespace flint; namespace { void usage() { std::cerr << "usage: csv2isd INPUT OUTPUT" << std::endl; } } // namespace int main(int argc, char *argv[]) { if (argc == 2) { usage(); if ( std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0 ) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } } if (argc != 3) { usage(); return EXIT_FAILURE; } return (ExportIsdFromCsv(argv[1], argv[2])) ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>// PUBLIC DOMAIN LICENSE: https://github.com/KjellKod/Concurrent/blob/master/LICENSE // // Repository: https://github.com/KjellKod/Concurrent // // Concurrent Wrapper // =============================== // Wrap "any" object to get concurrent access with asynchronous execution in FIFO order. // Published originally at : // http://kjellkod.wordpress.com/2014/04/07/concurrency-concurrent-wrapper/ // https://github.com/KjellKod/concurrent // // // 1) The "concurrent" can wrap ANY object // 2) All access to the concurrent is done though a lambda or using an easy pointer-to-member function call. // 3) All access call to the concurrent is done asynchronously and they are executed in FIFO order // 4) At scope exit all queued jobs has to finish before the concurrent goes out of scope // 5) A function call to a concurrent wrapped object can either be bundled for several actions within one asynchronous call // or it can be a single action within that asynchronous call // // ========================================= // 1) Single Action per Single Asynchronous call. KjellKod's g3log approach. // example usage: // struct Hello { void world() { cout << "Hello World" << endl; } }; // concurrent<Hello> ch; // ch.call(&world); // // // 2) Bundled actions per Single Asynchronous call. Herb Sutter's approach // Ref: http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism // The calls are made through a lambda. Multiple actions can be bundled. It also helps when there are overloads of the same function // concurrent<Hello> ch; // ch.lambda( [](Hello& msg){ // msg.world(); // msg.world(); // }); // // #pragma once #include <thread> #include <future> #include <functional> #include <type_traits> #include <memory> #include <stdexcept> #include "moveoncopy.hpp" #include "shared_queue.hpp" #include "std2_make_unique.hpp" // until available in C++14 namespace concurrent_helper { typedef std::function<void() > Callback; /** helper for non-void promises */ template<typename Fut, typename F, typename T> void set_value(std::promise<Fut>& p, F& f, T& t) { p.set_value(f(t)); } /** helper for setting promise/exception for promise of void */ template<typename F, typename T> void set_value(std::promise<void>& p, F& f, T& t) { f(t); p.set_value(); } } // namespace concurrent_helper /** * Basically a light weight active object. www.kjellkod.cc/active-object-with-cpp0x#TOC-Active-Object-the-C-11-way * all input happens in the background. At shutdown it exits only after all * queued requests are handled. */ template <class T> class concurrent { mutable std::unique_ptr<T> _worker; mutable shared_queue<concurrent_helper::Callback> _q; bool _done; // not atomic since only the thread is touching it std::thread _thd; void run() const { concurrent_helper::Callback call; while (!_done) { _q.wait_and_pop(call); call(); } } public: /** Constructs an unique_ptr<T> that is the background object * @param args to construct the unique_ptr<T> in-place */ template<typename ... Args> concurrent(Args&&... args) : concurrent(std2::make_unique<T>(std::forward<Args>(args)...)) {} /** * Moves in a unique_ptr<T> to be the background object. Starts up the worker thread * @param workerto act as the background object */ concurrent(std::unique_ptr<T> worker) : _worker(std::move(worker)) , _done(false) , _thd([ = ]{concurrent_helper::Callback call; while (_worker && !_done) { _q.wait_and_pop(call); call(); }}) { } /** * Clean shutdown. All pending messages are executed before the shutdown message is received */ virtual ~concurrent() { _q.push([ = ]{_done = true;}); if (_thd.joinable()) { _thd.join(); } _worker.reset(nullptr); } /** * @return whether the background object is still active. If the thread is stopped then * the background object will also be removed. */ bool empty() const { return !_worker; } /** * Following Herb Sutter's approach for a concurrent wrapper * using std::promise and setting the value using a lambda approach * * Example: struct Hello { void foo(){...} * concurrent<Hello> h; * h.lambda( [](Hello& object){ object.foo(); }; * * @param func lambda that has to take the wrapped object by reference as argument * the lambda will be called by the wrapper for the given lambda * @return std::future return of the lambda */ template<typename F> // typename std::result_of< decltype(func)(T*, Args...)>::type auto lambda(F func) const -> std::future<typename std::result_of<decltype(func)(T&)>::type> { typedef typename std::result_of < decltype(func)(T&)>::type result_type; auto p = std::make_shared < std::promise<result_type>>(); auto future_result = p->get_future(); if (empty()) { p->set_exception(std::make_exception_ptr(std::runtime_error("nullptr instantiated worker"))); } else { _q.push([ = ]{ try { concurrent_helper::set_value(*p, func, *(_worker.get())); } catch (...) { p->set_exception(std::current_exception()); } }); } return future_result; } /** * Following Kjell Hedström (KjellKod)'s approach for a concurrent wrapper in g3log * using std::packaged_task and and std::bind (since lambda currently cannot * deal with expanding parameter packs in a lambda). * * Example: struct Hello { void foo(){...} * concurrent<Hello> h; * h.call(&Hello::foo); * * @param func function pointer to the wrapped object * @param args parameter pack to executed by the function pointer. * @return std::future return of the background executed function */ template<typename AsyncCall, typename... Args> auto call(AsyncCall func, Args&&... args) const -> std::future<typename std::result_of< decltype(func)(T*, Args...)>::type> { typedef typename std::result_of <decltype(func)(T*, Args...)>::type result_type; typedef std::packaged_task<result_type()> task_type; if (empty()) { auto p = std::make_shared<std::promise<result_type>>(); std::future<result_type> future_result = p->get_future(); p->set_exception(std::make_exception_ptr(std::runtime_error("concurrent was cleared of background thread object"))); return future_result; } // weak compiler support for expanding parameter pack in a lambda. std::function is the work-around // With better compiler support it can be changed to: // auto bgCall = [&, args...]{ return (_worker.*func)(args...); }; auto bgCall = std::bind(func, _worker.get(), std::forward<Args>(args)...); task_type task(std::move(bgCall)); std::future<result_type> result = task.get_future(); _q.push(MoveOnCopy<task_type>(std::move(task))); return std::move(result); } }; <commit_msg>Clarified error message<commit_after>// PUBLIC DOMAIN LICENSE: https://github.com/KjellKod/Concurrent/blob/master/LICENSE // // Repository: https://github.com/KjellKod/Concurrent // // Concurrent Wrapper // =============================== // Wrap "any" object to get concurrent access with asynchronous execution in FIFO order. // Published originally at : // http://kjellkod.wordpress.com/2014/04/07/concurrency-concurrent-wrapper/ // https://github.com/KjellKod/concurrent // // // 1) The "concurrent" can wrap ANY object // 2) All access to the concurrent is done though a lambda or using an easy pointer-to-member function call. // 3) All access call to the concurrent is done asynchronously and they are executed in FIFO order // 4) At scope exit all queued jobs has to finish before the concurrent goes out of scope // 5) A function call to a concurrent wrapped object can either be bundled for several actions within one asynchronous call // or it can be a single action within that asynchronous call // // ========================================= // 1) Single Action per Single Asynchronous call. KjellKod's g3log approach. // example usage: // struct Hello { void world() { cout << "Hello World" << endl; } }; // concurrent<Hello> ch; // ch.call(&world); // // // 2) Bundled actions per Single Asynchronous call. Herb Sutter's approach // Ref: http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism // The calls are made through a lambda. Multiple actions can be bundled. It also helps when there are overloads of the same function // concurrent<Hello> ch; // ch.lambda( [](Hello& msg){ // msg.world(); // msg.world(); // }); // // #pragma once #include <thread> #include <future> #include <functional> #include <type_traits> #include <memory> #include <stdexcept> #include "moveoncopy.hpp" #include "shared_queue.hpp" #include "std2_make_unique.hpp" // until available in C++14 namespace concurrent_helper { typedef std::function<void() > Callback; /** helper for non-void promises */ template<typename Fut, typename F, typename T> void set_value(std::promise<Fut>& p, F& f, T& t) { p.set_value(f(t)); } /** helper for setting promise/exception for promise of void */ template<typename F, typename T> void set_value(std::promise<void>& p, F& f, T& t) { f(t); p.set_value(); } } // namespace concurrent_helper /** * Basically a light weight active object. www.kjellkod.cc/active-object-with-cpp0x#TOC-Active-Object-the-C-11-way * all input happens in the background. At shutdown it exits only after all * queued requests are handled. */ template <class T> class concurrent { mutable std::unique_ptr<T> _worker; mutable shared_queue<concurrent_helper::Callback> _q; bool _done; // not atomic since only the thread is touching it std::thread _thd; void run() const { concurrent_helper::Callback call; while (!_done) { _q.wait_and_pop(call); call(); } } public: /** Constructs an unique_ptr<T> that is the background object * @param args to construct the unique_ptr<T> in-place */ template<typename ... Args> concurrent(Args&&... args) : concurrent(std2::make_unique<T>(std::forward<Args>(args)...)) {} /** * Moves in a unique_ptr<T> to be the background object. Starts up the worker thread * @param workerto act as the background object */ concurrent(std::unique_ptr<T> worker) : _worker(std::move(worker)) , _done(false) , _thd([ = ]{concurrent_helper::Callback call; while (_worker && !_done) { _q.wait_and_pop(call); call(); }}) { } /** * Clean shutdown. All pending messages are executed before the shutdown message is received */ virtual ~concurrent() { _q.push([ = ]{_done = true;}); if (_thd.joinable()) { _thd.join(); } _worker.reset(nullptr); } /** * @return whether the background object is still active. If the thread is stopped then * the background object will also be removed. */ bool empty() const { return !_worker; } /** * Following Herb Sutter's approach for a concurrent wrapper * using std::promise and setting the value using a lambda approach * * Example: struct Hello { void foo(){...} * concurrent<Hello> h; * h.lambda( [](Hello& object){ object.foo(); }; * * @param func lambda that has to take the wrapped object by reference as argument * the lambda will be called by the wrapper for the given lambda * @return std::future return of the lambda */ template<typename F> // typename std::result_of< decltype(func)(T*, Args...)>::type auto lambda(F func) const -> std::future<typename std::result_of<decltype(func)(T&)>::type> { typedef typename std::result_of < decltype(func)(T&)>::type result_type; auto p = std::make_shared < std::promise<result_type>>(); auto future_result = p->get_future(); if (empty()) { p->set_exception(std::make_exception_ptr(std::runtime_error("nullptr instantiated worker"))); } else { _q.push([ = ]{ try { concurrent_helper::set_value(*p, func, *(_worker.get())); } catch (...) { p->set_exception(std::current_exception()); } }); } return future_result; } /** * Following Kjell Hedström (KjellKod)'s approach for a concurrent wrapper in g3log * using std::packaged_task and and std::bind (since lambda currently cannot * deal with expanding parameter packs in a lambda). * * Example: struct Hello { void foo(){...} * concurrent<Hello> h; * h.call(&Hello::foo); * * @param func function pointer to the wrapped object * @param args parameter pack to executed by the function pointer. * @return std::future return of the background executed function */ template<typename AsyncCall, typename... Args> auto call(AsyncCall func, Args&&... args) const -> std::future<typename std::result_of< decltype(func)(T*, Args...)>::type> { typedef typename std::result_of <decltype(func)(T*, Args...)>::type result_type; typedef std::packaged_task<result_type()> task_type; if (empty()) { auto p = std::make_shared<std::promise<result_type>>(); std::future<result_type> future_result = p->get_future(); p->set_exception(std::make_exception_ptr(std::runtime_error("nullptr instantiated worker"))); return future_result; } // weak compiler support for expanding parameter pack in a lambda. std::function is the work-around // With better compiler support it can be changed to: // auto bgCall = [&, args...]{ return (_worker.*func)(args...); }; auto bgCall = std::bind(func, _worker.get(), std::forward<Args>(args)...); task_type task(std::move(bgCall)); std::future<result_type> result = task.get_future(); _q.push(MoveOnCopy<task_type>(std::move(task))); return std::move(result); } }; <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stats_table.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/trace_event.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/http/http_cache.h" #include "net/socket/ssl_test_util.h" #include "net/url_request/url_request_context.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/extensions/v8/gc_extension.h" #include "webkit/extensions/v8/heap_profiler_extension.h" #include "webkit/extensions/v8/playback_extension.h" #include "webkit/extensions/v8/profiler_extension.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" #include "webkit/tools/test_shell/test_shell_webkit_init.h" static const size_t kPathBufSize = 2048; using WebKit::WebScriptController; namespace { // StatsTable initialization parameters. const char* const kStatsFilePrefix = "testshell_"; int kStatsFileThreads = 20; int kStatsFileCounters = 200; } // namespace int main(int argc, char* argv[]) { base::EnableInProcessStackDumping(); base::EnableTerminationOnHeapCorruption(); // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; TestShellPlatformDelegate::PreflightArgs(&argc, &argv); CommandLine::Init(argc, argv); const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); TestShellPlatformDelegate platform(parsed_command_line); if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) TestShell::ShowStartupDebuggingDialog(); if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) { exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1); } // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = ( base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme); bool classic_theme = parsed_command_line.HasSwitch(test_shell::kClassicTheme); #if defined(OS_WIN) bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) || parsed_command_line.HasSwitch(test_shell::kGenericTheme); #else // Stop compiler warnings about unused variables. ux_theme = ux_theme; #endif bool enable_gp_fault_error_box = false; enable_gp_fault_error_box = parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox); TestShell::InitLogging(suppress_error_dialogs, layout_test_mode, enable_gp_fault_error_box); // Initialize WebKit for this scope. TestShellWebKitInit test_shell_webkit_init(layout_test_mode); // Suppress abort message in v8 library in debugging mode (but not // actually under a debugger). V8 calls abort() when it hits // assertion errors. if (suppress_error_dialogs) { platform.SuppressErrorReporting(); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; // This is a special mode where JS helps the browser implement // playback/record mode. Generally, in this mode, some functions // of client-side randomness are removed. For example, in // this mode Math.random() and Date.getTime() may not return // values which vary. bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); FilePath cache_path = parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir); // If the cache_path is empty and it's layout_test_mode, leave it empty // so we use an in-memory cache. This makes running multiple test_shells // in parallel less flaky. if (cache_path.empty() && !layout_test_mode) { PathService::Get(base::DIR_EXE, &cache_path); cache_path = cache_path.AppendASCII("cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode, layout_test_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(TestShell::NetResourceProvider); // On Linux, load the test root certificate. net::TestServerLauncher ssl_util; ssl_util.LoadTestRootCert(); platform.InitializeGUI(); TestShell::InitializeTestShell(layout_test_mode); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. #if defined(OS_WIN) TestShellWebTheme::Engine engine; #endif if (classic_theme) platform.SelectUnifiedTheme(); #if defined(OS_WIN) if (generic_theme) test_shell_webkit_init.SetThemeEngine(&engine); #endif if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str()))); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Treat the first loose value as the initial URL to open. GURL starting_url; // Default to a homepage if we're interactive. if (!layout_test_mode) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("webkit"); path = path.AppendASCII("data"); path = path.AppendASCII("test_shell"); path = path.AppendASCII("index.html"); starting_url = net::FilePathToFileURL(path); } std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues(); if (loose_values.size() > 0) { GURL url(WideToUTF16Hack(loose_values[0])); if (url.is_valid()) { starting_url = url; } else { // Treat as a file path starting_url = net::FilePathToFileURL(FilePath::FromWStringHack(loose_values[0])); } } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. js_flags += L" --expose-gc"; webkit_glue::SetJavaScriptFlags(js_flags); // Expose GCController to JavaScript. WebScriptController::registerExtension(extensions_v8::GCExtension::Get()); if (parsed_command_line.HasSwitch(test_shell::kProfiler)) { WebScriptController::registerExtension( extensions_v8::ProfilerExtension::Get()); } if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) { WebScriptController::registerExtension( extensions_v8::HeapProfilerExtension::Get()); } // Load and initialize the stats table. Attempt to construct a somewhat // unique name to isolate separate instances from each other. StatsTable *table = new StatsTable( // truncate the random # to 32 bits for the benefit of Mac OS X, to // avoid tripping over its maximum shared memory segment name length kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL), kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(starting_url, &shell)) { if (record_mode || playback_mode) { platform.SetWindowPositionForRecording(shell); WebScriptController::registerExtension( extensions_v8::PlaybackExtension::Get()); } shell->Show(WebKit::WebNavigationPolicyNewWindow); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { FilePath script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); script_path = script_path.AppendASCII("script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (!starting_url.is_valid()) { // Watch stdin for URLs. char filenameBuffer[kPathBufSize]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { // When running layout tests we pass new line separated // tests to TestShell. Each line is a space separated list // of filename, timeout and expected pixel hash. The timeout // and the pixel hash are optional. char* newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; params.test_url = strtok(filenameBuffer, " "); // Set the current path to the directory that contains the test // files. This is because certain test file may use the relative // path. GURL test_url(params.test_url); FilePath test_file_path; net::FileURLToFilePath(test_url, &test_file_path); file_util::SetCurrentDirectory(test_file_path.DirName()); int old_timeout_ms = TestShell::GetLayoutTestTimeout(); char* timeout = strtok(NULL, " "); if (timeout) { TestShell::SetFileTestTimeout(atoi(timeout)); char* pixel_hash = strtok(NULL, " "); if (pixel_hash) params.pixel_hash = pixel_hash; } if (!TestShell::RunFileTest(params)) break; TestShell::SetFileTestTimeout(old_timeout_ms); } } else { // TODO(ojan): Provide a way for run-singly tests to pass // in a hash and then set params.pixel_hash here. params.test_url = WideToUTF8(loose_values[0]); TestShell::RunFileTest(params); } shell->CallJSGC(); shell->CallJSGC(); // When we finish the last test, cleanup the LayoutTestController. // It may have references to not-yet-cleaned up windows. By // cleaning up here we help purify reports. shell->ResetTestController(); // Flush any remaining messages before we kill ourselves. // http://code.google.com/p/chromium/issues/detail?id=9500 MessageLoop::current()->RunAllPending(); delete shell; } else { MessageLoop::current()->Run(); } // Flush any remaining messages. This ensures that any accumulated // Task objects get destroyed before we exit, which avoids noise in // purify leak-test results. MessageLoop::current()->RunAllPending(); if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; return 0; } <commit_msg>[Mac/Linux] clean up the shmem file at the end of each testshell run. - Mac/Linux back shmem with a file, but the file isn't cleaned up (since it could be shared), this pulls over the same basic code we used in chrome_test_suite to clean up the files there also so they don't leak a fill up the bots.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stats_table.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/trace_event.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/http/http_cache.h" #include "net/socket/ssl_test_util.h" #include "net/url_request/url_request_context.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/extensions/v8/gc_extension.h" #include "webkit/extensions/v8/heap_profiler_extension.h" #include "webkit/extensions/v8/playback_extension.h" #include "webkit/extensions/v8/profiler_extension.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" #include "webkit/tools/test_shell/test_shell_webkit_init.h" static const size_t kPathBufSize = 2048; using WebKit::WebScriptController; namespace { // StatsTable initialization parameters. const char* const kStatsFilePrefix = "testshell_"; int kStatsFileThreads = 20; int kStatsFileCounters = 200; void RemoveSharedMemoryFile(std::string& filename) { // Stats uses SharedMemory under the hood. On posix, this results in a file // on disk. #if defined(OS_POSIX) base::SharedMemory memory; memory.Delete(UTF8ToWide(filename)); #endif } } // namespace int main(int argc, char* argv[]) { base::EnableInProcessStackDumping(); base::EnableTerminationOnHeapCorruption(); // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; TestShellPlatformDelegate::PreflightArgs(&argc, &argv); CommandLine::Init(argc, argv); const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); TestShellPlatformDelegate platform(parsed_command_line); if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) TestShell::ShowStartupDebuggingDialog(); if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) { exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1); } // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = ( base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme); bool classic_theme = parsed_command_line.HasSwitch(test_shell::kClassicTheme); #if defined(OS_WIN) bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) || parsed_command_line.HasSwitch(test_shell::kGenericTheme); #else // Stop compiler warnings about unused variables. ux_theme = ux_theme; #endif bool enable_gp_fault_error_box = false; enable_gp_fault_error_box = parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox); TestShell::InitLogging(suppress_error_dialogs, layout_test_mode, enable_gp_fault_error_box); // Initialize WebKit for this scope. TestShellWebKitInit test_shell_webkit_init(layout_test_mode); // Suppress abort message in v8 library in debugging mode (but not // actually under a debugger). V8 calls abort() when it hits // assertion errors. if (suppress_error_dialogs) { platform.SuppressErrorReporting(); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; // This is a special mode where JS helps the browser implement // playback/record mode. Generally, in this mode, some functions // of client-side randomness are removed. For example, in // this mode Math.random() and Date.getTime() may not return // values which vary. bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); FilePath cache_path = parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir); // If the cache_path is empty and it's layout_test_mode, leave it empty // so we use an in-memory cache. This makes running multiple test_shells // in parallel less flaky. if (cache_path.empty() && !layout_test_mode) { PathService::Get(base::DIR_EXE, &cache_path); cache_path = cache_path.AppendASCII("cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode, layout_test_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(TestShell::NetResourceProvider); // On Linux, load the test root certificate. net::TestServerLauncher ssl_util; ssl_util.LoadTestRootCert(); platform.InitializeGUI(); TestShell::InitializeTestShell(layout_test_mode); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. #if defined(OS_WIN) TestShellWebTheme::Engine engine; #endif if (classic_theme) platform.SelectUnifiedTheme(); #if defined(OS_WIN) if (generic_theme) test_shell_webkit_init.SetThemeEngine(&engine); #endif if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str()))); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Treat the first loose value as the initial URL to open. GURL starting_url; // Default to a homepage if we're interactive. if (!layout_test_mode) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("webkit"); path = path.AppendASCII("data"); path = path.AppendASCII("test_shell"); path = path.AppendASCII("index.html"); starting_url = net::FilePathToFileURL(path); } std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues(); if (loose_values.size() > 0) { GURL url(WideToUTF16Hack(loose_values[0])); if (url.is_valid()) { starting_url = url; } else { // Treat as a file path starting_url = net::FilePathToFileURL(FilePath::FromWStringHack(loose_values[0])); } } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. js_flags += L" --expose-gc"; webkit_glue::SetJavaScriptFlags(js_flags); // Expose GCController to JavaScript. WebScriptController::registerExtension(extensions_v8::GCExtension::Get()); if (parsed_command_line.HasSwitch(test_shell::kProfiler)) { WebScriptController::registerExtension( extensions_v8::ProfilerExtension::Get()); } if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) { WebScriptController::registerExtension( extensions_v8::HeapProfilerExtension::Get()); } // Load and initialize the stats table. Attempt to construct a somewhat // unique name to isolate separate instances from each other. // truncate the random # to 32 bits for the benefit of Mac OS X, to // avoid tripping over its maximum shared memory segment name length std::string stats_filename = kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL); RemoveSharedMemoryFile(stats_filename); StatsTable *table = new StatsTable(stats_filename, kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(starting_url, &shell)) { if (record_mode || playback_mode) { platform.SetWindowPositionForRecording(shell); WebScriptController::registerExtension( extensions_v8::PlaybackExtension::Get()); } shell->Show(WebKit::WebNavigationPolicyNewWindow); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { FilePath script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); script_path = script_path.AppendASCII("script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (!starting_url.is_valid()) { // Watch stdin for URLs. char filenameBuffer[kPathBufSize]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { // When running layout tests we pass new line separated // tests to TestShell. Each line is a space separated list // of filename, timeout and expected pixel hash. The timeout // and the pixel hash are optional. char* newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; params.test_url = strtok(filenameBuffer, " "); // Set the current path to the directory that contains the test // files. This is because certain test file may use the relative // path. GURL test_url(params.test_url); FilePath test_file_path; net::FileURLToFilePath(test_url, &test_file_path); file_util::SetCurrentDirectory(test_file_path.DirName()); int old_timeout_ms = TestShell::GetLayoutTestTimeout(); char* timeout = strtok(NULL, " "); if (timeout) { TestShell::SetFileTestTimeout(atoi(timeout)); char* pixel_hash = strtok(NULL, " "); if (pixel_hash) params.pixel_hash = pixel_hash; } if (!TestShell::RunFileTest(params)) break; TestShell::SetFileTestTimeout(old_timeout_ms); } } else { // TODO(ojan): Provide a way for run-singly tests to pass // in a hash and then set params.pixel_hash here. params.test_url = WideToUTF8(loose_values[0]); TestShell::RunFileTest(params); } shell->CallJSGC(); shell->CallJSGC(); // When we finish the last test, cleanup the LayoutTestController. // It may have references to not-yet-cleaned up windows. By // cleaning up here we help purify reports. shell->ResetTestController(); // Flush any remaining messages before we kill ourselves. // http://code.google.com/p/chromium/issues/detail?id=9500 MessageLoop::current()->RunAllPending(); delete shell; } else { MessageLoop::current()->Run(); } // Flush any remaining messages. This ensures that any accumulated // Task objects get destroyed before we exit, which avoids noise in // purify leak-test results. MessageLoop::current()->RunAllPending(); if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; RemoveSharedMemoryFile(stats_filename); return 0; } <|endoftext|>
<commit_before>// @(#)root/roostats:$Id: LikelihoodIntervalPlot.h 26427 2009-05-20 15:45:36Z pellicci $ /************************************************************************* * Project: RooStats * * Package: RooFit/RooStats * * Authors: * * Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke * ************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //____________________________________________________________________ /* LikelihoodIntervalPlot : This class provides simple and straightforward utilities to plot a LikelihoodInterval object. */ #include "RooStats/LikelihoodIntervalPlot.h" #include <algorithm> #include <iostream> #include "TROOT.h" #include "TMath.h" #include "TLine.h" #include "TObjArray.h" #include "TList.h" #include "TGraph.h" #include "TPad.h" #include "RooRealVar.h" #include "RooPlot.h" /// ClassImp for building the THtml documentation of the class ClassImp(RooStats::LikelihoodIntervalPlot); using namespace RooStats; //_______________________________________________________ LikelihoodIntervalPlot::LikelihoodIntervalPlot() { // LikelihoodIntervalPlot default constructor fInterval = 0; fNdimPlot = 0; fParamsPlot = 0; fColor = 0; fFillStyle = 4050; // half transparent fLineColor = 0; fMaximum = 2.; } //_______________________________________________________ LikelihoodIntervalPlot::LikelihoodIntervalPlot(LikelihoodInterval* theInterval) { // LikelihoodIntervalPlot constructor fInterval = theInterval; fParamsPlot = fInterval->GetParameters(); fNdimPlot = fParamsPlot->getSize(); fColor = kBlue; fLineColor = kGreen; fFillStyle = 4050; // half transparent fMaximum = 2.; } //_______________________________________________________ LikelihoodIntervalPlot::~LikelihoodIntervalPlot() { // LikelihoodIntervalPlot destructor } //_____________________________________________________________________________ void LikelihoodIntervalPlot::SetLikelihoodInterval(LikelihoodInterval* theInterval) { fInterval = theInterval; fParamsPlot = fInterval->GetParameters(); fNdimPlot = fParamsPlot->getSize(); return; } //_____________________________________________________________________________ void LikelihoodIntervalPlot::SetPlotParameters(const RooArgSet *params) { fNdimPlot = params->getSize(); fParamsPlot = (RooArgSet*) params->clone((std::string(params->GetName())+"_clone").c_str()); return; } //_____________________________________________________________________________ void LikelihoodIntervalPlot::Draw(const Option_t *options) { if(fNdimPlot > 2){ std::cout << "LikelihoodIntervalPlot::Draw(" << GetName() << ") ERROR: contours for more than 2 dimensions not implemented!" << std::endl; return; } TIter it = fParamsPlot->createIterator(); RooRealVar *myparam = (RooRealVar*)it.Next(); // RooAbsReal* newProfile = fInterval->GetLikelihoodRatio()->createProfile(*fParamsPlot); RooAbsReal* newProfile = fInterval->GetLikelihoodRatio(); if(fNdimPlot == 1){ const Double_t xcont_min = fInterval->LowerLimit(*myparam); const Double_t xcont_max = fInterval->UpperLimit(*myparam); RooRealVar* myarg = (RooRealVar *) newProfile->getVariables()->find(myparam->GetName()); RooPlot *frame = myarg->frame(); frame->SetTitle(GetTitle()); frame->GetYaxis()->SetTitle("- log #lambda"); // frame->GetYaxis()->SetTitle("- log profile likelihood ratio"); newProfile->plotOn(frame); frame->SetMaximum(fMaximum); frame->SetMinimum(0.); // Double_t debug_var= newProfile->getVal(); myarg->setVal(xcont_min); //const Double_t Yat_Xmin = newProfile->getVal(); myarg->setVal(xcont_max); const Double_t Yat_Xmax = newProfile->getVal(); TLine *Yline_cutoff = new TLine(myarg->getMin(),Yat_Xmax,myarg->getMax(),Yat_Xmax); TLine *Yline_min = new TLine(xcont_min,0.,xcont_min,Yat_Xmax); TLine *Yline_max = new TLine(xcont_max,0.,xcont_max,Yat_Xmax); //std::cout <<"debug " << xcont_min << " " << xcont_max << " " //<< Yat_Xmin << " " << Yat_Xmax << std::endl; Yline_cutoff->SetLineColor(fLineColor); Yline_min->SetLineColor(fLineColor); Yline_max->SetLineColor(fLineColor); frame->addObject(Yline_cutoff); frame->addObject(Yline_min); frame->addObject(Yline_max); frame->Draw(options); return; } else if(fNdimPlot == 2){ RooRealVar *myparamY = (RooRealVar*)it.Next(); TH2F* hist2D = (TH2F*)newProfile->createHistogram("_hist2D",*myparamY,RooFit::YVar(*myparam),RooFit::Binning(40),RooFit::Scaling(kFALSE)); hist2D->SetTitle(GetTitle()); hist2D->SetStats(kFALSE); Double_t cont_level = TMath::ChisquareQuantile(fInterval->ConfidenceLevel(),fNdimPlot); // level for -2log LR cont_level = cont_level/2; // since we are plotting -log LR hist2D->SetContour(1,&cont_level); hist2D->SetFillColor(fColor); hist2D->SetFillStyle(fFillStyle); hist2D->SetLineColor(fLineColor); TString tmpOpt(options); if(!tmpOpt.Contains("CONT")) tmpOpt.Append("CONT"); if(!tmpOpt.Contains("LIST")) tmpOpt.Append("LIST"); // if you want the contour TGraphs hist2D->Draw(tmpOpt.Data()); // hist2D->Draw("cont2,list,same"); gPad->Update(); // needed for get list of specials // get TGraphs and add them // gROOT->GetListOfSpecials()->Print(); TObjArray *contours = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); if(contours){ TList *list = (TList*)contours->At(0); TGraph *gr1 = (TGraph*)list->First(); gr1->SetLineColor(kBlack); gr1->SetLineStyle(kDashed); gr1->Draw("same"); } else{ std::cout << "no countours found in ListOfSpecials" << std::endl; } return; } return; } <commit_msg>fix Profile likelihood plot by using a TF1 for drawing a profileLL<commit_after>// @(#)root/roostats:$Id: LikelihoodIntervalPlot.h 26427 2009-05-20 15:45:36Z pellicci $ /************************************************************************* * Project: RooStats * * Package: RooFit/RooStats * * Authors: * * Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke * ************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //____________________________________________________________________ /* LikelihoodIntervalPlot : This class provides simple and straightforward utilities to plot a LikelihoodInterval object. */ #include "RooStats/LikelihoodIntervalPlot.h" #include <algorithm> #include <iostream> #include "TROOT.h" #include "TMath.h" #include "TLine.h" #include "TObjArray.h" #include "TList.h" #include "TGraph.h" #include "TPad.h" #include "RooRealVar.h" #include "RooPlot.h" //#include "RooProfileLL.h" #include "TF1.h" /// ClassImp for building the THtml documentation of the class ClassImp(RooStats::LikelihoodIntervalPlot); using namespace RooStats; //_______________________________________________________ LikelihoodIntervalPlot::LikelihoodIntervalPlot() { // LikelihoodIntervalPlot default constructor fInterval = 0; fNdimPlot = 0; fParamsPlot = 0; fColor = 0; fFillStyle = 4050; // half transparent fLineColor = 0; fMaximum = 2.; } //_______________________________________________________ LikelihoodIntervalPlot::LikelihoodIntervalPlot(LikelihoodInterval* theInterval) { // LikelihoodIntervalPlot constructor fInterval = theInterval; fParamsPlot = fInterval->GetParameters(); fNdimPlot = fParamsPlot->getSize(); fColor = kBlue; fLineColor = kGreen; fFillStyle = 4050; // half transparent fMaximum = 2.; } //_______________________________________________________ LikelihoodIntervalPlot::~LikelihoodIntervalPlot() { // LikelihoodIntervalPlot destructor } //_____________________________________________________________________________ void LikelihoodIntervalPlot::SetLikelihoodInterval(LikelihoodInterval* theInterval) { fInterval = theInterval; fParamsPlot = fInterval->GetParameters(); fNdimPlot = fParamsPlot->getSize(); return; } //_____________________________________________________________________________ void LikelihoodIntervalPlot::SetPlotParameters(const RooArgSet *params) { fNdimPlot = params->getSize(); fParamsPlot = (RooArgSet*) params->clone((std::string(params->GetName())+"_clone").c_str()); return; } //_____________________________________________________________________________ void LikelihoodIntervalPlot::Draw(const Option_t *options) { if(fNdimPlot > 2){ std::cout << "LikelihoodIntervalPlot::Draw(" << GetName() << ") ERROR: contours for more than 2 dimensions not implemented!" << std::endl; return; } TIter it = fParamsPlot->createIterator(); RooRealVar *myparam = (RooRealVar*)it.Next(); // RooAbsReal* newProfile = fInterval->GetLikelihoodRatio()->createProfile(*fParamsPlot); RooAbsReal* newProfile = fInterval->GetLikelihoodRatio(); if(fNdimPlot == 1){ // RooArgList fittedParams(((RooProfileLL*) newProfile)->bestFitParams()); const Double_t xcont_min = fInterval->LowerLimit(*myparam); const Double_t xcont_max = fInterval->UpperLimit(*myparam); // std::cout << "BEST FIT PARAMETERS = " << std::endl; // for (int i = 0; i < fittedParams.getSize(); ++i) // fittedParams[i].Print(); RooRealVar* myarg = (RooRealVar *) newProfile->getVariables()->find(myparam->GetName()); //myarg->Print(); // myarg->setVal(xcont_min); // std::cout << " Profile for x = " << xcont_min << " PLL = " << newProfile->getVal() << std::endl; // myarg->setVal(xcont_max); // std::cout << " Profile for x = " << xcont_max << " PLL = " << newProfile->getVal() << std::endl; // RooPlot *frame = myarg->frame(); // frame->SetTitle(GetTitle()); // frame->GetYaxis()->SetTitle("- log #lambda"); // // frame->GetYaxis()->SetTitle("- log profile likelihood ratio"); // newProfile->plotOn(frame); // frame->SetMaximum(fMaximum); // frame->SetMinimum(0.); TF1 * f1 = newProfile->asTF(*myarg); f1->SetTitle("- log profile likelihood ratio"); TString name = TString(GetName()) + TString("_PLL_") + TString(myarg->GetName()); f1->SetName(name); // set range for value of fMaximum // use a clone function which is sampled to avoid many profilell evaluations TF1 * tmp = (TF1*) f1->Clone(); double x0 = tmp->GetX(0, myarg->getMin(), myarg->getMax()); double x1 = tmp->GetX(fMaximum, myarg->getMin(), x0); double x2 = tmp->GetX(fMaximum, x0, myarg->getMax()); delete tmp; f1->SetMaximum(fMaximum); f1->SetRange(x1,x2); f1->SetLineColor(kBlue); f1->GetXaxis()->SetTitle(myarg->GetName()); f1->GetYaxis()->SetTitle("- log #lambda"); f1->Draw(); // frame->addObject(f1); //f1->Draw("SAME"); // Double_t debug_var= newProfile->getVal(); // myarg->setVal(xcont_min); // const Double_t Yat_Xmin = newProfile->getVal(); myarg->setVal(xcont_max); const Double_t Yat_Xmax = newProfile->getVal(); TLine *Yline_cutoff = new TLine(x1,Yat_Xmax,x2,Yat_Xmax); TLine *Yline_min = new TLine(xcont_min,0.,xcont_min,Yat_Xmax); TLine *Yline_max = new TLine(xcont_max,0.,xcont_max,Yat_Xmax); //std::cout <<"debug " << xcont_min << " " << xcont_max << " " //<< Yat_Xmin << " " << Yat_Xmax << std::endl; Yline_cutoff->SetLineColor(fLineColor); Yline_min->SetLineColor(fLineColor); Yline_max->SetLineColor(fLineColor); Yline_cutoff->Draw(); Yline_min->Draw(); Yline_max->Draw(); // frame->addObject(Yline_cutoff); // frame->addObject(Yline_min); // frame->addObject(Yline_max); // frame->Draw(options); return; } else if(fNdimPlot == 2){ RooRealVar *myparamY = (RooRealVar*)it.Next(); TH2F* hist2D = (TH2F*)newProfile->createHistogram("_hist2D",*myparamY,RooFit::YVar(*myparam),RooFit::Binning(40),RooFit::Scaling(kFALSE)); hist2D->SetTitle(GetTitle()); hist2D->SetStats(kFALSE); Double_t cont_level = TMath::ChisquareQuantile(fInterval->ConfidenceLevel(),fNdimPlot); // level for -2log LR cont_level = cont_level/2; // since we are plotting -log LR hist2D->SetContour(1,&cont_level); hist2D->SetFillColor(fColor); hist2D->SetFillStyle(fFillStyle); hist2D->SetLineColor(fLineColor); TString tmpOpt(options); if(!tmpOpt.Contains("CONT")) tmpOpt.Append("CONT"); if(!tmpOpt.Contains("LIST")) tmpOpt.Append("LIST"); // if you want the contour TGraphs hist2D->Draw(tmpOpt.Data()); // hist2D->Draw("cont2,list,same"); gPad->Update(); // needed for get list of specials // get TGraphs and add them // gROOT->GetListOfSpecials()->Print(); TObjArray *contours = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours"); if(contours){ TList *list = (TList*)contours->At(0); TGraph *gr1 = (TGraph*)list->First(); gr1->SetLineColor(kBlack); gr1->SetLineStyle(kDashed); gr1->Draw("same"); } else{ std::cout << "no countours found in ListOfSpecials" << std::endl; } return; } return; } <|endoftext|>
<commit_before>#include <Python.h> #include <string> #include <iostream> #include <TTree.h> #include <TFile.h> #include <TChain.h> #include <TLeaf.h> #include <map> #include <numpy/arrayobject.h> #include <cassert> #include <set> struct TypeInfo{ PyObject* nptype; int size;//in bytes TypeInfo(const TypeInfo& t):nptype(t.nptype),size(t.size){Py_INCREF(nptype);} TypeInfo(const char* nptype, int size):nptype(PyString_FromString(nptype)),size(size){}; ~TypeInfo(){Py_DECREF(nptype);} }; static std::map<std::string, TypeInfo> root_typemap; //map roottype string to TypeInfo Object void init_roottypemap(){ using std::make_pair; //TODO: correct this one so it doesn't depend on system // from TTree doc // - C : a character string terminated by the 0 character // - B : an 8 bit signed integer (Char_t) // - b : an 8 bit unsigned integer (UChar_t) // - S : a 16 bit signed integer (Short_t) // - s : a 16 bit unsigned integer (UShort_t) // - I : a 32 bit signed integer (Int_t) // - i : a 32 bit unsigned integer (UInt_t) // - F : a 32 bit floating point (Float_t) // - D : a 64 bit floating point (Double_t) // - L : a 64 bit signed integer (Long64_t) // - l : a 64 bit unsigned integer (ULong64_t) // - O : [the letter 'o', not a zero] a boolean (Bool_t) // from numericdtype.py // # b -> boolean // # u -> unsigned integer // # i -> signed integer // # f -> floating point // # c -> complex // # M -> datetime // # m -> timedelta // # S -> string // # U -> Unicode string // # V -> record // # O -> Python object root_typemap.insert(make_pair("Char_t",TypeInfo("i1",1))); root_typemap.insert(make_pair("UChar_t",TypeInfo("u1",1))); root_typemap.insert(make_pair("Short_t",TypeInfo("i2",1))); root_typemap.insert(make_pair("UShort_t",TypeInfo("u2",1))); root_typemap.insert(make_pair("Int_t",TypeInfo("i4",4))); root_typemap.insert(make_pair("UInt_t",TypeInfo("u4",4))); root_typemap.insert(make_pair("Float_t",TypeInfo("f4",4))); root_typemap.insert(std::make_pair("Double_t",TypeInfo("f8",8))); root_typemap.insert(make_pair("Long64_t",TypeInfo("i8",8))); root_typemap.insert(make_pair("ULong64_t",TypeInfo("u8",8))); //this one is kinda special currently need to read c-api on exacly how numpy and root store bool //but int seems to work root_typemap.insert(make_pair("Bool_t",TypeInfo("i4",4))); } TypeInfo* convert_roottype(const std::string& t){ std::map<std::string, TypeInfo>::iterator it = root_typemap.find(t); if(it==root_typemap.end()){ std::string msg = "Unknown root type: "+t; PyErr_SetString(PyExc_RuntimeError,msg.c_str()); return NULL; } return &(it->second); } struct LeafInfo{ std::string name; TypeInfo* type; std::string root_type; char payload[64];//reserve for payload LeafInfo():name(),type(){} LeafInfo(const std::string& name,const std::string& root_type):name(name),root_type(root_type),type(0){}; std::string repr(){ return name + "("+root_type+")"; } }; //return all branch name from tree std::vector<std::string> get_branchnames(TTree& tree){ TObjArray* branches = (TObjArray*)tree.GetListOfBranches(); std::vector<std::string> ret; for(int i=0;i<branches->GetEntries();++i){ TBranch* thisBranch = dynamic_cast<TBranch*>(branches->At(i)); const char* tmp = thisBranch->GetName(); std::string str(tmp); ret.push_back(tmp); } return ret; } //vector unique with order preservation(just get the first one) O(nlogn) std::vector<std::string> vector_unique(const std::vector<std::string>& org){ using namespace std; set<string> myset; myset.insert(org.begin(),org.end()); vector<string> ret; for(int i=0;i<org.size();i++){ set<string>::iterator it = myset.find(org[i]); if(it!=myset.end()){ myset.erase(it); ret.push_back(org[i]); } } return ret; } //get list of leafinfo from tree //if branches is not empty, only the branches specified in branches will be used //otherwise it will automatically list all the branches of the first tree in chain std::vector<LeafInfo*> get_leafinfo(TTree& tree,const std::vector<std::string>& branches){ using namespace std; vector<string> branchNames; std::vector<LeafInfo*> ret; if(branches.size()==0) branchNames = get_branchnames(tree); else branchNames = vector_unique(branches); for(int i=0;i<branchNames.size();i++){ TBranch* thisBranch = dynamic_cast<TBranch*>(tree.GetBranch(branchNames[i].c_str())); std::string roottype("Float_t"); if(thisBranch!=0){ TObjArray* leaves = thisBranch->GetListOfLeaves(); assert(leaves!=0); TLeaf* thisLeaf = dynamic_cast<TLeaf*>(leaves->At(0)); assert(thisLeaf!=0); roottype = thisLeaf->GetTypeName(); }else{ std::cout << "Warning: branch not found in the first tree(assume type of Float_t)" << branchNames[i] << std::endl; } //need to set branch address at tree level because TChain will fail if branch is set at the first tree LeafInfo* li = new LeafInfo(thisBranch->GetName(),roottype); tree.SetBranchAddress(thisBranch->GetName(),&(li->payload)); ret.push_back(li); } return ret; } //helper function for building numpy descr //build == transfer ref ownershp to caller PyObject* build_numpy_descr(const std::vector<LeafInfo*>& lis){ PyObject* mylist = PyList_New(0); for(int i=0;i<lis.size();++i){ PyObject* pyname = PyString_FromString(lis[i]->name.c_str()); TypeInfo* ti = convert_roottype(lis[i]->root_type); lis[i]->type = ti; if(ti==0) return NULL; PyObject* pytype = ti->nptype; Py_INCREF(pytype); PyObject* nt_tuple = PyTuple_New(2); PyTuple_SetItem(nt_tuple,0,pyname); PyTuple_SetItem(nt_tuple,1,pytype); PyList_Append(mylist,nt_tuple); } return mylist; } //convert all leaf specified in lis to numpy structured array PyObject* build_array(TTree& chain, std::vector<LeafInfo*>& lis){ int numEntries = chain.GetEntries(); PyObject* numpy_descr = build_numpy_descr(lis); if(numpy_descr==0){return NULL;} //build the array PyArray_Descr* descr; PyArray_DescrConverter(numpy_descr,&descr); Py_DECREF(numpy_descr); npy_intp dims[1]; dims[0]=numEntries; PyArrayObject* array = (PyArrayObject*)PyArray_SimpleNewFromDescr(1,dims,descr); //assume numpy array is contiguous char* current = (char*)PyArray_DATA(array); //now put stuff in array for(int iEntry=0;iEntry<numEntries;++iEntry){ chain.GetEntry(iEntry); for(int ileaf=0;ileaf<lis.size();++ileaf){ //cout << *(int*)(lis[ileaf]->payload) << " " << *(float*)(lis[ileaf]->payload) << endl; int size = lis[ileaf]->type->size; memcpy((void*)current,(void*)lis[ileaf]->payload,size); current+=size; } } //return Py_BuildValue("i",numEntries); return (PyObject*)array; } //convert list of string to vector of string //if los is just a string vos will be filled with that string //if los is null or PyNone it do nothing to vos and return OK; int los2vos(PyObject* los, std::vector<std::string>& vos){ int ret=1; if(los==NULL){ //do nothing } else if(los==Py_None){ //do nothing } else if(PyString_Check(los)){ char* tmp = PyString_AsString(los); vos.push_back(tmp); }else if(PyList_Check(los)){ int len = PyList_Size(los); for(int i=0;i<len;i++){ PyObject* s = PyList_GetItem(los,i); if(!s){return NULL;} char* tmp = PyString_AsString(s); if(!tmp){return NULL;} std::string str(tmp); vos.push_back(tmp); } }else{ ret=NULL; } return ret; } /** * loadTTree from PyObject if fnames is list of string then it load every pattern in fnames * if fnames is just a string then it load just one * caller is responsible to delete the return value * null is return if fnames is not a valid python object(either list of string or string) */ TTree* loadTree(PyObject* fnames, const char* treename){ using namespace std; vector<string> vs; if(!los2vos(fnames,vs)){return NULL;} TChain* chain = new TChain(treename); for(int i=0;i<vs.size();++i){chain->Add(vs[i].c_str());} return dynamic_cast<TTree*>(chain); } PyObject* root2array(PyObject *self, PyObject *args, PyObject* keywords){ using namespace std; PyObject* fnames=NULL; char* treename_; PyObject* branches_=NULL; PyObject* array=NULL; static const char* keywordslist[] = {"fname","treename","branches",NULL}; if(!PyArg_ParseTupleAndKeywords(args,keywords,"Os|O",const_cast<char **>(keywordslist),&fnames,&treename_,&branches_)){ return NULL; } vector<string> branches; if(!los2vos(branches_,branches)){return NULL;} Py_XDECREF(branches_); TTree* chain = loadTree(fnames,treename_); if(!chain){return NULL;} Py_DECREF(fnames); int numEntries = chain->GetEntries(); if(numEntries==0){ PyErr_SetString(PyExc_TypeError,"Empty Tree"); return NULL; } vector<LeafInfo*> lis = get_leafinfo(*chain,branches); array = build_array(*chain, lis); //don't switch these two lines because lis[i] contains payload delete chain; for(int i=0;i<lis.size();i++){delete lis[i];} return (PyObject*)array; } static PyMethodDef methods[] = { {"root2array", (PyCFunction)root2array, METH_VARARGS|METH_KEYWORDS, "root2array(fnames,treename,branches=None)\n" "convert tree treename in root files specified in fnames to numpy structured array\n" "------------------\n" "return numpy array\n" "fnames: list of string or string. Root file name patterns. Anything that works with TChain.Add is accepted\n" "treename: name of tree to convert to numpy array\n" "branches(optional): list of string for branch name to be extracted from tree.\n" "\tIf branches is not specified or is none or is empty, all from the first treebranches are extracted\n" "\tIf branches contains duplicate branches, only the first one is used.\n" "\n" "Caveat: This should not matter for most use cases. But, due to the way TChain works, if the trees specified in the input files have different\n" "structures, only the branch in the first tree will be automatically extracted. You can work around this by either reordering the input file or\n" "specify the branches manually.\n" "------------------\n" "Ex:\n" "root2array('a.root','mytree')#read all branches from tree named mytree from a.root\n\n" "root2array('a*.root','mytree')#read all branches from tree named mytree from a*.root\n\n" "root2array(['a*.root','b*.root'],'mytree')#read all branches from tree named mytree from a*.root and b*.root\n\n" "root2array('a.root','mytree','x')#read branch x from tree named mytree from a.root(useful if memory usage matters)\n\n" "root2array('a.root','mytree',['x','y'])#read branch x and y from tree named mytree from a.root\n" }, {NULL, NULL, 0, NULL} /* Sentinel */ }; void cleanup(){ //do nothing } PyMODINIT_FUNC initcroot_numpy(void) { import_array(); init_roottypemap(); (void) Py_InitModule("croot_numpy", methods); //import_array(); } <commit_msg>fix alignment, fix bool size, and double free<commit_after>#include <Python.h> #include <string> #include <iostream> #include <TTree.h> #include <TFile.h> #include <TChain.h> #include <TLeaf.h> #include <map> #include <numpy/arrayobject.h> #include <cassert> #include <set> #include <iomanip> #define RNDEBUG(s) std::cout << "DEBUG: " << __FILE__ << "(" <<__LINE__ << ") " << #s << " = " << s << std::endl; struct TypeInfo{ PyObject* nptype; int size;//in bytes TypeInfo(const TypeInfo& t):nptype(t.nptype),size(t.size){Py_INCREF(nptype);} TypeInfo(const char* nptype, int size):nptype(PyString_FromString(nptype)),size(size){}; ~TypeInfo(){Py_DECREF(nptype);} }; static std::map<std::string, TypeInfo> root_typemap; //map roottype string to TypeInfo Object void init_roottypemap(){ using std::make_pair; //TODO: correct this one so it doesn't depend on system // from TTree doc // - C : a character string terminated by the 0 character // - B : an 8 bit signed integer (Char_t) // - b : an 8 bit unsigned integer (UChar_t) // - S : a 16 bit signed integer (Short_t) // - s : a 16 bit unsigned integer (UShort_t) // - I : a 32 bit signed integer (Int_t) // - i : a 32 bit unsigned integer (UInt_t) // - F : a 32 bit floating point (Float_t) // - D : a 64 bit floating point (Double_t) // - L : a 64 bit signed integer (Long64_t) // - l : a 64 bit unsigned integer (ULong64_t) // - O : [the letter 'o', not a zero] a boolean (Bool_t) // from numericdtype.py // # b -> boolean // # u -> unsigned integer // # i -> signed integer // # f -> floating point // # c -> complex // # M -> datetime // # m -> timedelta // # S -> string // # U -> Unicode string // # V -> record // # O -> Python object root_typemap.insert(make_pair("Char_t",TypeInfo("i1",1))); root_typemap.insert(make_pair("UChar_t",TypeInfo("u1",1))); root_typemap.insert(make_pair("Short_t",TypeInfo("i2",2))); root_typemap.insert(make_pair("UShort_t",TypeInfo("u2",2))); root_typemap.insert(make_pair("Int_t",TypeInfo("i4",4))); root_typemap.insert(make_pair("UInt_t",TypeInfo("u4",4))); root_typemap.insert(make_pair("Float_t",TypeInfo("f4",4))); root_typemap.insert(std::make_pair("Double_t",TypeInfo("f8",8))); root_typemap.insert(make_pair("Long64_t",TypeInfo("i8",8))); root_typemap.insert(make_pair("ULong64_t",TypeInfo("u8",8))); //this one is kinda special currently need to read c-api on exacly how numpy and root store bool //but int seems to work root_typemap.insert(make_pair("Bool_t",TypeInfo("u1",1))); } TypeInfo* convert_roottype(const std::string& t){ std::map<std::string, TypeInfo>::iterator it = root_typemap.find(t); if(it==root_typemap.end()){ std::string msg = "Unknown root type: "+t; PyErr_SetString(PyExc_RuntimeError,msg.c_str()); return NULL; } return &(it->second); } struct LeafInfo{ std::string name; TypeInfo* type; std::string root_type; char payload[64];//reserve for payload LeafInfo():name(),type(){} LeafInfo(const std::string& name,const std::string& root_type):name(name),root_type(root_type),type(0){}; std::string repr(){ return name + "("+root_type+")"; } }; //return all branch name from tree std::vector<std::string> get_branchnames(TTree& tree){ TObjArray* branches = (TObjArray*)tree.GetListOfBranches(); std::vector<std::string> ret; for(int i=0;i<branches->GetEntries();++i){ TBranch* thisBranch = dynamic_cast<TBranch*>(branches->At(i)); const char* tmp = thisBranch->GetName(); std::string str(tmp); ret.push_back(tmp); } return ret; } //vector unique with order preservation(just get the first one) O(nlogn) std::vector<std::string> vector_unique(const std::vector<std::string>& org){ using namespace std; set<string> myset; myset.insert(org.begin(),org.end()); vector<string> ret; for(int i=0;i<org.size();i++){ set<string>::iterator it = myset.find(org[i]); if(it!=myset.end()){ myset.erase(it); ret.push_back(org[i]); } } return ret; } //get list of leafinfo from tree //if branches is not empty, only the branches specified in branches will be used //otherwise it will automatically list all the branches of the first tree in chain std::vector<LeafInfo*> get_leafinfo(TTree& tree,const std::vector<std::string>& branches){ using namespace std; vector<string> branchNames; std::vector<LeafInfo*> ret; if(branches.size()==0) branchNames = get_branchnames(tree); else branchNames = vector_unique(branches); for(int i=0;i<branchNames.size();i++){ TBranch* thisBranch = dynamic_cast<TBranch*>(tree.GetBranch(branchNames[i].c_str())); std::string roottype("Float_t"); if(thisBranch!=0){ TObjArray* leaves = thisBranch->GetListOfLeaves(); assert(leaves!=0); TLeaf* thisLeaf = dynamic_cast<TLeaf*>(leaves->At(0)); assert(thisLeaf!=0); roottype = thisLeaf->GetTypeName(); }else{ std::cout << "Warning: branch not found in the first tree(assume type of Float_t)" << branchNames[i] << std::endl; } //need to set branch address at tree level because TChain will fail if branch is set at the first tree LeafInfo* li = new LeafInfo(thisBranch->GetName(),roottype); tree.SetBranchAddress(thisBranch->GetName(),&(li->payload)); ret.push_back(li); } return ret; } //helper function for building numpy descr //build == transfer ref ownershp to caller PyObject* build_numpy_descr(const std::vector<LeafInfo*>& lis){ PyObject* mylist = PyList_New(0); for(int i=0;i<lis.size();++i){ PyObject* pyname = PyString_FromString(lis[i]->name.c_str()); TypeInfo* ti = convert_roottype(lis[i]->root_type); lis[i]->type = ti; if(ti==0) return NULL; PyObject* pytype = ti->nptype; Py_INCREF(pytype); PyObject* nt_tuple = PyTuple_New(2); PyTuple_SetItem(nt_tuple,0,pyname); PyTuple_SetItem(nt_tuple,1,pytype); PyList_Append(mylist,nt_tuple); } return mylist; } //convert all leaf specified in lis to numpy structured array PyObject* build_array(TTree& chain, std::vector<LeafInfo*>& lis){ using namespace std; int numEntries = chain.GetEntries(); PyObject* numpy_descr = build_numpy_descr(lis); if(numpy_descr==0){return NULL;} //build the array PyArray_Descr* descr; PyArray_DescrConverter(numpy_descr,&descr); Py_DECREF(numpy_descr); npy_intp dims[1]; dims[0]=numEntries; PyArrayObject* array = (PyArrayObject*)PyArray_SimpleNewFromDescr(1,dims,descr); //assume numpy array is contiguous char* current = (char*)PyArray_DATA(array); //now put stuff in array for(int iEntry=0;iEntry<numEntries;++iEntry){ chain.GetEntry(iEntry); current = (char*)PyArray_GETPTR1(array, iEntry); for(int ileaf=0;ileaf<lis.size();++ileaf){ int size = lis[ileaf]->type->size; // // cout << lis[ileaf]->name << " " << lis[ileaf]->root_type << endl; // // cout << *(int*)(lis[ileaf]->payload) << " " << *(float*)(lis[ileaf]->payload) << endl; // cout << lis[ileaf]->name << "("<< iEntry << ")"; // cout << " current: 0x"; // cout << std::hex << (long)(current) << std::dec ; // cout << " size:" << size << " " ; // cout << array->strides[0] << endl; memcpy((char*)current,(char*)lis[ileaf]->payload,size); current+=size; } // if(iEntry==0 || iEntry == numEntries-1) // RNDEBUG(PyArray_ISBEHAVED(array)); } //return Py_BuildValue("i",numEntries); return (PyObject*)array; } //convert list of string to vector of string //if los is just a string vos will be filled with that string //if los is null or PyNone it do nothing to vos and return OK; int los2vos(PyObject* los, std::vector<std::string>& vos){ int ret=1; if(los==NULL){ //do nothing } else if(los==Py_None){ //do nothing } else if(PyString_Check(los)){ char* tmp = PyString_AsString(los); vos.push_back(tmp); }else if(PyList_Check(los)){ int len = PyList_Size(los); for(int i=0;i<len;i++){ PyObject* s = PyList_GetItem(los,i); if(!s){return NULL;} char* tmp = PyString_AsString(s); if(!tmp){return NULL;} std::string str(tmp); vos.push_back(tmp); } }else{ ret=NULL; } return ret; } /** * loadTTree from PyObject if fnames is list of string then it load every pattern in fnames * if fnames is just a string then it load just one * caller is responsible to delete the return value * null is return if fnames is not a valid python object(either list of string or string) */ TTree* loadTree(PyObject* fnames, const char* treename){ using namespace std; vector<string> vs; if(!los2vos(fnames,vs)){return NULL;} TChain* chain = new TChain(treename); for(int i=0;i<vs.size();++i){chain->Add(vs[i].c_str());} return dynamic_cast<TTree*>(chain); } PyObject* root2array(PyObject *self, PyObject *args, PyObject* keywords){ using namespace std; PyObject* fnames=NULL; char* treename_; PyObject* branches_=NULL; PyObject* array=NULL; static const char* keywordslist[] = {"fname","treename","branches",NULL}; if(!PyArg_ParseTupleAndKeywords(args,keywords,"Os|O",const_cast<char **>(keywordslist),&fnames,&treename_,&branches_)){ return NULL; } vector<string> branches; if(!los2vos(branches_,branches)){return NULL;} //Py_XDECREF(branches_); TTree* chain = loadTree(fnames,treename_); if(!chain){return NULL;} //Py_DECREF(fnames); int numEntries = chain->GetEntries(); if(numEntries==0){ PyErr_SetString(PyExc_TypeError,"Empty Tree"); return NULL; } vector<LeafInfo*> lis = get_leafinfo(*chain,branches); array = build_array(*chain, lis); //don't switch these two lines because lis[i] contains payload delete chain; for(int i=0;i<lis.size();i++){delete lis[i];} return (PyObject*)array; } PyObject* test(PyObject *self, PyObject *args){ using namespace std; cout << sizeof(Int_t) << endl; cout << sizeof(Bool_t) << endl; Py_INCREF(Py_None); return Py_None; } static PyMethodDef methods[] = { {"test",test,METH_VARARGS,""}, {"root2array", (PyCFunction)root2array, METH_VARARGS|METH_KEYWORDS, "root2array(fnames,treename,branches=None)\n" "convert tree treename in root files specified in fnames to numpy structured array\n" "------------------\n" "return numpy array\n" "fnames: list of string or string. Root file name patterns. Anything that works with TChain.Add is accepted\n" "treename: name of tree to convert to numpy array\n" "branches(optional): list of string for branch name to be extracted from tree.\n" "\tIf branches is not specified or is none or is empty, all from the first treebranches are extracted\n" "\tIf branches contains duplicate branches, only the first one is used.\n" "\n" "Caveat: This should not matter for most use cases. But, due to the way TChain works, if the trees specified in the input files have different\n" "structures, only the branch in the first tree will be automatically extracted. You can work around this by either reordering the input file or\n" "specify the branches manually.\n" "------------------\n" "Ex:\n" "root2array('a.root','mytree')#read all branches from tree named mytree from a.root\n\n" "root2array('a*.root','mytree')#read all branches from tree named mytree from a*.root\n\n" "root2array(['a*.root','b*.root'],'mytree')#read all branches from tree named mytree from a*.root and b*.root\n\n" "root2array('a.root','mytree','x')#read branch x from tree named mytree from a.root(useful if memory usage matters)\n\n" "root2array('a.root','mytree',['x','y'])#read branch x and y from tree named mytree from a.root\n" }, {NULL, NULL, 0, NULL} /* Sentinel */ }; void cleanup(){ //do nothing } PyObject* list_branches(){ } PyObject* list_tree(){ } PyMODINIT_FUNC initcroot_numpy(void) { import_array(); init_roottypemap(); (void) Py_InitModule("croot_numpy", methods); //import_array(); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2014 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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 "main.h" template<typename T> bool isNotNaN(const T& x) { return x==x; } template<typename T> bool isNaN(const T& x) { return x!=x; } template<typename T> bool isInf(const T& x) { return x > NumTraits<T>::highest(); } template<typename T> bool isMinusInf(const T& x) { return x < NumTraits<T>::lowest(); } // workaround aggressive optimization in ICC template<typename T> EIGEN_DONT_INLINE T sub(T a, T b) { return a - b; } template<typename T> bool isFinite(const T& x) { return isNotNaN(sub(x,x)); } template<typename T> EIGEN_DONT_INLINE T copy(const T& x) { return x; } template<typename MatrixType> void stable_norm(const MatrixType& m) { /* this test covers the following files: StableNorm.h */ using std::sqrt; using std::abs; typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; // Check the basic machine-dependent constants. { int ibeta, it, iemin, iemax; ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent VERIFY( (!(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5) || (it<=4 && ibeta <= 3 ) || it<2)) && "the stable norm algorithm cannot be guaranteed on this computer"); } Index rows = m.rows(); Index cols = m.cols(); // get a non-zero random factor Scalar factor = internal::random<Scalar>(); while(numext::abs2(factor)<RealScalar(1e-4)) factor = internal::random<Scalar>(); Scalar big = factor * ((std::numeric_limits<RealScalar>::max)() * RealScalar(1e-4)); factor = internal::random<Scalar>(); while(numext::abs2(factor)<RealScalar(1e-4)) factor = internal::random<Scalar>(); Scalar small = factor * ((std::numeric_limits<RealScalar>::min)() * RealScalar(1e4)); MatrixType vzero = MatrixType::Zero(rows, cols), vrand = MatrixType::Random(rows, cols), vbig(rows, cols), vsmall(rows,cols); vbig.fill(big); vsmall.fill(small); VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1)); VERIFY_IS_APPROX(vrand.stableNorm(), vrand.norm()); VERIFY_IS_APPROX(vrand.blueNorm(), vrand.norm()); VERIFY_IS_APPROX(vrand.hypotNorm(), vrand.norm()); RealScalar size = static_cast<RealScalar>(m.size()); // test isFinite VERIFY(!isFinite( std::numeric_limits<RealScalar>::infinity())); VERIFY(!isFinite(sqrt(-abs(big)))); // test overflow VERIFY(isFinite(sqrt(size)*abs(big))); VERIFY_IS_NOT_APPROX(sqrt(copy(vbig.squaredNorm())), abs(sqrt(size)*big)); // here the default norm must fail VERIFY_IS_APPROX(vbig.stableNorm(), sqrt(size)*abs(big)); VERIFY_IS_APPROX(vbig.blueNorm(), sqrt(size)*abs(big)); VERIFY_IS_APPROX(vbig.hypotNorm(), sqrt(size)*abs(big)); // test underflow VERIFY(isFinite(sqrt(size)*abs(small))); VERIFY_IS_NOT_APPROX(sqrt(copy(vsmall.squaredNorm())), abs(sqrt(size)*small)); // here the default norm must fail VERIFY_IS_APPROX(vsmall.stableNorm(), sqrt(size)*abs(small)); VERIFY_IS_APPROX(vsmall.blueNorm(), sqrt(size)*abs(small)); VERIFY_IS_APPROX(vsmall.hypotNorm(), sqrt(size)*abs(small)); // Test compilation of cwise() version VERIFY_IS_APPROX(vrand.colwise().stableNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.colwise().blueNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.colwise().hypotNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().stableNorm(), vrand.rowwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().blueNorm(), vrand.rowwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().hypotNorm(), vrand.rowwise().norm()); // test NaN, +inf, -inf MatrixType v; Index i = internal::random<Index>(0,rows-1); Index j = internal::random<Index>(0,cols-1); // NaN { v = vrand; v(i,j) = RealScalar(0)/RealScalar(0); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isNaN(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isNaN(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isNaN(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isNaN(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isNaN(v.hypotNorm())); } // +inf { v = vrand; v(i,j) = RealScalar(1)/RealScalar(0); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isInf(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isInf(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isInf(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isInf(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isInf(v.hypotNorm())); } // -inf { v = vrand; v(i,j) = RealScalar(-1)/RealScalar(0); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isInf(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isInf(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isInf(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isInf(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isInf(v.hypotNorm())); } // mix { Index i2 = internal::random<Index>(0,rows-1); Index j2 = internal::random<Index>(0,cols-1); v = vrand; v(i,j) = RealScalar(-1)/RealScalar(0); v(i2,j2) = RealScalar(0)/RealScalar(0); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isNaN(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isNaN(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isNaN(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isNaN(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isNaN(v.hypotNorm())); } } void test_stable_norm() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( stable_norm(Matrix<float, 1, 1>()) ); CALL_SUBTEST_2( stable_norm(Vector4d()) ); CALL_SUBTEST_3( stable_norm(VectorXd(internal::random<int>(10,2000))) ); CALL_SUBTEST_4( stable_norm(VectorXf(internal::random<int>(10,2000))) ); CALL_SUBTEST_5( stable_norm(VectorXcd(internal::random<int>(10,2000))) ); } } <commit_msg>avoid division by 0<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2014 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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 "main.h" template<typename T> bool isNotNaN(const T& x) { return x==x; } template<typename T> bool isNaN(const T& x) { return x!=x; } template<typename T> bool isInf(const T& x) { return x > NumTraits<T>::highest(); } template<typename T> bool isMinusInf(const T& x) { return x < NumTraits<T>::lowest(); } // workaround aggressive optimization in ICC template<typename T> EIGEN_DONT_INLINE T sub(T a, T b) { return a - b; } template<typename T> bool isFinite(const T& x) { return isNotNaN(sub(x,x)); } template<typename T> EIGEN_DONT_INLINE T copy(const T& x) { return x; } template<typename MatrixType> void stable_norm(const MatrixType& m) { /* this test covers the following files: StableNorm.h */ using std::sqrt; using std::abs; typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; // Check the basic machine-dependent constants. { int ibeta, it, iemin, iemax; ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent VERIFY( (!(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5) || (it<=4 && ibeta <= 3 ) || it<2)) && "the stable norm algorithm cannot be guaranteed on this computer"); } Index rows = m.rows(); Index cols = m.cols(); // get a non-zero random factor Scalar factor = internal::random<Scalar>(); while(numext::abs2(factor)<RealScalar(1e-4)) factor = internal::random<Scalar>(); Scalar big = factor * ((std::numeric_limits<RealScalar>::max)() * RealScalar(1e-4)); factor = internal::random<Scalar>(); while(numext::abs2(factor)<RealScalar(1e-4)) factor = internal::random<Scalar>(); Scalar small = factor * ((std::numeric_limits<RealScalar>::min)() * RealScalar(1e4)); MatrixType vzero = MatrixType::Zero(rows, cols), vrand = MatrixType::Random(rows, cols), vbig(rows, cols), vsmall(rows,cols); vbig.fill(big); vsmall.fill(small); VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1)); VERIFY_IS_APPROX(vrand.stableNorm(), vrand.norm()); VERIFY_IS_APPROX(vrand.blueNorm(), vrand.norm()); VERIFY_IS_APPROX(vrand.hypotNorm(), vrand.norm()); RealScalar size = static_cast<RealScalar>(m.size()); // test isFinite VERIFY(!isFinite( std::numeric_limits<RealScalar>::infinity())); VERIFY(!isFinite(sqrt(-abs(big)))); // test overflow VERIFY(isFinite(sqrt(size)*abs(big))); VERIFY_IS_NOT_APPROX(sqrt(copy(vbig.squaredNorm())), abs(sqrt(size)*big)); // here the default norm must fail VERIFY_IS_APPROX(vbig.stableNorm(), sqrt(size)*abs(big)); VERIFY_IS_APPROX(vbig.blueNorm(), sqrt(size)*abs(big)); VERIFY_IS_APPROX(vbig.hypotNorm(), sqrt(size)*abs(big)); // test underflow VERIFY(isFinite(sqrt(size)*abs(small))); VERIFY_IS_NOT_APPROX(sqrt(copy(vsmall.squaredNorm())), abs(sqrt(size)*small)); // here the default norm must fail VERIFY_IS_APPROX(vsmall.stableNorm(), sqrt(size)*abs(small)); VERIFY_IS_APPROX(vsmall.blueNorm(), sqrt(size)*abs(small)); VERIFY_IS_APPROX(vsmall.hypotNorm(), sqrt(size)*abs(small)); // Test compilation of cwise() version VERIFY_IS_APPROX(vrand.colwise().stableNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.colwise().blueNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.colwise().hypotNorm(), vrand.colwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().stableNorm(), vrand.rowwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().blueNorm(), vrand.rowwise().norm()); VERIFY_IS_APPROX(vrand.rowwise().hypotNorm(), vrand.rowwise().norm()); // test NaN, +inf, -inf MatrixType v; Index i = internal::random<Index>(0,rows-1); Index j = internal::random<Index>(0,cols-1); // NaN { v = vrand; v(i,j) = std::numeric_limits<RealScalar>::quiet_NaN(); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isNaN(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isNaN(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isNaN(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isNaN(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isNaN(v.hypotNorm())); } // +inf { v = vrand; v(i,j) = std::numeric_limits<RealScalar>::infinity(); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isInf(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isInf(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isInf(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isInf(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isInf(v.hypotNorm())); } // -inf { v = vrand; v(i,j) = -std::numeric_limits<RealScalar>::infinity(); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isInf(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isInf(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isInf(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isInf(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isInf(v.hypotNorm())); } // mix { Index i2 = internal::random<Index>(0,rows-1); Index j2 = internal::random<Index>(0,cols-1); v = vrand; v(i,j) = -std::numeric_limits<RealScalar>::infinity(); v(i2,j2) = std::numeric_limits<RealScalar>::quiet_NaN(); VERIFY(!isFinite(v.squaredNorm())); VERIFY(isNaN(v.squaredNorm())); VERIFY(!isFinite(v.norm())); VERIFY(isNaN(v.norm())); VERIFY(!isFinite(v.stableNorm())); VERIFY(isNaN(v.stableNorm())); VERIFY(!isFinite(v.blueNorm())); VERIFY(isNaN(v.blueNorm())); VERIFY(!isFinite(v.hypotNorm())); VERIFY(isNaN(v.hypotNorm())); } } void test_stable_norm() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( stable_norm(Matrix<float, 1, 1>()) ); CALL_SUBTEST_2( stable_norm(Vector4d()) ); CALL_SUBTEST_3( stable_norm(VectorXd(internal::random<int>(10,2000))) ); CALL_SUBTEST_4( stable_norm(VectorXf(internal::random<int>(10,2000))) ); CALL_SUBTEST_5( stable_norm(VectorXcd(internal::random<int>(10,2000))) ); } } <|endoftext|>
<commit_before>/** * Copyright (c) 2015, Timothy Stack * * 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 Timothy Stack 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 REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <assert.h> #include "relative_time.hh" struct { const char *reltime; const char *expected; } TEST_DATA[] = { { "a minute ago", "0y0m0d0h-1m0s0u" }, { "1m ago", "0y0m0d0h-1m0s0u" }, { "a min ago", "0y0m0d0h-1m0s0u" }, { "a m ago", "0y0m0d0h-1m0s0u" }, { "+1 minute ago", "0y0m0d0h-1m0s0u" }, { "-1 minute ago", "0y0m0d0h-1m0s0u" }, { "-1 minute", "0y0m0d0h-1m0s0u" }, { "1:40", "0y0m0d1H40M0S0U" }, { "01:40", "0y0m0d1H40M0S0U" }, { "1h40m", "0y0m0d1h40m0s0u" }, { "1pm", "0y0m0d13H0M0S0U" }, { NULL, NULL } }; struct { const char *reltime; const char *expected_error; } BAD_TEST_DATA[] = { { "ago", "" }, { "minute", "" }, { "1 2", "" }, { NULL, NULL } }; int main(int argc, char *argv[]) { time_t base_time = 1317913200; struct exttm base_tm; base_tm.et_tm = *gmtime(&base_time); struct relative_time::parse_error pe; struct timeval tv; struct exttm tm, tm2; time_t new_time; relative_time rt; for (int lpc = 0; TEST_DATA[lpc].reltime; lpc++) { bool rc; rt.clear(); rc = rt.parse(TEST_DATA[lpc].reltime, pe); printf("%s %s %s\n", TEST_DATA[lpc].reltime, TEST_DATA[lpc].expected, rt.to_string().c_str()); assert(rc); assert(std::string(TEST_DATA[lpc].expected) == rt.to_string()); } for (int lpc = 0; BAD_TEST_DATA[lpc].reltime; lpc++) { bool rc; rt.clear(); rc = rt.parse(BAD_TEST_DATA[lpc].reltime, pe); printf("%s -- %s\n", BAD_TEST_DATA[lpc].reltime, pe.pe_msg.c_str()); assert(!rc); } rt.parse("a minute ago", pe); assert(rt.rt_field[relative_time::RTF_MINUTES] == -1); rt.parse("5 milliseconds", pe); assert(rt.rt_field[relative_time::RTF_MICROSECONDS] == 5 * 1000); rt.clear(); rt.parse("5000 ms ago", pe); assert(rt.rt_field[relative_time::RTF_SECONDS] == -5); rt.clear(); rt.parse("5 hours 20 minutes ago", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == -5); assert(rt.rt_field[relative_time::RTF_MINUTES] == -20); rt.clear(); rt.parse("5 hours and 20 minutes ago", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == -5); assert(rt.rt_field[relative_time::RTF_MINUTES] == -20); rt.clear(); rt.parse("1:23", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == 1); assert(rt.rt_is_absolute[relative_time::RTF_HOURS]); assert(rt.rt_field[relative_time::RTF_MINUTES] == 23); assert(rt.rt_is_absolute[relative_time::RTF_MINUTES]); rt.clear(); rt.parse("1:23:45", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == 1); assert(rt.rt_is_absolute[relative_time::RTF_HOURS]); assert(rt.rt_field[relative_time::RTF_MINUTES] == 23); assert(rt.rt_is_absolute[relative_time::RTF_MINUTES]); assert(rt.rt_field[relative_time::RTF_SECONDS] == 45); assert(rt.rt_is_absolute[relative_time::RTF_SECONDS]); tm = base_tm; rt.add(tm); new_time = timegm(&tm.et_tm); tm.et_tm = *gmtime(&new_time); assert(tm.et_tm.tm_hour == 1); assert(tm.et_tm.tm_min == 23); rt.clear(); rt.parse("5 minutes ago", pe); tm = base_tm; rt.add(tm); new_time = timegm(&tm.et_tm); assert(new_time == (base_time - (5 * 60))); rt.clear(); rt.parse("today at 4pm", pe); memset(&tm, 0, sizeof(tm)); memset(&tm2, 0, sizeof(tm2)); gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm2.et_tm); tm2.et_tm.tm_hour = 16; tm2.et_tm.tm_min = 0; tm2.et_tm.tm_sec = 0; rt.add(tm); tm.et_tm.tm_yday = 0; tm2.et_tm.tm_yday = 0; tm.et_tm.tm_wday = 0; tm2.et_tm.tm_wday = 0; #ifdef HAVE_STRUCT_TM_TM_ZONE tm2.et_tm.tm_gmtoff = 0; tm2.et_tm.tm_zone = NULL; #endif assert(memcmp(&tm.et_tm, &tm2.et_tm, sizeof(tm2.et_tm)) == 0); rt.clear(); rt.parse("yesterday at 4pm", pe); gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm2.et_tm); tm2.et_tm.tm_mday -= 1; tm2.et_tm.tm_hour = 16; tm2.et_tm.tm_min = 0; tm2.et_tm.tm_sec = 0; rt.add(tm); tm.et_tm.tm_yday = 0; tm2.et_tm.tm_yday = 0; tm.et_tm.tm_wday = 0; tm2.et_tm.tm_wday = 0; #ifdef HAVE_STRUCT_TM_TM_ZONE tm2.et_tm.tm_gmtoff = 0; tm2.et_tm.tm_zone = NULL; #endif assert(memcmp(&tm.et_tm, &tm2.et_tm, sizeof(tm2.et_tm)) == 0); } <commit_msg>build stuff<commit_after>/** * Copyright (c) 2015, Timothy Stack * * 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 Timothy Stack 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 REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <assert.h> #include "relative_time.hh" struct { const char *reltime; const char *expected; } TEST_DATA[] = { { "a minute ago", "0y0m0d0h-1m0s0u" }, { "1m ago", "0y0m0d0h-1m0s0u" }, { "a min ago", "0y0m0d0h-1m0s0u" }, { "a m ago", "0y0m0d0h-1m0s0u" }, { "+1 minute ago", "0y0m0d0h-1m0s0u" }, { "-1 minute ago", "0y0m0d0h-1m0s0u" }, { "-1 minute", "0y0m0d0h-1m0s0u" }, { "1:40", "0y0m0d1H40M0S0U" }, { "01:40", "0y0m0d1H40M0S0U" }, { "1h40m", "0y0m0d1h40m0s0u" }, { "1pm", "0y0m0d13H0M0S0U" }, { NULL, NULL } }; struct { const char *reltime; const char *expected_error; } BAD_TEST_DATA[] = { { "ago", "" }, { "minute", "" }, { "1 2", "" }, { NULL, NULL } }; static void dump_memory(FILE *dst, const char *src, int len) { int lpc; for (lpc = 0; lpc < len; lpc++) { fprintf(dst, "%02x", src[lpc]); } } int main(int argc, char *argv[]) { time_t base_time = 1317913200; struct exttm base_tm; base_tm.et_tm = *gmtime(&base_time); struct relative_time::parse_error pe; struct timeval tv; struct exttm tm, tm2; time_t new_time; relative_time rt; for (int lpc = 0; TEST_DATA[lpc].reltime; lpc++) { bool rc; rt.clear(); rc = rt.parse(TEST_DATA[lpc].reltime, pe); printf("%s %s %s\n", TEST_DATA[lpc].reltime, TEST_DATA[lpc].expected, rt.to_string().c_str()); assert(rc); assert(std::string(TEST_DATA[lpc].expected) == rt.to_string()); } for (int lpc = 0; BAD_TEST_DATA[lpc].reltime; lpc++) { bool rc; rt.clear(); rc = rt.parse(BAD_TEST_DATA[lpc].reltime, pe); printf("%s -- %s\n", BAD_TEST_DATA[lpc].reltime, pe.pe_msg.c_str()); assert(!rc); } rt.parse("a minute ago", pe); assert(rt.rt_field[relative_time::RTF_MINUTES] == -1); rt.parse("5 milliseconds", pe); assert(rt.rt_field[relative_time::RTF_MICROSECONDS] == 5 * 1000); rt.clear(); rt.parse("5000 ms ago", pe); assert(rt.rt_field[relative_time::RTF_SECONDS] == -5); rt.clear(); rt.parse("5 hours 20 minutes ago", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == -5); assert(rt.rt_field[relative_time::RTF_MINUTES] == -20); rt.clear(); rt.parse("5 hours and 20 minutes ago", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == -5); assert(rt.rt_field[relative_time::RTF_MINUTES] == -20); rt.clear(); rt.parse("1:23", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == 1); assert(rt.rt_is_absolute[relative_time::RTF_HOURS]); assert(rt.rt_field[relative_time::RTF_MINUTES] == 23); assert(rt.rt_is_absolute[relative_time::RTF_MINUTES]); rt.clear(); rt.parse("1:23:45", pe); assert(rt.rt_field[relative_time::RTF_HOURS] == 1); assert(rt.rt_is_absolute[relative_time::RTF_HOURS]); assert(rt.rt_field[relative_time::RTF_MINUTES] == 23); assert(rt.rt_is_absolute[relative_time::RTF_MINUTES]); assert(rt.rt_field[relative_time::RTF_SECONDS] == 45); assert(rt.rt_is_absolute[relative_time::RTF_SECONDS]); tm = base_tm; rt.add(tm); new_time = timegm(&tm.et_tm); tm.et_tm = *gmtime(&new_time); assert(tm.et_tm.tm_hour == 1); assert(tm.et_tm.tm_min == 23); rt.clear(); rt.parse("5 minutes ago", pe); tm = base_tm; rt.add(tm); new_time = timegm(&tm.et_tm); assert(new_time == (base_time - (5 * 60))); rt.clear(); rt.parse("today at 4pm", pe); memset(&tm, 0, sizeof(tm)); memset(&tm2, 0, sizeof(tm2)); gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm2.et_tm); tm2.et_tm.tm_hour = 16; tm2.et_tm.tm_min = 0; tm2.et_tm.tm_sec = 0; rt.add(tm); tm.et_tm.tm_yday = 0; tm2.et_tm.tm_yday = 0; tm.et_tm.tm_wday = 0; tm2.et_tm.tm_wday = 0; #ifdef HAVE_STRUCT_TM_TM_ZONE tm2.et_tm.tm_gmtoff = 0; tm2.et_tm.tm_zone = NULL; #endif printf("today out\n"); dump_memory(stdout, (const char *)&tm.et_tm, sizeof(tm.et_tm)); printf("\n"); dump_memory(stdout, (const char *)&tm2.et_tm, sizeof(tm2.et_tm)); assert(memcmp(&tm.et_tm, &tm2.et_tm, sizeof(tm2.et_tm)) == 0); rt.clear(); rt.parse("yesterday at 4pm", pe); gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm2.et_tm); tm2.et_tm.tm_mday -= 1; tm2.et_tm.tm_hour = 16; tm2.et_tm.tm_min = 0; tm2.et_tm.tm_sec = 0; rt.add(tm); tm.et_tm.tm_yday = 0; tm2.et_tm.tm_yday = 0; tm.et_tm.tm_wday = 0; tm2.et_tm.tm_wday = 0; #ifdef HAVE_STRUCT_TM_TM_ZONE tm2.et_tm.tm_gmtoff = 0; tm2.et_tm.tm_zone = NULL; #endif assert(memcmp(&tm.et_tm, &tm2.et_tm, sizeof(tm2.et_tm)) == 0); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <shadow.hpp> class tct1_class { public: tct1_class() = default; tct1_class(int i) : i_(i) { } int get_i() const { return i_; } void set_i(int i) { i_ = i; } private: int i_; }; int extract_i(const tct1_class& a) { return a.get_i(); } int mult(const int* i) { return *i * 2; } void modify(int* i) { *i += 10; } void triple(int& i) { i *= 3; } namespace tct1_space { REGISTER_TYPE_BEGIN() REGISTER_TYPE(tct1_class) REGISTER_TYPE_END() REGISTER_CONSTRUCTOR(tct1_class) REGISTER_FREE_FUNCTION(extract_i) SHADOW_INIT() } namespace tct1_space2 { REGISTER_TYPE_BEGIN() REGISTER_TYPE(tct1_class) REGISTER_TYPE_END() REGISTER_CONSTRUCTOR(tct1_class, int) REGISTER_MEMBER_FUNCTION(tct1_class, get_i) REGISTER_MEMBER_FUNCTION(tct1_class, set_i) REGISTER_FREE_FUNCTION(mult) REGISTER_FREE_FUNCTION(modify) REGISTER_FREE_FUNCTION(triple) SHADOW_INIT() } TEST_CASE("create an int using static_construct", "[static_construct]") { auto anint = tct1_space::static_construct<int>(23); auto anint2 = tct1_space2::static_construct<int>(100); REQUIRE(anint.type().name() == std::string("int")); REQUIRE(tct1_space::get_held_value<int>(anint) == 23); SECTION( "find constructor for tct1_class from tct1_space2 namespace manager") { auto constructors = tct1_space2::manager.constructors(); auto found = std::find_if( constructors.first, constructors.second, [](const auto& ct) { const auto name = tct1_space2::manager.constructor_type(ct).name(); return name == std::string("tct1_class"); }); auto paramtypes = tct1_space2::manager.constructor_parameter_types(*found); REQUIRE(found != constructors.second); REQUIRE(std::distance(paramtypes.first, paramtypes.second) == 1); REQUIRE(paramtypes.first->name() == std::string("int")); SECTION("construct a tct1_class from tct1_space2 with int from " "tct1_space namespace") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.construct_object( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("tct1_class")); REQUIRE(tct1_space2::get_held_value<tct1_class>(res).get_i() == 23); REQUIRE(tct1_space::get_held_value<tct1_class>(res).get_i() == 23); SECTION("find all free functions from tct1_space") { auto ffs = tct1_space::manager.free_functions(); REQUIRE(std::distance(ffs.first, ffs.second) > 0); SECTION("find free function taking tct1_class as argument") { auto ff_found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { auto param_types = tct1_space::manager .free_function_parameter_types(ff); return (std::distance(param_types.first, param_types.second) == 1) && (param_types.first->name() == std::string("tct1_class")); }); REQUIRE(ff_found != ffs.second); SECTION("call free function") { auto ff_res = tct1_space::manager.call_free_function( *ff_found, &res, &res + 1); REQUIRE(ff_res.type().name() == std::string("int")); REQUIRE(tct1_space::get_held_value<int>(ff_res) == 23); } } } } } SECTION("find all type conversions available") { auto conversions = tct1_space::manager.conversions(); SECTION("find conversion from int to float") { auto found = std::find_if( conversions.first, conversions.second, [](const auto& cv) { auto conv_types = tct1_space::manager.conversion_types(cv); return conv_types.first.name() == std::string("int") && conv_types.second.name() == std::string("float"); }); REQUIRE(found != conversions.second); SECTION("convert int to float") { auto res = tct1_space::manager.convert(*found, anint); REQUIRE(res.type().name() == std::string("float")); REQUIRE(tct1_space::get_held_value<float>(res) == Approx(23.0f)); } } } SECTION("find all functions from tct1_space2") { auto ffs = tct1_space2::manager.free_functions(); REQUIRE(std::distance(ffs.first, ffs.second) == 3); SECTION("find function 'mult'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("mult"); }); REQUIRE(found != ffs.second); SECTION("call mult with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("int")); REQUIRE(tct1_space2::get_held_value<int>(res) == 200); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 100); } } SECTION("fund function 'modify'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("modify"); }); REQUIRE(found != ffs.second); SECTION("call mult with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 110); } SECTION("call mult with anint in a vector") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.call_free_function( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(args[0]) == 33); } } SECTION("find function 'triple'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("triple"); }); REQUIRE(found != ffs.second); SECTION("call triple with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 300); } SECTION("call triple with anint in vector") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.call_free_function( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space::get_held_value<int>(args[0]) == 23 * 3); } } } SECTION("get all member functions in tct1_space2") { auto mfs = tct1_space2::manager.member_functions(); REQUIRE(std::distance(mfs.first, mfs.second) == 2); SECTION("find tct1_class::get_i") { auto found = std::find_if(mfs.first, mfs.second, [](const auto& mf) { return tct1_space2::manager.member_function_name(mf) == std::string("get_i") && tct1_space2::manager.member_function_class(mf) .name() == std::string("tct1_class"); }); REQUIRE(found != mfs.second); SECTION("get parameter types") { auto param_types = tct1_space2::manager.member_function_parameter_types( *found); REQUIRE(std::distance(param_types.first, param_types.second) == 0); SECTION( "call get_i on an ctc1_class object from same namespace") { auto obj = tct1_space2::static_construct<tct1_class>(33); std::vector<shadow::object> args; auto res = tct1_space2::manager.call_member_function( obj, *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("int")); REQUIRE(tct1_space2::get_held_value<int>(res) == 33); } } } SECTION("find tct1_class::set_i") { auto found = std::find_if(mfs.first, mfs.second, [](const auto& mf) { return tct1_space2::manager.member_function_name(mf) == std::string("set_i") && tct1_space2::manager.member_function_class(mf) .name() == std::string("tct1_class"); }); REQUIRE(found != mfs.second); SECTION("get parameter types") { auto param_types = tct1_space2::manager.member_function_parameter_types( *found); REQUIRE(std::distance(param_types.first, param_types.second) == 1); REQUIRE(param_types.first->name() == std::string("int")); SECTION("call set_i on a ctc1_class object from same namespace") { auto obj = tct1_space2::static_construct<tct1_class>(33); auto res = tct1_space2::manager.call_member_function( obj, *found, &anint, &anint + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE( tct1_space2::get_held_value<tct1_class>(obj).get_i() == 23); } } } } } <commit_msg>Add unit test with reference out parameter. modified: tests/test_compile_time1.cpp<commit_after>#include "catch.hpp" #include <shadow.hpp> class tct1_class { public: tct1_class() = default; tct1_class(int i) : i_(i) { } int get_i() const { return i_; } void set_i(int i) { i_ = i; } void output_i(int& i) { i = i_; } void pointer_out(int* i) { *i = i_; } private: int i_; }; int extract_i(const tct1_class& a) { return a.get_i(); } int mult(const int* i) { return *i * 2; } void modify(int* i) { *i += 10; } void triple(int& i) { i *= 3; } namespace tct1_space { REGISTER_TYPE_BEGIN() REGISTER_TYPE(tct1_class) REGISTER_TYPE_END() REGISTER_CONSTRUCTOR(tct1_class) REGISTER_FREE_FUNCTION(extract_i) SHADOW_INIT() } namespace tct1_space2 { REGISTER_TYPE_BEGIN() REGISTER_TYPE(tct1_class) REGISTER_TYPE_END() REGISTER_CONSTRUCTOR(tct1_class, int) REGISTER_MEMBER_FUNCTION(tct1_class, get_i) REGISTER_MEMBER_FUNCTION(tct1_class, set_i) REGISTER_MEMBER_FUNCTION(tct1_class, output_i) REGISTER_MEMBER_FUNCTION(tct1_class, pointer_out) REGISTER_FREE_FUNCTION(mult) REGISTER_FREE_FUNCTION(modify) REGISTER_FREE_FUNCTION(triple) SHADOW_INIT() } TEST_CASE("create an int using static_construct", "[static_construct]") { auto anint = tct1_space::static_construct<int>(23); auto anint2 = tct1_space2::static_construct<int>(100); REQUIRE(anint.type().name() == std::string("int")); REQUIRE(tct1_space::get_held_value<int>(anint) == 23); SECTION( "find constructor for tct1_class from tct1_space2 namespace manager") { auto constructors = tct1_space2::manager.constructors(); auto found = std::find_if( constructors.first, constructors.second, [](const auto& ct) { const auto name = tct1_space2::manager.constructor_type(ct).name(); return name == std::string("tct1_class"); }); auto paramtypes = tct1_space2::manager.constructor_parameter_types(*found); REQUIRE(found != constructors.second); REQUIRE(std::distance(paramtypes.first, paramtypes.second) == 1); REQUIRE(paramtypes.first->name() == std::string("int")); SECTION("construct a tct1_class from tct1_space2 with int from " "tct1_space namespace") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.construct_object( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("tct1_class")); REQUIRE(tct1_space2::get_held_value<tct1_class>(res).get_i() == 23); REQUIRE(tct1_space::get_held_value<tct1_class>(res).get_i() == 23); SECTION("find all free functions from tct1_space") { auto ffs = tct1_space::manager.free_functions(); REQUIRE(std::distance(ffs.first, ffs.second) > 0); SECTION("find free function taking tct1_class as argument") { auto ff_found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { auto param_types = tct1_space::manager .free_function_parameter_types(ff); return (std::distance(param_types.first, param_types.second) == 1) && (param_types.first->name() == std::string("tct1_class")); }); REQUIRE(ff_found != ffs.second); SECTION("call free function") { auto ff_res = tct1_space::manager.call_free_function( *ff_found, &res, &res + 1); REQUIRE(ff_res.type().name() == std::string("int")); REQUIRE(tct1_space::get_held_value<int>(ff_res) == 23); } } } } } SECTION("find all type conversions available") { auto conversions = tct1_space::manager.conversions(); SECTION("find conversion from int to float") { auto found = std::find_if( conversions.first, conversions.second, [](const auto& cv) { auto conv_types = tct1_space::manager.conversion_types(cv); return conv_types.first.name() == std::string("int") && conv_types.second.name() == std::string("float"); }); REQUIRE(found != conversions.second); SECTION("convert int to float") { auto res = tct1_space::manager.convert(*found, anint); REQUIRE(res.type().name() == std::string("float")); REQUIRE(tct1_space::get_held_value<float>(res) == Approx(23.0f)); } } } SECTION("find all functions from tct1_space2") { auto ffs = tct1_space2::manager.free_functions(); REQUIRE(std::distance(ffs.first, ffs.second) == 3); SECTION("find function 'mult'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("mult"); }); REQUIRE(found != ffs.second); SECTION("call mult with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("int")); REQUIRE(tct1_space2::get_held_value<int>(res) == 200); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 100); } } SECTION("fund function 'modify'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("modify"); }); REQUIRE(found != ffs.second); SECTION("call mult with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 110); } SECTION("call mult with anint in a vector") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.call_free_function( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(args[0]) == 33); } } SECTION("find function 'triple'") { auto found = std::find_if(ffs.first, ffs.second, [](const auto& ff) { return tct1_space2::manager.free_function_name(ff) == std::string("triple"); }); REQUIRE(found != ffs.second); SECTION("call triple with anint2") { auto res = tct1_space2::manager.call_free_function( *found, &anint2, &anint2 + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space2::get_held_value<int>(anint2) == 300); } SECTION("call triple with anint in vector") { std::vector<shadow::object> args{anint}; auto res = tct1_space2::manager.call_free_function( *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space::get_held_value<int>(args[0]) == 23 * 3); } } } SECTION("get all member functions in tct1_space2") { auto mfs = tct1_space2::manager.member_functions(); REQUIRE(std::distance(mfs.first, mfs.second) == 4); SECTION("find tct1_class::get_i") { auto found = std::find_if(mfs.first, mfs.second, [](const auto& mf) { return tct1_space2::manager.member_function_name(mf) == std::string("get_i") && tct1_space2::manager.member_function_class(mf) .name() == std::string("tct1_class"); }); REQUIRE(found != mfs.second); SECTION("get parameter types") { auto param_types = tct1_space2::manager.member_function_parameter_types( *found); REQUIRE(std::distance(param_types.first, param_types.second) == 0); SECTION( "call get_i on an ctc1_class object from same namespace") { auto obj = tct1_space2::static_construct<tct1_class>(33); std::vector<shadow::object> args; auto res = tct1_space2::manager.call_member_function( obj, *found, args.begin(), args.end()); REQUIRE(res.type().name() == std::string("int")); REQUIRE(tct1_space2::get_held_value<int>(res) == 33); } } } SECTION("find tct1_class::set_i") { auto found = std::find_if(mfs.first, mfs.second, [](const auto& mf) { return tct1_space2::manager.member_function_name(mf) == std::string("set_i") && tct1_space2::manager.member_function_class(mf) .name() == std::string("tct1_class"); }); REQUIRE(found != mfs.second); SECTION("get parameter types") { auto param_types = tct1_space2::manager.member_function_parameter_types( *found); REQUIRE(std::distance(param_types.first, param_types.second) == 1); REQUIRE(param_types.first->name() == std::string("int")); SECTION("call set_i on a ctc1_class object from same namespace") { auto obj = tct1_space2::static_construct<tct1_class>(33); auto res = tct1_space2::manager.call_member_function( obj, *found, &anint, &anint + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE( tct1_space2::get_held_value<tct1_class>(obj).get_i() == 23); } } } SECTION("find tct1_class::output_i") { auto found = std::find_if(mfs.first, mfs.second, [](const auto& mf) { return tct1_space2::manager.member_function_name(mf) == std::string("output_i") && tct1_space2::manager.member_function_class(mf) .name() == std::string("tct1_class"); }); REQUIRE(found != mfs.second); SECTION("get parameter types") { auto param_types = tct1_space2::manager.member_function_parameter_types( *found); REQUIRE(std::distance(param_types.first, param_types.second) == 1); REQUIRE(param_types.first->name() == std::string("int")); SECTION("call output_i on a ctc1_class object") { auto obj = tct1_space2::static_construct<tct1_class>(2000); auto res = tct1_space2::manager.call_member_function( obj, *found, &anint, &anint + 1); REQUIRE(res.type().name() == std::string("void")); REQUIRE(tct1_space::get_held_value<int>(anint) == 2000); } } } } } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/string.hpp" #include "flusspferd/string_io.hpp" #include "flusspferd/exception.hpp" #include <iostream> #include <cstring> #include <string> #include "test_environment.hpp" BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture ) BOOST_AUTO_TEST_CASE( empty_string ) { flusspferd::string s, t; BOOST_CHECK(s.length() == 0); BOOST_CHECK(s.to_string().empty()); BOOST_CHECK(std::strlen(s.c_str()) == 0); BOOST_CHECK_EQUAL(s, t); } BOOST_AUTO_TEST_CASE( cstring ) { char const * const test = "Hallo Welt!\n"; flusspferd::string s(test); BOOST_CHECK_EQUAL(s.length(), std::strlen(test)); BOOST_CHECK(std::strcmp(s.c_str(), test) == 0); } BOOST_AUTO_TEST_CASE( std_string ) { std::string test = "Hallo Welt!\n"; flusspferd::string s(test); BOOST_CHECK_EQUAL(s.length(), test.length()); BOOST_CHECK_EQUAL(s.to_string(), test); BOOST_CHECK(std::strcmp(s.c_str(), test.c_str()) == 0); } BOOST_AUTO_TEST_CASE( copy_op ) { flusspferd::string const a("Hallo Welt!\n"); flusspferd::string b; b = a; BOOST_CHECK_EQUAL(a, b); } BOOST_AUTO_TEST_CASE( op_less ) { std::string const ss1 = "aaa"; std::string const ss2 = "aab"; flusspferd::string fs1 = ss1; flusspferd::string fs2 = ss2; BOOST_CHECK( (fs1 < fs2) == (ss1 < ss2) ); BOOST_CHECK( (fs2 < fs1) == (ss2 < ss1) ); } BOOST_AUTO_TEST_CASE( string_substr ) { std::string const str = "Ba bo bu bi bo bz"; flusspferd::string s = str; BOOST_CHECK_EQUAL(s.substr(3, 5), str.substr(3, 5)); } BOOST_AUTO_TEST_CASE( string_io ) { std::stringstream ss; flusspferd::string s("Hallo Welt!"); ss << s; BOOST_CHECK_EQUAL(s.to_string(), ss.str()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>tests: added unit test for string op!=<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/string.hpp" #include "flusspferd/string_io.hpp" #include "flusspferd/exception.hpp" #include <iostream> #include <cstring> #include <string> #include "test_environment.hpp" BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture ) BOOST_AUTO_TEST_CASE( empty_string ) { flusspferd::string s, t; BOOST_CHECK(s.length() == 0); BOOST_CHECK(s.to_string().empty()); BOOST_CHECK(std::strlen(s.c_str()) == 0); BOOST_CHECK_EQUAL(s, t); } BOOST_AUTO_TEST_CASE( cstring ) { char const * const test = "Hallo Welt!\n"; flusspferd::string s(test); BOOST_CHECK_EQUAL(s.length(), std::strlen(test)); BOOST_CHECK(std::strcmp(s.c_str(), test) == 0); } BOOST_AUTO_TEST_CASE( std_string ) { std::string test = "Hallo Welt!\n"; flusspferd::string s(test); BOOST_CHECK_EQUAL(s.length(), test.length()); BOOST_CHECK_EQUAL(s.to_string(), test); BOOST_CHECK(std::strcmp(s.c_str(), test.c_str()) == 0); } BOOST_AUTO_TEST_CASE( copy_op ) { flusspferd::string const a("Hallo Welt!\n"); flusspferd::string b; b = a; BOOST_CHECK_EQUAL(a, b); } BOOST_AUTO_TEST_CASE( op_ne ) { flusspferd::string const a("Test String\n"); flusspferd::string const b(a); BOOST_CHECK( !(a == b) == (a != b) ); flusspferd::string const c("sth. completly different\n"); BOOST_CHECK( !(a == c) == (a != c) ); } BOOST_AUTO_TEST_CASE( op_less ) { std::string const ss1 = "aaa"; std::string const ss2 = "aab"; flusspferd::string fs1 = ss1; flusspferd::string fs2 = ss2; BOOST_CHECK( (fs1 < fs2) == (ss1 < ss2) ); BOOST_CHECK( (fs2 < fs1) == (ss2 < ss1) ); } BOOST_AUTO_TEST_CASE( string_substr ) { std::string const str = "Ba bo bu bi bo bz"; flusspferd::string s = str; BOOST_CHECK_EQUAL(s.substr(3, 5), str.substr(3, 5)); } BOOST_AUTO_TEST_CASE( string_io ) { std::stringstream ss; flusspferd::string s("Hallo Welt!"); ss << s; BOOST_CHECK_EQUAL(s.to_string(), ss.str()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 <testpp/test.h> #include "default_output.h" /** * Define tests */ testpp_suite_c parent_suite( "parent" ); testpp_suite_c simple_suite( "simple", parent_suite ); testpp_suite_c special_suite( "special", parent_suite ); testpp_suite_c assertion_suite( "assertion" ); /** * This is a sample test for using in tests. */ template < int N > class test_sample : public testpp_c { public: void test() { tested = true; } static bool tested; }; template < int N > bool test_sample< N >::tested = false; class test_custom : public testpp_c { public: void test() { assertpp( m_x ).t(); assertpp( m_x ) == 5; } void setup() { m_x = 5; } void teardown() { m_x = 0; } private: int m_x; }; REGISTER_TESTPP( test_custom ); // REGISTER_SUITE_TESTPP( test_custom, parent_suite ); // expansion of what the TESTPP macro does class simple_test : public testpp_c { void test(); }; /* static testpp_runner_i simple_test_runner( new simple_test(), "simple_test" , __FILE__, __LINE__ ); */ void simple_test::test() { } SUITE_TESTPP( test_equality_assertion, assertion_suite ) { int value( 5 ); assertpp( value ) == 5; } TESTPP( test_equality_assertion_failure ) { int value( 5 ); assertpp( value ) == 4; } TESTPP( test_inequality_assertion ) { int value( 5 ); assertpp( value ) != 4; } TESTPP( test_inequality_assertion_failure ) { int value( 5 ); assertpp( value ) != 5; } TESTPP( test_string_equality_assertion ) { std::string value( "hello" ); assertpp( value ) == "hello"; } TESTPP( test_suite_match ) { testpp_suite_c suite( "special" ); assertpp( suite.match( "special" ) ).t(); } TESTPP( test_parent_suite_match ) { testpp_suite_c parent( "parent" ); testpp_suite_c suite( "special", parent ); assertpp( suite.match( "parent" ) ).t(); } TESTPP( test_duplicate_runner ) { /* can't run these b/c they alter the list of runners. need to fix this. testpp_runner_c< test_duplicate_runner > runner( "tst_runner_in_suite" , __FILE__, __LINE__ ); assertpp( runner.in_suite( "simple" ) ).f(); */ } TESTPP( test_runner_in_suite ) { /* can't run these b/c they alter the list of runners. need to fix this. testpp_runner_c< test_runner_in_suite > runner( "tst_runner_in_suite" , simple_suite, __FILE__, __LINE__ ); assertpp( runner.in_suite( "simple" ) ).t(); */ } /** * Test that the testpp_set constructor works and defaults values properly. */ TESTPP( test_testpp_set_constructor ) { testpp_set_c set; assertpp( set.test_files().empty() ).t(); assertpp( set.test_suites().empty() ).t(); } /** * Test that adding tests to the testpp_set works and the test_files * and test_suites work better. */ TESTPP( test_testpp_add_tests ) { testpp_set_c set; human_testpp_output_c output; set.add< test_sample< 1 > >( "sample1", "file1.cpp", 118 ); set.add< test_sample< 2 > >( "sample2", "file2.cpp", 120 ); assertpp( set.test_files().size() ) == 2; assertpp( set.test_suites().size() ) == 0; // set.run( output ); assertpp( test_sample< 1 >::tested ).t(); assertpp( test_sample< 2 >::tested ).t(); } <commit_msg>fixed the name of the testpp_set add() function so it's clearly testing the testpp_set class.<commit_after>/** * Copyright 2008 Matthew Graham * 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 <testpp/test.h> #include "default_output.h" /** * Define tests */ testpp_suite_c parent_suite( "parent" ); testpp_suite_c simple_suite( "simple", parent_suite ); testpp_suite_c special_suite( "special", parent_suite ); testpp_suite_c assertion_suite( "assertion" ); /** * This is a sample test for using in tests. */ template < int N > class test_sample : public testpp_c { public: void test() { tested = true; } static bool tested; }; template < int N > bool test_sample< N >::tested = false; class test_custom : public testpp_c { public: void test() { assertpp( m_x ).t(); assertpp( m_x ) == 5; } void setup() { m_x = 5; } void teardown() { m_x = 0; } private: int m_x; }; REGISTER_TESTPP( test_custom ); // REGISTER_SUITE_TESTPP( test_custom, parent_suite ); // expansion of what the TESTPP macro does class simple_test : public testpp_c { void test(); }; /* static testpp_runner_i simple_test_runner( new simple_test(), "simple_test" , __FILE__, __LINE__ ); */ void simple_test::test() { } SUITE_TESTPP( test_equality_assertion, assertion_suite ) { int value( 5 ); assertpp( value ) == 5; } TESTPP( test_equality_assertion_failure ) { int value( 5 ); assertpp( value ) == 4; } TESTPP( test_inequality_assertion ) { int value( 5 ); assertpp( value ) != 4; } TESTPP( test_inequality_assertion_failure ) { int value( 5 ); assertpp( value ) != 5; } TESTPP( test_string_equality_assertion ) { std::string value( "hello" ); assertpp( value ) == "hello"; } TESTPP( test_suite_match ) { testpp_suite_c suite( "special" ); assertpp( suite.match( "special" ) ).t(); } TESTPP( test_parent_suite_match ) { testpp_suite_c parent( "parent" ); testpp_suite_c suite( "special", parent ); assertpp( suite.match( "parent" ) ).t(); } TESTPP( test_duplicate_runner ) { /* can't run these b/c they alter the list of runners. need to fix this. testpp_runner_c< test_duplicate_runner > runner( "tst_runner_in_suite" , __FILE__, __LINE__ ); assertpp( runner.in_suite( "simple" ) ).f(); */ } TESTPP( test_runner_in_suite ) { /* can't run these b/c they alter the list of runners. need to fix this. testpp_runner_c< test_runner_in_suite > runner( "tst_runner_in_suite" , simple_suite, __FILE__, __LINE__ ); assertpp( runner.in_suite( "simple" ) ).t(); */ } /** * Test that the testpp_set constructor works and defaults values properly. */ TESTPP( test_testpp_set_constructor ) { testpp_set_c set; assertpp( set.test_files().empty() ).t(); assertpp( set.test_suites().empty() ).t(); } /** * Test that adding tests to the testpp_set works and the test_files * and test_suites work better. */ TESTPP( test_testpp_set_add_tests ) { testpp_set_c set; human_testpp_output_c output; set.add< test_sample< 1 > >( "sample1", "file1.cpp", 118 ); set.add< test_sample< 2 > >( "sample2", "file2.cpp", 120 ); assertpp( set.test_files().size() ) == 2; assertpp( set.test_suites().size() ) == 0; // set.run( output ); assertpp( test_sample< 1 >::tested ).t(); assertpp( test_sample< 2 >::tested ).t(); } <|endoftext|>
<commit_before>#include "json_ui.hh" #include "display_buffer.hh" #include "event_manager.hh" #include "exception.hh" #include "file.hh" #include "keys.hh" #include "ranges.hh" #include "string_utils.hh" #include "unit_tests.hh" #include "value.hh" #include <utility> #include <unistd.h> namespace Kakoune { template<typename T> String to_json(ArrayView<const T> array) { return "[" + join(array | transform([](auto&& elem) { return to_json(elem); }), ", ") + "]"; } template<typename T, MemoryDomain D> String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); } template<typename K, typename V, MemoryDomain D> String to_json(const HashMap<K, V, D>& map) { return "{" + join(map | transform([](auto&& i) { return format("{}: {}", to_json(i.key), to_json(i.value)); }), ',', false) + "}"; } String to_json(int i) { return to_string(i); } String to_json(bool b) { return b ? "true" : "false"; } String to_json(StringView str) { String res; res.reserve(str.length() + 4); res += '"'; for (auto it = str.begin(), end = str.end(); it != end; ) { auto next = std::find_if(it, end, [](char c) { return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F); }); res += StringView{it, next}; if (next == end) break; char buf[7] = {'\\', *next, 0}; if (*next >= 0 and *next <= 0x1F) sprintf(buf, "\\u%04x", *next); res += buf; it = next+1; } res += '"'; return res; } String to_json(Color color) { if (color.color == Kakoune::Color::RGB) { char buffer[10]; sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b); return buffer; } return to_json(to_string(color)); } String to_json(Attribute attributes) { struct Attr { Attribute attr; StringView name; } attrs[] { { Attribute::Exclusive, "exclusive" }, { Attribute::Underline, "underline" }, { Attribute::Reverse, "reverse" }, { Attribute::Blink, "blink" }, { Attribute::Bold, "bold" }, { Attribute::Dim, "dim" }, { Attribute::Italic, "italic" }, }; return "[" + join(attrs | filter([=](const Attr& a) { return attributes & a.attr; }) | transform([](const Attr& a) { return to_json(a.name); }), ',', false) + "]"; } String to_json(Face face) { return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })", to_json(face.fg), to_json(face.bg), to_json(face.attributes)); } String to_json(const DisplayAtom& atom) { return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content())); } String to_json(const DisplayLine& line) { return to_json(line.atoms()); } String to_json(DisplayCoord coord) { return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column); } String to_json(MenuStyle style) { switch (style) { case MenuStyle::Prompt: return R"("prompt")"; case MenuStyle::Inline: return R"("inline")"; } return ""; } String to_json(InfoStyle style) { switch (style) { case InfoStyle::Prompt: return R"("prompt")"; case InfoStyle::Inline: return R"("inline")"; case InfoStyle::InlineAbove: return R"("inlineAbove")"; case InfoStyle::InlineBelow: return R"("inlineBelow")"; case InfoStyle::MenuDoc: return R"("menuDoc")"; case InfoStyle::Modal: return R"("modal")"; } return ""; } String to_json(CursorMode mode) { switch (mode) { case CursorMode::Prompt: return R"("prompt")"; case CursorMode::Buffer: return R"("buffer")"; } return ""; } String concat() { return ""; } template<typename First, typename... Args> String concat(First&& first, Args&&... args) { if (sizeof...(Args) != 0) return to_json(first) + ", " + concat(args...); return to_json(first); } template<typename... Args> void rpc_call(StringView method, Args&&... args) { auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})", method, concat(std::forward<Args>(args)...), "\n"); write(1, q); } JsonUI::JsonUI() : m_stdin_watcher{0, FdEvents::Read, [this](FDWatcher&, FdEvents, EventMode mode) { parse_requests(mode); }}, m_dimensions{24, 80} { set_signal_handler(SIGINT, SIG_DFL); } void JsonUI::draw(const DisplayBuffer& display_buffer, const Face& default_face, const Face& padding_face) { rpc_call("draw", display_buffer.lines(), default_face, padding_face); } void JsonUI::draw_status(const DisplayLine& status_line, const DisplayLine& mode_line, const Face& default_face) { rpc_call("draw_status", status_line, mode_line, default_face); } void JsonUI::menu_show(ConstArrayView<DisplayLine> items, DisplayCoord anchor, Face fg, Face bg, MenuStyle style) { rpc_call("menu_show", items, anchor, fg, bg, style); } void JsonUI::menu_select(int selected) { rpc_call("menu_select", selected); } void JsonUI::menu_hide() { rpc_call("menu_hide"); } void JsonUI::info_show(StringView title, StringView content, DisplayCoord anchor, Face face, InfoStyle style) { rpc_call("info_show", title, content, anchor, face, style); } void JsonUI::info_hide() { rpc_call("info_hide"); } void JsonUI::set_cursor(CursorMode mode, DisplayCoord coord) { rpc_call("set_cursor", mode, coord); } void JsonUI::refresh(bool force) { rpc_call("refresh", force); } void JsonUI::set_ui_options(const Options& options) { rpc_call("set_ui_options", options); } DisplayCoord JsonUI::dimensions() { return m_dimensions; } void JsonUI::set_on_key(OnKeyCallback callback) { m_on_key = std::move(callback); } using JsonArray = Vector<Value>; using JsonObject = HashMap<String, Value>; static bool is_digit(char c) { return c >= '0' and c <= '9'; } std::tuple<Value, const char*> parse_json(const char* pos, const char* end) { using Result = std::tuple<Value, const char*>; if (not skip_while(pos, end, is_blank)) return {}; if (is_digit(*pos)) { auto digit_end = pos; skip_while(digit_end, end, is_digit); return Result{ Value{str_to_int({pos, digit_end})}, digit_end }; } if (end - pos > 4 and StringView{pos, pos+4} == "true") return Result{ Value{true}, pos+4 }; if (end - pos > 5 and StringView{pos, pos+5} == "false") return Result{ Value{false}, pos+5 }; if (*pos == '"') { String value; bool escaped = false; ++pos; for (auto string_end = pos; string_end != end; ++string_end) { if (escaped) { escaped = false; value += StringView{pos, string_end}; value.back() = *string_end; pos = string_end+1; continue; } if (*string_end == '\\') escaped = true; if (*string_end == '"') { value += StringView{pos, string_end}; return Result{std::move(value), string_end+1}; } } return {}; } if (*pos == '[') { JsonArray array; if (++pos == end) throw runtime_error("unable to parse array"); if (*pos == ']') return Result{std::move(array), pos+1}; while (true) { Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; array.push_back(std::move(element)); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == ']') return Result{std::move(array), pos+1}; else throw runtime_error("unable to parse array, expected ',' or ']'"); } } if (*pos == '{') { if (++pos == end) throw runtime_error("unable to parse object"); JsonObject object; if (*pos == '}') return Result{std::move(object), pos+1}; while (true) { Value name_value; std::tie(name_value, pos) = parse_json(pos, end); if (not name_value) return {}; String& name = name_value.as<String>(); if (not skip_while(pos, end, is_blank)) return {}; if (*pos++ != ':') throw runtime_error("expected :"); Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; object.insert({ std::move(name), std::move(element) }); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == '}') return Result{std::move(object), pos+1}; else throw runtime_error("unable to parse object, expected ',' or '}'"); } } throw runtime_error("unable to parse json"); } std::tuple<Value, const char*> parse_json(StringView json) { return parse_json(json.begin(), json.end()); } void JsonUI::eval_json(const Value& json) { if (not json.is_a<JsonObject>()) throw runtime_error("json request is not an object"); const JsonObject& object = json.as<JsonObject>(); auto json_it = object.find("jsonrpc"_sv); if (json_it == object.end() or json_it->value.as<String>() != "2.0") throw runtime_error("invalid json rpc request"); auto method_it = object.find("method"_sv); if (method_it == object.end()) throw runtime_error("invalid json rpc request (method missing)"); StringView method = method_it->value.as<String>(); auto params_it = object.find("params"_sv); if (params_it == object.end()) throw runtime_error("invalid json rpc request (params missing)"); const JsonArray& params = params_it->value.as<JsonArray>(); if (method == "keys") { for (auto& key_val : params) { for (auto& key : parse_keys(key_val.as<String>())) m_on_key(key); } } else if (method == "mouse") { if (params.size() != 3) throw runtime_error("mouse type/coordinates not specified"); const StringView type = params[0].as<String>(); const Codepoint coord = encode_coord({params[1].as<int>(), params[2].as<int>()}); if (type == "move") m_on_key({Key::Modifiers::MousePos, coord}); else if (type == "press") m_on_key({Key::Modifiers::MousePress, coord}); else if (type == "release") m_on_key({Key::Modifiers::MouseRelease, coord}); else if (type == "wheel_up") m_on_key({Key::Modifiers::MouseWheelUp, coord}); else if (type == "wheel_down") m_on_key({Key::Modifiers::MouseWheelDown, coord}); else throw runtime_error(format("invalid mouse event type: {}", type)); } else if (method == "menu_select") { if (params.size() != 1) throw runtime_error("menu_select needs the item index"); m_on_key({Key::Modifiers::MenuSelect, (Codepoint)params[0].as<int>()}); } else if (method == "resize") { if (params.size() != 2) throw runtime_error("resize expects 2 parameters"); DisplayCoord dim{params[0].as<int>(), params[1].as<int>()}; m_dimensions = dim; m_on_key(resize(dim)); } else throw runtime_error("unknown method"); } void JsonUI::parse_requests(EventMode mode) { constexpr size_t bufsize = 1024; char buf[bufsize]; while (fd_readable(0)) { ssize_t size = ::read(0, buf, bufsize); if (size == -1 or size == 0) { m_stdin_watcher.close_fd(); break; } m_requests += StringView{buf, buf + size}; } if (not m_on_key) return; while (not m_requests.empty()) { const char* pos = nullptr; try { Value json; std::tie(json, pos) = parse_json(m_requests); if (json) eval_json(json); } catch (runtime_error& error) { write(2, format("error while handling requests '{}': '{}'", m_requests, error.what())); // try to salvage request by dropping its first line pos = std::min(m_requests.end(), find(m_requests, '\n')+1); } if (not pos) break; // unterminated request ? m_requests = String{pos, m_requests.end()}; } } UnitTest test_json_parser{[]() { { auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })")); kak_assert(value); } { auto value = std::get<0>(parse_json("[10,20]")); kak_assert(value and value.is_a<JsonArray>()); kak_assert(value.as<JsonArray>().at(1).as<int>() == 20); } { auto value = std::get<0>(parse_json("{}")); kak_assert(value and value.is_a<JsonObject>()); kak_assert(value.as<JsonObject>().empty()); } }}; } <commit_msg>Print a newline after errors in the JSON UI.<commit_after>#include "json_ui.hh" #include "display_buffer.hh" #include "event_manager.hh" #include "exception.hh" #include "file.hh" #include "keys.hh" #include "ranges.hh" #include "string_utils.hh" #include "unit_tests.hh" #include "value.hh" #include <utility> #include <unistd.h> namespace Kakoune { template<typename T> String to_json(ArrayView<const T> array) { return "[" + join(array | transform([](auto&& elem) { return to_json(elem); }), ", ") + "]"; } template<typename T, MemoryDomain D> String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); } template<typename K, typename V, MemoryDomain D> String to_json(const HashMap<K, V, D>& map) { return "{" + join(map | transform([](auto&& i) { return format("{}: {}", to_json(i.key), to_json(i.value)); }), ',', false) + "}"; } String to_json(int i) { return to_string(i); } String to_json(bool b) { return b ? "true" : "false"; } String to_json(StringView str) { String res; res.reserve(str.length() + 4); res += '"'; for (auto it = str.begin(), end = str.end(); it != end; ) { auto next = std::find_if(it, end, [](char c) { return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F); }); res += StringView{it, next}; if (next == end) break; char buf[7] = {'\\', *next, 0}; if (*next >= 0 and *next <= 0x1F) sprintf(buf, "\\u%04x", *next); res += buf; it = next+1; } res += '"'; return res; } String to_json(Color color) { if (color.color == Kakoune::Color::RGB) { char buffer[10]; sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b); return buffer; } return to_json(to_string(color)); } String to_json(Attribute attributes) { struct Attr { Attribute attr; StringView name; } attrs[] { { Attribute::Exclusive, "exclusive" }, { Attribute::Underline, "underline" }, { Attribute::Reverse, "reverse" }, { Attribute::Blink, "blink" }, { Attribute::Bold, "bold" }, { Attribute::Dim, "dim" }, { Attribute::Italic, "italic" }, }; return "[" + join(attrs | filter([=](const Attr& a) { return attributes & a.attr; }) | transform([](const Attr& a) { return to_json(a.name); }), ',', false) + "]"; } String to_json(Face face) { return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })", to_json(face.fg), to_json(face.bg), to_json(face.attributes)); } String to_json(const DisplayAtom& atom) { return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content())); } String to_json(const DisplayLine& line) { return to_json(line.atoms()); } String to_json(DisplayCoord coord) { return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column); } String to_json(MenuStyle style) { switch (style) { case MenuStyle::Prompt: return R"("prompt")"; case MenuStyle::Inline: return R"("inline")"; } return ""; } String to_json(InfoStyle style) { switch (style) { case InfoStyle::Prompt: return R"("prompt")"; case InfoStyle::Inline: return R"("inline")"; case InfoStyle::InlineAbove: return R"("inlineAbove")"; case InfoStyle::InlineBelow: return R"("inlineBelow")"; case InfoStyle::MenuDoc: return R"("menuDoc")"; case InfoStyle::Modal: return R"("modal")"; } return ""; } String to_json(CursorMode mode) { switch (mode) { case CursorMode::Prompt: return R"("prompt")"; case CursorMode::Buffer: return R"("buffer")"; } return ""; } String concat() { return ""; } template<typename First, typename... Args> String concat(First&& first, Args&&... args) { if (sizeof...(Args) != 0) return to_json(first) + ", " + concat(args...); return to_json(first); } template<typename... Args> void rpc_call(StringView method, Args&&... args) { auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})", method, concat(std::forward<Args>(args)...), "\n"); write(1, q); } JsonUI::JsonUI() : m_stdin_watcher{0, FdEvents::Read, [this](FDWatcher&, FdEvents, EventMode mode) { parse_requests(mode); }}, m_dimensions{24, 80} { set_signal_handler(SIGINT, SIG_DFL); } void JsonUI::draw(const DisplayBuffer& display_buffer, const Face& default_face, const Face& padding_face) { rpc_call("draw", display_buffer.lines(), default_face, padding_face); } void JsonUI::draw_status(const DisplayLine& status_line, const DisplayLine& mode_line, const Face& default_face) { rpc_call("draw_status", status_line, mode_line, default_face); } void JsonUI::menu_show(ConstArrayView<DisplayLine> items, DisplayCoord anchor, Face fg, Face bg, MenuStyle style) { rpc_call("menu_show", items, anchor, fg, bg, style); } void JsonUI::menu_select(int selected) { rpc_call("menu_select", selected); } void JsonUI::menu_hide() { rpc_call("menu_hide"); } void JsonUI::info_show(StringView title, StringView content, DisplayCoord anchor, Face face, InfoStyle style) { rpc_call("info_show", title, content, anchor, face, style); } void JsonUI::info_hide() { rpc_call("info_hide"); } void JsonUI::set_cursor(CursorMode mode, DisplayCoord coord) { rpc_call("set_cursor", mode, coord); } void JsonUI::refresh(bool force) { rpc_call("refresh", force); } void JsonUI::set_ui_options(const Options& options) { rpc_call("set_ui_options", options); } DisplayCoord JsonUI::dimensions() { return m_dimensions; } void JsonUI::set_on_key(OnKeyCallback callback) { m_on_key = std::move(callback); } using JsonArray = Vector<Value>; using JsonObject = HashMap<String, Value>; static bool is_digit(char c) { return c >= '0' and c <= '9'; } std::tuple<Value, const char*> parse_json(const char* pos, const char* end) { using Result = std::tuple<Value, const char*>; if (not skip_while(pos, end, is_blank)) return {}; if (is_digit(*pos)) { auto digit_end = pos; skip_while(digit_end, end, is_digit); return Result{ Value{str_to_int({pos, digit_end})}, digit_end }; } if (end - pos > 4 and StringView{pos, pos+4} == "true") return Result{ Value{true}, pos+4 }; if (end - pos > 5 and StringView{pos, pos+5} == "false") return Result{ Value{false}, pos+5 }; if (*pos == '"') { String value; bool escaped = false; ++pos; for (auto string_end = pos; string_end != end; ++string_end) { if (escaped) { escaped = false; value += StringView{pos, string_end}; value.back() = *string_end; pos = string_end+1; continue; } if (*string_end == '\\') escaped = true; if (*string_end == '"') { value += StringView{pos, string_end}; return Result{std::move(value), string_end+1}; } } return {}; } if (*pos == '[') { JsonArray array; if (++pos == end) throw runtime_error("unable to parse array"); if (*pos == ']') return Result{std::move(array), pos+1}; while (true) { Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; array.push_back(std::move(element)); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == ']') return Result{std::move(array), pos+1}; else throw runtime_error("unable to parse array, expected ',' or ']'"); } } if (*pos == '{') { if (++pos == end) throw runtime_error("unable to parse object"); JsonObject object; if (*pos == '}') return Result{std::move(object), pos+1}; while (true) { Value name_value; std::tie(name_value, pos) = parse_json(pos, end); if (not name_value) return {}; String& name = name_value.as<String>(); if (not skip_while(pos, end, is_blank)) return {}; if (*pos++ != ':') throw runtime_error("expected :"); Value element; std::tie(element, pos) = parse_json(pos, end); if (not element) return {}; object.insert({ std::move(name), std::move(element) }); if (not skip_while(pos, end, is_blank)) return {}; if (*pos == ',') ++pos; else if (*pos == '}') return Result{std::move(object), pos+1}; else throw runtime_error("unable to parse object, expected ',' or '}'"); } } throw runtime_error("unable to parse json"); } std::tuple<Value, const char*> parse_json(StringView json) { return parse_json(json.begin(), json.end()); } void JsonUI::eval_json(const Value& json) { if (not json.is_a<JsonObject>()) throw runtime_error("json request is not an object"); const JsonObject& object = json.as<JsonObject>(); auto json_it = object.find("jsonrpc"_sv); if (json_it == object.end() or json_it->value.as<String>() != "2.0") throw runtime_error("invalid json rpc request"); auto method_it = object.find("method"_sv); if (method_it == object.end()) throw runtime_error("invalid json rpc request (method missing)"); StringView method = method_it->value.as<String>(); auto params_it = object.find("params"_sv); if (params_it == object.end()) throw runtime_error("invalid json rpc request (params missing)"); const JsonArray& params = params_it->value.as<JsonArray>(); if (method == "keys") { for (auto& key_val : params) { for (auto& key : parse_keys(key_val.as<String>())) m_on_key(key); } } else if (method == "mouse") { if (params.size() != 3) throw runtime_error("mouse type/coordinates not specified"); const StringView type = params[0].as<String>(); const Codepoint coord = encode_coord({params[1].as<int>(), params[2].as<int>()}); if (type == "move") m_on_key({Key::Modifiers::MousePos, coord}); else if (type == "press") m_on_key({Key::Modifiers::MousePress, coord}); else if (type == "release") m_on_key({Key::Modifiers::MouseRelease, coord}); else if (type == "wheel_up") m_on_key({Key::Modifiers::MouseWheelUp, coord}); else if (type == "wheel_down") m_on_key({Key::Modifiers::MouseWheelDown, coord}); else throw runtime_error(format("invalid mouse event type: {}", type)); } else if (method == "menu_select") { if (params.size() != 1) throw runtime_error("menu_select needs the item index"); m_on_key({Key::Modifiers::MenuSelect, (Codepoint)params[0].as<int>()}); } else if (method == "resize") { if (params.size() != 2) throw runtime_error("resize expects 2 parameters"); DisplayCoord dim{params[0].as<int>(), params[1].as<int>()}; m_dimensions = dim; m_on_key(resize(dim)); } else throw runtime_error("unknown method"); } void JsonUI::parse_requests(EventMode mode) { constexpr size_t bufsize = 1024; char buf[bufsize]; while (fd_readable(0)) { ssize_t size = ::read(0, buf, bufsize); if (size == -1 or size == 0) { m_stdin_watcher.close_fd(); break; } m_requests += StringView{buf, buf + size}; } if (not m_on_key) return; while (not m_requests.empty()) { const char* pos = nullptr; try { Value json; std::tie(json, pos) = parse_json(m_requests); if (json) eval_json(json); } catch (runtime_error& error) { write(2, format("error while handling requests '{}': '{}'\n", m_requests, error.what())); // try to salvage request by dropping its first line pos = std::min(m_requests.end(), find(m_requests, '\n')+1); } if (not pos) break; // unterminated request ? m_requests = String{pos, m_requests.end()}; } } UnitTest test_json_parser{[]() { { auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })")); kak_assert(value); } { auto value = std::get<0>(parse_json("[10,20]")); kak_assert(value and value.is_a<JsonArray>()); kak_assert(value.as<JsonArray>().at(1).as<int>() == 20); } { auto value = std::get<0>(parse_json("{}")); kak_assert(value and value.is_a<JsonObject>()); kak_assert(value.as<JsonObject>().empty()); } }}; } <|endoftext|>
<commit_before>#include "testmessagehandler.h" #include "peer.h" #define INSTALL_CUSTOM_MESSAGE_FACTORY(messageType, messageFactory) \ static MessageFactory s_##messageType##Factory \ = Message::installMessageFactory((Message::Type)messageType, messageFactory); static const quint8 GenericType = Message::NumberOfTypes + 1; class Generic : public Message { Q_OBJECT public: Generic() : Message((Message::Type)GenericType) {} static Message* createMessage() { return new Generic; } }; INSTALL_CUSTOM_MESSAGE_FACTORY(GenericType, &Generic::createMessage); static const quint8 RawDataType = Message::NumberOfTypes + 2; class RawData : public Message { Q_OBJECT Q_PROPERTY(QByteArray data READ data WRITE setData STORED false) public: RawData() : Message((Message::Type)RawDataType) {} const QByteArray& data() const { return m_data; } void setData(const QByteArray& data) { m_data = data; } virtual bool serialize(QIODevice* device); virtual bool deserialize(QIODevice* device); static Message* createMessage() { return new RawData; } private: QByteArray m_data; }; INSTALL_CUSTOM_MESSAGE_FACTORY(RawDataType, &RawData::createMessage); bool RawData::serialize(QIODevice* device) { quint32 size = m_data.size(); if (device->write(reinterpret_cast<char*>(&size), sizeof(quint32)) == -1) return false; if (device->write(m_data) == -1) return false; return true; } bool RawData::deserialize(QIODevice* device) { while(device->bytesAvailable() < 4) device->waitForReadyRead(-1); quint32 size = 0; if (device->read(reinterpret_cast<char*>(&size), sizeof(quint32)) < 4) return false; while (quint32(m_data.size()) < size) { m_data.append(device->readAll()); device->waitForReadyRead(-1); } return true; } struct TestMessageHandlerPrivate { }; void TestMessageHandler::initTestCase() { d = new TestMessageHandlerPrivate; } void TestMessageHandler::cleanupTestCase() { delete d; d = 0; } void TestMessageHandler::sendMessage() { Peer peer1(1111, 2222); Peer peer2(2222, 1111); peer2.expectMessage(); Generic msg; QVERIFY(peer1.sendMessage(&msg) == true); QVERIFY(peer2.blockForMessage() == true); QVERIFY(msg.type() == peer2.lastMessageReceived()->type()); } void TestMessageHandler::sendLargeMessage() { Peer peer1(1111, 2222); Peer peer2(2222, 1111); peer2.expectMessage(); QByteArray data; data.fill('X', 1024 * 1024); RawData msg; msg.setData(data); QVERIFY(peer1.sendMessage(&msg) == true); QVERIFY(peer2.blockForMessage() == true); Message* out = peer2.lastMessageReceived(); QVERIFY(out->type() == msg.type()); if (out->type() == msg.type()) { RawData* raw = static_cast<RawData*>(out); QVERIFY(raw->data() == msg.data()); } } #include "testmessagehandler.moc" <commit_msg>Add tests for the remaining methods in messagehandler.<commit_after>#include "testmessagehandler.h" #include "peer.h" #define INSTALL_CUSTOM_MESSAGE_FACTORY(messageType, messageFactory) \ static MessageFactory s_##messageType##Factory \ = Message::installMessageFactory((Message::Type)messageType, messageFactory); static const quint8 GenericType = Message::NumberOfTypes + 1; class Generic : public Message { Q_OBJECT public: Generic() : Message((Message::Type)GenericType) {} static Message* createMessage() { return new Generic; } }; INSTALL_CUSTOM_MESSAGE_FACTORY(GenericType, &Generic::createMessage); static const quint8 RawDataType = Message::NumberOfTypes + 2; class RawData : public Message { Q_OBJECT Q_PROPERTY(QByteArray data READ data WRITE setData STORED false) public: RawData() : Message((Message::Type)RawDataType) {} const QByteArray& data() const { return m_data; } void setData(const QByteArray& data) { m_data = data; } virtual bool serialize(QIODevice* device); virtual bool deserialize(QIODevice* device); static Message* createMessage() { return new RawData; } private: QByteArray m_data; }; INSTALL_CUSTOM_MESSAGE_FACTORY(RawDataType, &RawData::createMessage); bool RawData::serialize(QIODevice* device) { quint32 size = m_data.size(); if (device->write(reinterpret_cast<char*>(&size), sizeof(quint32)) == -1) return false; if (device->write(m_data) == -1) return false; return true; } bool RawData::deserialize(QIODevice* device) { while(device->bytesAvailable() < 4) device->waitForReadyRead(-1); quint32 size = 0; if (device->read(reinterpret_cast<char*>(&size), sizeof(quint32)) < 4) return false; while (quint32(m_data.size()) < size) { m_data.append(device->readAll()); device->waitForReadyRead(-1); } return true; } struct TestMessageHandlerPrivate { }; void TestMessageHandler::initTestCase() { d = new TestMessageHandlerPrivate; } void TestMessageHandler::cleanupTestCase() { delete d; d = 0; } void TestMessageHandler::sendMessage() { Peer peer1(1111, 2222); QVERIFY(peer1.isRunning() == true); QVERIFY(peer1.readPort() == 1111); QVERIFY(peer1.writePort() == 2222); Peer peer2(2222, 1111); QVERIFY(peer2.isRunning() == true); QVERIFY(peer2.readPort() == 2222); QVERIFY(peer2.writePort() == 1111); peer2.expectMessage(); Generic msg; QVERIFY(peer1.sendMessage(&msg) == true); QVERIFY(peer2.blockForMessage() == true); QVERIFY(msg.type() == peer2.lastMessageReceived()->type()); } void TestMessageHandler::sendLargeMessage() { Peer peer1(1111, 2222); QVERIFY(peer1.isRunning() == true); QVERIFY(peer1.readPort() == 1111); QVERIFY(peer1.writePort() == 2222); Peer peer2(2222, 1111); QVERIFY(peer2.isRunning() == true); QVERIFY(peer2.readPort() == 2222); QVERIFY(peer2.writePort() == 1111); peer2.expectMessage(); QByteArray data; data.fill('X', 1024 * 1024); RawData msg; msg.setData(data); QVERIFY(peer1.sendMessage(&msg) == true); QVERIFY(peer2.blockForMessage() == true); Message* out = peer2.lastMessageReceived(); QVERIFY(out->type() == msg.type()); if (out->type() == msg.type()) { RawData* raw = static_cast<RawData*>(out); QVERIFY(raw->data() == msg.data()); } } #include "testmessagehandler.moc" <|endoftext|>
<commit_before>/* =============================================================================== FILE: laszip.cpp CONTENTS: see corresponding header file PROGRAMMERS: martin.isenburg@gmail.com COPYRIGHT: (c) 2011, Martin Isenburg, LASSO - 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: see corresponding header file =============================================================================== */ #include "laszip.hpp" #include "mydefs.hpp" #include <assert.h> LASzip::LASzip() { compressor = LASZIP_COMPRESSOR_DEFAULT; coder = LASZIP_CODER_ARITHMETIC; version_major = LASZIP_VERSION_MAJOR; version_minor = LASZIP_VERSION_MINOR; version_revision = LASZIP_VERSION_REVISION; options = 0; num_items = 0; chunk_size = 0; num_points = -1; num_bytes = -1; items = 0; requested_version = 0; bytes = 0; } LASzip::~LASzip() { if (items) delete [] items; if (bytes) delete [] bytes; } // unpack from VLR data bool LASzip::unpack(const U8* bytes, const I32 num) { if (num < 34) return false; // too few bytes if (((num - 34) % 6) != 0) return false; // wrong number bytes if (((num - 34) / 6) == 0) return false; // too few items num_items = (num - 34) / 6; if (items) delete [] items; items = new LASitem[num_items]; // the data of the LASzip VLR // U16 compressor 2 bytes // U16 coder 2 bytes // U8 version_major 1 byte // U8 version_minor 1 byte // U16 version_revision 2 bytes // U32 options 4 bytes // U32 chunk_size 4 bytes // I64 num_points 8 bytes // I64 num_bytes 8 bytes // U16 num_items 2 bytes // U16 type 2 bytes * num_items // U16 size 2 bytes * num_items // U16 version 2 bytes * num_items // which totals 34+6*num_items U16 i; const U8* b = bytes; compressor = *((U16*)b); b += 2; coder = *((U16*)b); b += 2; version_major = *((U8*)b); b += 1; version_minor = *((U8*)b); b += 1; version_revision = *((U16*)b); b += 2; options = *((U32*)b); b += 4; chunk_size = *((U32*)b); b += 4; num_points = *((I64*)b); b += 8; num_bytes = *((I64*)b); b += 8; num_items = *((U16*)b); b += 2; for (i = 0; i < num_items; i++) { items[i].type = (LASitem::Type)*((U16*)b); b += 2; items[i].size = *((U16*)b); b += 2; items[i].version = *((U16*)b); b += 2; } assert((bytes + num) == b); for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } return true; } // pack to VLR data bool LASzip::pack(U8*& bytes, I32& num) { num = 34 + 6*num_items; if (this->bytes) delete [] this->bytes; this->bytes = bytes = new U8[num]; // the data of the LASzip VLR // U16 compressor 2 bytes // U16 coder 2 bytes // U8 version_major 1 byte // U8 version_minor 1 byte // U16 version_revision 2 bytes // U32 options 4 bytes // U32 chunk_size 4 bytes // I64 num_points 8 bytes // I64 num_bytes 8 bytes // U16 num_items 2 bytes // U16 type 2 bytes * num_items // U16 size 2 bytes * num_items // U16 version 2 bytes * num_items // which totals 34+6*num_items U16 i; U8* b = bytes; *((U16*)b) = compressor; b += 2; *((U16*)b) = coder; b += 2; *((U8*)b) = version_major; b += 1; *((U8*)b) = version_minor; b += 1; *((U16*)b) = version_revision; b += 2; *((U32*)b) = options; b += 4; *((U32*)b) = chunk_size; b += 4; *((I64*)b) = num_points; b += 8; *((I64*)b) = num_bytes; b += 8; *((U16*)b) = num_items; b += 2; for (i = 0; i < num_items; i++) { *((U16*)b) = (U16)items[i].type; b += 2; *((U16*)b) = items[i].size; b += 2; *((U16*)b) = items[i].version; b += 2; } assert((bytes + num) == b); for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } return true; } bool LASzip::setup(const U8 point_type, const U16 point_size, const U16 compressor) { if (compressor > LASZIP_COMPRESSOR_POINTWISE_CHUNKED) return false; // switch over the point types we know BOOL have_gps_time = FALSE; BOOL have_rgb = FALSE; BOOL have_wavepacket = FALSE; I32 extra_bytes_number = 0; switch (point_type) { case 0: extra_bytes_number = (I32)point_size - 20; break; case 1: have_gps_time = TRUE; extra_bytes_number = (I32)point_size - 28; break; case 2: have_rgb = TRUE; extra_bytes_number = (I32)point_size - 26; break; case 3: have_gps_time = TRUE; have_rgb = TRUE; extra_bytes_number = (I32)point_size - 34; break; case 4: have_gps_time = TRUE; have_wavepacket = TRUE; extra_bytes_number = (I32)point_size - 57; break; case 5: have_gps_time = TRUE; have_rgb = TRUE; have_wavepacket = TRUE; extra_bytes_number = (I32)point_size - 63; break; default: return false; } if (extra_bytes_number < 0) return false; // create item description if (items) delete [] items; num_items = 1 + !!(have_gps_time) + !!(have_rgb) + !!(have_wavepacket) + !!(extra_bytes_number); items = new LASitem[num_items]; U16 i = 1; items[0].type = LASitem::POINT10; items[0].size = 20; items[0].version = 0; if (have_gps_time) { items[i].type = LASitem::GPSTIME11; items[i].size = 8; items[i].version = 0; i++; } if (have_rgb) { items[i].type = LASitem::RGB12; items[i].size = 6; items[i].version = 0; i++; } if (have_wavepacket) { items[i].type = LASitem::WAVEPACKET13; items[i].size = 29; items[i].version = 0; i++; } if (extra_bytes_number) { items[i].type = LASitem::BYTE; items[i].size = extra_bytes_number; items[i].version = 0; i++; } assert(i == num_items); this->compressor = compressor; if (this->compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } return true; } bool LASzip::setup(const U16 num_items, const LASitem* items, const U16 compressor) { U16 i; if (num_items == 0) return false; if (items == 0) return false; if (compressor > LASZIP_COMPRESSOR_POINTWISE_CHUNKED) return false; for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } this->num_items = num_items; if (this->items) delete [] this->items; this->items = new LASitem[num_items]; for (i = 0; i < num_items; i++) { this->items[i] = items[i]; } this->compressor = compressor; if (this->compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } return true; } void LASzip::set_chunk_size(const U32 chunk_size) { this->chunk_size = chunk_size; } void LASzip::request_version(const U32 requested_version) { this->requested_version = requested_version; } bool LASitem::is_type(LASitem::Type t) const { if (t != type) return false; switch (t) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported() const { switch (type) { case POINT10: if (size != 20) return false; if (version > 2) return false; break; case GPSTIME11: if (size != 8) return false; if (version > 2) return false; break; case RGB12: if (size != 6) return false; if (version > 2) return false; break; case WAVEPACKET13: if (size != 29) return false; if (version > 1) return false; break; case BYTE: if (size < 1) return false; if (version > 2) return false; break; default: return false; } return true; } const char* LASitem::get_name() const { switch (type) { case POINT10: return "POINT10"; break; case GPSTIME11: return "GPSTIME11"; break; case RGB12: return "RGB12"; break; case WAVEPACKET13: return "WAVEPACKET13"; break; case BYTE: return "BYTE"; break; default: break; } return 0; } <commit_msg>added functions to query point type and size<commit_after>/* =============================================================================== FILE: laszip.cpp CONTENTS: see corresponding header file PROGRAMMERS: martin.isenburg@gmail.com COPYRIGHT: (c) 2011, Martin Isenburg, LASSO - 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: see corresponding header file =============================================================================== */ #include "laszip.hpp" #include "mydefs.hpp" #include <assert.h> LASzip::LASzip() { compressor = LASZIP_COMPRESSOR_DEFAULT; coder = LASZIP_CODER_ARITHMETIC; version_major = LASZIP_VERSION_MAJOR; version_minor = LASZIP_VERSION_MINOR; version_revision = LASZIP_VERSION_REVISION; options = 0; num_items = 0; chunk_size = 0; num_points = -1; num_bytes = -1; items = 0; requested_version = 0; bytes = 0; } LASzip::~LASzip() { if (items) delete [] items; if (bytes) delete [] bytes; } // unpack from VLR data bool LASzip::unpack(const U8* bytes, const I32 num) { if (num < 34) return false; // too few bytes if (((num - 34) % 6) != 0) return false; // wrong number bytes if (((num - 34) / 6) == 0) return false; // too few items num_items = (num - 34) / 6; if (items) delete [] items; items = new LASitem[num_items]; // the data of the LASzip VLR // U16 compressor 2 bytes // U16 coder 2 bytes // U8 version_major 1 byte // U8 version_minor 1 byte // U16 version_revision 2 bytes // U32 options 4 bytes // U32 chunk_size 4 bytes // I64 num_points 8 bytes // I64 num_bytes 8 bytes // U16 num_items 2 bytes // U16 type 2 bytes * num_items // U16 size 2 bytes * num_items // U16 version 2 bytes * num_items // which totals 34+6*num_items U16 i; const U8* b = bytes; compressor = *((U16*)b); b += 2; coder = *((U16*)b); b += 2; version_major = *((U8*)b); b += 1; version_minor = *((U8*)b); b += 1; version_revision = *((U16*)b); b += 2; options = *((U32*)b); b += 4; chunk_size = *((U32*)b); b += 4; num_points = *((I64*)b); b += 8; num_bytes = *((I64*)b); b += 8; num_items = *((U16*)b); b += 2; for (i = 0; i < num_items; i++) { items[i].type = (LASitem::Type)*((U16*)b); b += 2; items[i].size = *((U16*)b); b += 2; items[i].version = *((U16*)b); b += 2; } assert((bytes + num) == b); for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } return true; } // pack to VLR data bool LASzip::pack(U8*& bytes, I32& num) { num = 34 + 6*num_items; if (this->bytes) delete [] this->bytes; this->bytes = bytes = new U8[num]; // the data of the LASzip VLR // U16 compressor 2 bytes // U16 coder 2 bytes // U8 version_major 1 byte // U8 version_minor 1 byte // U16 version_revision 2 bytes // U32 options 4 bytes // U32 chunk_size 4 bytes // I64 num_points 8 bytes // I64 num_bytes 8 bytes // U16 num_items 2 bytes // U16 type 2 bytes * num_items // U16 size 2 bytes * num_items // U16 version 2 bytes * num_items // which totals 34+6*num_items U16 i; U8* b = bytes; *((U16*)b) = compressor; b += 2; *((U16*)b) = coder; b += 2; *((U8*)b) = version_major; b += 1; *((U8*)b) = version_minor; b += 1; *((U16*)b) = version_revision; b += 2; *((U32*)b) = options; b += 4; *((U32*)b) = chunk_size; b += 4; *((I64*)b) = num_points; b += 8; *((I64*)b) = num_bytes; b += 8; *((U16*)b) = num_items; b += 2; for (i = 0; i < num_items; i++) { *((U16*)b) = (U16)items[i].type; b += 2; *((U16*)b) = items[i].size; b += 2; *((U16*)b) = items[i].version; b += 2; } assert((bytes + num) == b); for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } return true; } bool LASzip::setup(const U8 point_type, const U16 point_size, const U16 compressor) { if (compressor > LASZIP_COMPRESSOR_POINTWISE_CHUNKED) return false; this->num_items = 0; if (this->items) delete [] this->items; this->items = 0; if (!LASitem().setup(point_type, point_size, &num_items, &items)) return false; this->compressor = compressor; if (this->compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } return true; } bool LASzip::setup(const U16 num_items, const LASitem* items, const U16 compressor) { U16 i; if (num_items == 0) return false; if (items == 0) return false; if (compressor > LASZIP_COMPRESSOR_POINTWISE_CHUNKED) return false; this->num_items = 0; if (this->items) delete [] this->items; this->items = 0; for (i = 0; i < num_items; i++) { if (!items[i].supported()) return false; } this->num_items = num_items; this->items = new LASitem[num_items]; for (i = 0; i < num_items; i++) { this->items[i] = items[i]; } this->compressor = compressor; if (this->compressor == LASZIP_COMPRESSOR_POINTWISE_CHUNKED) { if (chunk_size == 0) chunk_size = LASZIP_CHUNK_SIZE_DEFAULT; } return true; } void LASzip::set_chunk_size(const U32 chunk_size) { this->chunk_size = chunk_size; } void LASzip::request_version(const U32 requested_version) { this->requested_version = requested_version; } bool LASzip::is_standard(U8* point_type, U16* record_length) const { return LASitem().is_standard(num_items, items, point_type, record_length); } bool LASitem::setup(const U8 point_type, const U16 point_size, U16* num_items, LASitem** items) const { BOOL have_gps_time = FALSE; BOOL have_rgb = FALSE; BOOL have_wavepacket = FALSE; I32 extra_bytes_number = 0; // switch over the point types we know switch (point_type) { case 0: extra_bytes_number = (I32)point_size - 20; break; case 1: have_gps_time = TRUE; extra_bytes_number = (I32)point_size - 28; break; case 2: have_rgb = TRUE; extra_bytes_number = (I32)point_size - 26; break; case 3: have_gps_time = TRUE; have_rgb = TRUE; extra_bytes_number = (I32)point_size - 34; break; case 4: have_gps_time = TRUE; have_wavepacket = TRUE; extra_bytes_number = (I32)point_size - 57; break; case 5: have_gps_time = TRUE; have_rgb = TRUE; have_wavepacket = TRUE; extra_bytes_number = (I32)point_size - 63; break; default: return false; } if (extra_bytes_number < 0) return false; // create item description (*num_items) = 1 + !!(have_gps_time) + !!(have_rgb) + !!(have_wavepacket) + !!(extra_bytes_number); (*items) = new LASitem[*num_items]; U16 i = 1; (*items)[0].type = LASitem::POINT10; (*items)[0].size = 20; (*items)[0].version = 0; if (have_gps_time) { (*items)[i].type = LASitem::GPSTIME11; (*items)[i].size = 8; (*items)[i].version = 0; i++; } if (have_rgb) { (*items)[i].type = LASitem::RGB12; (*items)[i].size = 6; (*items)[i].version = 0; i++; } if (have_wavepacket) { (*items)[i].type = LASitem::WAVEPACKET13; (*items)[i].size = 29; (*items)[i].version = 0; i++; } if (extra_bytes_number) { (*items)[i].type = LASitem::BYTE; (*items)[i].size = extra_bytes_number; (*items)[i].version = 0; i++; } assert(i == *num_items); return true; } bool LASitem::is_standard(const U16 num_items, const LASitem* items, U8* point_type, U16* record_length) const { if (items == 0) return false; // this is always true if (point_type) *point_type = 127; if (record_length) { U16 i; *record_length = 0; for (i = 0; i < num_items; i++) { *record_length += items[i].size; } } // the minimal number of items is 1 if (num_items < 1) return false; // the maximal number of items is 5 if (num_items > 5) return false; // all standard point types start with POINT10 if (!items[0].is_type(LASitem::POINT10)) return false; // consider all the other combinations if (num_items == 1) { if (point_type) *point_type = 0; if (record_length) assert(*record_length == 20); return true; } else { if (items[1].is_type(LASitem::GPSTIME11)) { if (num_items == 2) { if (point_type) *point_type = 1; if (record_length) assert(*record_length == 28); return true; } else { if (items[2].is_type(LASitem::RGB12)) { if (num_items == 3) { if (point_type) *point_type = 3; if (record_length) assert(*record_length == 34); return true; } else { if (items[3].is_type(LASitem::WAVEPACKET13)) { if (num_items == 4) { if (point_type) *point_type = 5; if (record_length) assert(*record_length == 63); return true; } else { if (items[4].is_type(LASitem::BYTE)) { if (num_items == 5) { if (point_type) *point_type = 5; if (record_length) assert(*record_length == (63 + items[4].size)); return true; } } } } else if (items[3].is_type(LASitem::BYTE)) { if (num_items == 4) { if (point_type) *point_type = 3; if (record_length) assert(*record_length == (34 + items[3].size)); return true; } } } } else if (items[2].is_type(LASitem::WAVEPACKET13)) { if (num_items == 3) { if (point_type) *point_type = 4; if (record_length) assert(*record_length == 57); return true; } else { if (items[3].is_type(LASitem::BYTE)) { if (num_items == 4) { if (point_type) *point_type = 4; if (record_length) assert(*record_length == (57 + items[3].size)); return true; } } } } else if (items[2].is_type(LASitem::BYTE)) { if (num_items == 3) { if (point_type) *point_type = 1; if (record_length) assert(*record_length == (28 + items[2].size)); return true; } } } } else if (items[1].is_type(LASitem::RGB12)) { if (num_items == 2) { if (point_type) *point_type = 2; if (record_length) assert(*record_length == 26); return true; } else { if (items[2].is_type(LASitem::BYTE)) { if (num_items == 3) { if (point_type) *point_type = 2; if (record_length) assert(*record_length == (26 + items[2].size)); return true; } } } } else if (items[1].is_type(LASitem::BYTE)) { if (num_items == 2) { if (point_type) *point_type = 0; if (record_length) assert(*record_length == (20 + items[1].size)); return true; } } } return false; } bool LASitem::is_type(LASitem::Type t) const { if (t != type) return false; switch (t) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported() const { switch (type) { case POINT10: if (size != 20) return false; if (version > 2) return false; break; case GPSTIME11: if (size != 8) return false; if (version > 2) return false; break; case RGB12: if (size != 6) return false; if (version > 2) return false; break; case WAVEPACKET13: if (size != 29) return false; if (version > 1) return false; break; case BYTE: if (size < 1) return false; if (version > 2) return false; break; default: return false; } return true; } const char* LASitem::get_name() const { switch (type) { case POINT10: return "POINT10"; break; case GPSTIME11: return "GPSTIME11"; break; case RGB12: return "RGB12"; break; case WAVEPACKET13: return "WAVEPACKET13"; break; case BYTE: return "BYTE"; break; default: break; } return 0; } <|endoftext|>
<commit_before>#define MS_CLASS "RTC::Codecs::H264" // #define MS_LOG_DEV #include "RTC/Codecs/H264.hpp" #include "Logger.hpp" #include "Utils.hpp" namespace RTC { namespace Codecs { /* Class methods. */ H264::PayloadDescriptor* H264::Parse( const uint8_t* data, size_t len, RTC::RtpPacket::FrameMarking* frameMarking, uint8_t frameMarkingLen) { MS_TRACE(); if (len < 2) return nullptr; std::unique_ptr<PayloadDescriptor> payloadDescriptor(new PayloadDescriptor()); // Use frame-marking. if (frameMarking) { // Read fields. payloadDescriptor->s = frameMarking->start; payloadDescriptor->e = frameMarking->end; payloadDescriptor->i = frameMarking->independent; payloadDescriptor->d = frameMarking->discardable; payloadDescriptor->b = frameMarking->base; payloadDescriptor->tid = frameMarking->tid; payloadDescriptor->hasTid = true; if (frameMarkingLen >= 2) { payloadDescriptor->hasLid = true; payloadDescriptor->lid = frameMarking->lid; } if (frameMarkingLen == 3) { payloadDescriptor->hasTl0picidx = true; payloadDescriptor->tl0picidx = frameMarking->tl0picidx; } // Detect key frame. if (frameMarking->start && frameMarking->independent) payloadDescriptor->isKeyFrame = true; } // NOTE: Unfortunately libwebrtc produces wrong Frame-Marking (without i=1 in // keyframes) when it uses H264 hardware encoder (at least in Mac): // https://bugs.chromium.org/p/webrtc/issues/detail?id=10746 // // As a temporal workaround, always do payload parsing to detect keyframes if // there is no frame-marking or if there is but keyframe was not detected above. if (!frameMarking || !payloadDescriptor->isKeyFrame) { uint8_t nal = *data & 0x1F; switch (nal) { // Single NAL unit packet. // IDR (instantaneous decoding picture). case 7: { payloadDescriptor->isKeyFrame = true; break; } // Aggreation packet. // STAP-A. case 24: { size_t offset{ 1 }; len -= 1; // Iterate NAL units. while (len >= 3) { auto naluSize = Utils::Byte::Get2Bytes(data, offset); uint8_t subnal = *(data + offset + sizeof(naluSize)) & 0x1F; if (subnal == 7) { payloadDescriptor->isKeyFrame = true; break; } // Check if there is room for the indicated NAL unit size. if (len < (naluSize + sizeof(naluSize))) break; offset += naluSize + sizeof(naluSize); len -= naluSize + sizeof(naluSize); } break; } // Aggreation packet. // FU-A, FU-B. case 28: case 29: { uint8_t subnal = *(data + 1) & 0x1F; uint8_t startBit = *(data + 1) & 0x80; if (subnal == 7 && startBit == 128) payloadDescriptor->isKeyFrame = true; break; } } } return payloadDescriptor.release(); } void H264::ProcessRtpPacket(RTC::RtpPacket* packet) { MS_TRACE(); auto* data = packet->GetPayload(); auto len = packet->GetPayloadLength(); RtpPacket::FrameMarking* frameMarking{ nullptr }; uint8_t frameMarkingLen{ 0 }; // Read frame-marking. packet->ReadFrameMarking(&frameMarking, frameMarkingLen); PayloadDescriptor* payloadDescriptor = H264::Parse(data, len, frameMarking, frameMarkingLen); if (!payloadDescriptor) return; auto* payloadDescriptorHandler = new PayloadDescriptorHandler(payloadDescriptor); packet->SetPayloadDescriptorHandler(payloadDescriptorHandler); } /* Instance methods. */ void H264::PayloadDescriptor::Dump() const { MS_TRACE(); MS_DUMP("<PayloadDescriptor>"); MS_DUMP( " s:%" PRIu8 "|e:%" PRIu8 "|i:%" PRIu8 "|d:%" PRIu8 "|b:%" PRIu8, this->s, this->e, this->i, this->d, this->b); if (this->hasTid) MS_DUMP(" tid : %" PRIu8, this->tid); if (this->hasLid) MS_DUMP(" lid : %" PRIu8, this->lid); if (this->hasTl0picidx) MS_DUMP(" tl0picidx : %" PRIu8, this->tl0picidx); MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false"); MS_DUMP("</PayloadDescriptor>"); } H264::PayloadDescriptorHandler::PayloadDescriptorHandler(H264::PayloadDescriptor* payloadDescriptor) { MS_TRACE(); this->payloadDescriptor.reset(payloadDescriptor); } bool H264::PayloadDescriptorHandler::Process( RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/, bool& /*marker*/) { MS_TRACE(); auto* context = static_cast<RTC::Codecs::H264::EncodingContext*>(encodingContext); MS_ASSERT(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1"); // Check if the payload should contain temporal layer info. if (context->GetTemporalLayers() > 1 && !this->payloadDescriptor->hasTid) { MS_WARN_DEV(rtp, "stream is supposed to have >1 temporal layers but does not have tid field"); } // clang-format off if ( this->payloadDescriptor->hasTid && this->payloadDescriptor->tid > context->GetTargetTemporalLayer() ) // clang-format on { return false; } // Upgrade required. Drop current packet if base flag is not set. // TODO: Cannot enable this until this issue is fixed (in libwebrtc?): // https://github.com/versatica/mediasoup/issues/306 // // clang-format off // else if ( // this->payloadDescriptor->hasTid && // this->payloadDescriptor->tid > context->GetCurrentTemporalLayer() && // !this->payloadDescriptor->b // ) // // clang-format on // { // return false; // } // Update/fix current temporal layer. // clang-format off if ( this->payloadDescriptor->hasTid && this->payloadDescriptor->tid > context->GetCurrentTemporalLayer() ) // clang-format on { context->SetCurrentTemporalLayer(this->payloadDescriptor->tid); } else { context->SetCurrentTemporalLayer(0); } if (context->GetCurrentTemporalLayer() > context->GetTargetTemporalLayer()) context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer()); return true; } void H264::PayloadDescriptorHandler::Restore(uint8_t* /*data*/) { MS_TRACE(); } } // namespace Codecs } // namespace RTC <commit_msg>Fix typo in MS_WARN_DEV() usage<commit_after>#define MS_CLASS "RTC::Codecs::H264" // #define MS_LOG_DEV #include "RTC/Codecs/H264.hpp" #include "Logger.hpp" #include "Utils.hpp" namespace RTC { namespace Codecs { /* Class methods. */ H264::PayloadDescriptor* H264::Parse( const uint8_t* data, size_t len, RTC::RtpPacket::FrameMarking* frameMarking, uint8_t frameMarkingLen) { MS_TRACE(); if (len < 2) return nullptr; std::unique_ptr<PayloadDescriptor> payloadDescriptor(new PayloadDescriptor()); // Use frame-marking. if (frameMarking) { // Read fields. payloadDescriptor->s = frameMarking->start; payloadDescriptor->e = frameMarking->end; payloadDescriptor->i = frameMarking->independent; payloadDescriptor->d = frameMarking->discardable; payloadDescriptor->b = frameMarking->base; payloadDescriptor->tid = frameMarking->tid; payloadDescriptor->hasTid = true; if (frameMarkingLen >= 2) { payloadDescriptor->hasLid = true; payloadDescriptor->lid = frameMarking->lid; } if (frameMarkingLen == 3) { payloadDescriptor->hasTl0picidx = true; payloadDescriptor->tl0picidx = frameMarking->tl0picidx; } // Detect key frame. if (frameMarking->start && frameMarking->independent) payloadDescriptor->isKeyFrame = true; } // NOTE: Unfortunately libwebrtc produces wrong Frame-Marking (without i=1 in // keyframes) when it uses H264 hardware encoder (at least in Mac): // https://bugs.chromium.org/p/webrtc/issues/detail?id=10746 // // As a temporal workaround, always do payload parsing to detect keyframes if // there is no frame-marking or if there is but keyframe was not detected above. if (!frameMarking || !payloadDescriptor->isKeyFrame) { uint8_t nal = *data & 0x1F; switch (nal) { // Single NAL unit packet. // IDR (instantaneous decoding picture). case 7: { payloadDescriptor->isKeyFrame = true; break; } // Aggreation packet. // STAP-A. case 24: { size_t offset{ 1 }; len -= 1; // Iterate NAL units. while (len >= 3) { auto naluSize = Utils::Byte::Get2Bytes(data, offset); uint8_t subnal = *(data + offset + sizeof(naluSize)) & 0x1F; if (subnal == 7) { payloadDescriptor->isKeyFrame = true; break; } // Check if there is room for the indicated NAL unit size. if (len < (naluSize + sizeof(naluSize))) break; offset += naluSize + sizeof(naluSize); len -= naluSize + sizeof(naluSize); } break; } // Aggreation packet. // FU-A, FU-B. case 28: case 29: { uint8_t subnal = *(data + 1) & 0x1F; uint8_t startBit = *(data + 1) & 0x80; if (subnal == 7 && startBit == 128) payloadDescriptor->isKeyFrame = true; break; } } } return payloadDescriptor.release(); } void H264::ProcessRtpPacket(RTC::RtpPacket* packet) { MS_TRACE(); auto* data = packet->GetPayload(); auto len = packet->GetPayloadLength(); RtpPacket::FrameMarking* frameMarking{ nullptr }; uint8_t frameMarkingLen{ 0 }; // Read frame-marking. packet->ReadFrameMarking(&frameMarking, frameMarkingLen); PayloadDescriptor* payloadDescriptor = H264::Parse(data, len, frameMarking, frameMarkingLen); if (!payloadDescriptor) return; auto* payloadDescriptorHandler = new PayloadDescriptorHandler(payloadDescriptor); packet->SetPayloadDescriptorHandler(payloadDescriptorHandler); } /* Instance methods. */ void H264::PayloadDescriptor::Dump() const { MS_TRACE(); MS_DUMP("<PayloadDescriptor>"); MS_DUMP( " s:%" PRIu8 "|e:%" PRIu8 "|i:%" PRIu8 "|d:%" PRIu8 "|b:%" PRIu8, this->s, this->e, this->i, this->d, this->b); if (this->hasTid) MS_DUMP(" tid : %" PRIu8, this->tid); if (this->hasLid) MS_DUMP(" lid : %" PRIu8, this->lid); if (this->hasTl0picidx) MS_DUMP(" tl0picidx : %" PRIu8, this->tl0picidx); MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false"); MS_DUMP("</PayloadDescriptor>"); } H264::PayloadDescriptorHandler::PayloadDescriptorHandler(H264::PayloadDescriptor* payloadDescriptor) { MS_TRACE(); this->payloadDescriptor.reset(payloadDescriptor); } bool H264::PayloadDescriptorHandler::Process( RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/, bool& /*marker*/) { MS_TRACE(); auto* context = static_cast<RTC::Codecs::H264::EncodingContext*>(encodingContext); MS_ASSERT(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1"); // Check if the payload should contain temporal layer info. if (context->GetTemporalLayers() > 1 && !this->payloadDescriptor->hasTid) { MS_WARN_DEV("stream is supposed to have >1 temporal layers but does not have tid field"); } // clang-format off if ( this->payloadDescriptor->hasTid && this->payloadDescriptor->tid > context->GetTargetTemporalLayer() ) // clang-format on { return false; } // Upgrade required. Drop current packet if base flag is not set. // TODO: Cannot enable this until this issue is fixed (in libwebrtc?): // https://github.com/versatica/mediasoup/issues/306 // // clang-format off // else if ( // this->payloadDescriptor->hasTid && // this->payloadDescriptor->tid > context->GetCurrentTemporalLayer() && // !this->payloadDescriptor->b // ) // // clang-format on // { // return false; // } // Update/fix current temporal layer. // clang-format off if ( this->payloadDescriptor->hasTid && this->payloadDescriptor->tid > context->GetCurrentTemporalLayer() ) // clang-format on { context->SetCurrentTemporalLayer(this->payloadDescriptor->tid); } else { context->SetCurrentTemporalLayer(0); } if (context->GetCurrentTemporalLayer() > context->GetTargetTemporalLayer()) context->SetCurrentTemporalLayer(context->GetTargetTemporalLayer()); return true; } void H264::PayloadDescriptorHandler::Restore(uint8_t* /*data*/) { MS_TRACE(); } } // namespace Codecs } // namespace RTC <|endoftext|>
<commit_before>#define MS_CLASS "RTC::RtpReceiver" // #define MS_LOG_DEV #include "RTC/RtpReceiver.h" #include "RTC/Transport.h" #include "Utils.h" #include "MediaSoupError.h" #include "Logger.h" namespace RTC { /* Instance methods. */ RtpReceiver::RtpReceiver(Listener* listener, Channel::Notifier* notifier, uint32_t rtpReceiverId, RTC::Media::Kind kind) : rtpReceiverId(rtpReceiverId), kind(kind), listener(listener), notifier(notifier) { MS_TRACE(); // Create an RtpStream. switch (kind) { case RTC::Media::Kind::VIDEO: case RTC::Media::Kind::DEPTH: this->rtpStream = new RTC::RtpStream(200); // Buffer up to 200 packets. break; case RTC::Media::Kind::AUDIO: this->rtpStream = new RTC::RtpStream(0); // No buffer for audio streams. break; default: ; } } RtpReceiver::~RtpReceiver() { MS_TRACE(); } void RtpReceiver::Close() { MS_TRACE(); static const Json::StaticString k_class("class"); Json::Value event_data(Json::objectValue); if (this->rtpParameters) delete this->rtpParameters; if (this->rtpStream) delete this->rtpStream; // Notify. event_data[k_class] = "RtpReceiver"; this->notifier->Emit(this->rtpReceiverId, "close", event_data); // Notify the listener. this->listener->onRtpReceiverClosed(this); delete this; } Json::Value RtpReceiver::toJson() { MS_TRACE(); static Json::Value null_data(Json::nullValue); static const Json::StaticString k_rtpReceiverId("rtpReceiverId"); static const Json::StaticString k_kind("kind"); static const Json::StaticString k_rtpParameters("rtpParameters"); static const Json::StaticString k_hasTransport("hasTransport"); static const Json::StaticString k_rtpRawEventEnabled("rtpRawEventEnabled"); static const Json::StaticString k_rtpObjectEventEnabled("rtpObjectEventEnabled"); Json::Value json(Json::objectValue); json[k_rtpReceiverId] = (Json::UInt)this->rtpReceiverId; json[k_kind] = RTC::Media::GetJsonString(this->kind); if (this->rtpParameters) json[k_rtpParameters] = this->rtpParameters->toJson(); else json[k_rtpParameters] = null_data; json[k_hasTransport] = this->transport ? true : false; json[k_rtpRawEventEnabled] = this->rtpRawEventEnabled; json[k_rtpObjectEventEnabled] = this->rtpObjectEventEnabled; return json; } void RtpReceiver::HandleRequest(Channel::Request* request) { MS_TRACE(); switch (request->methodId) { case Channel::Request::MethodId::rtpReceiver_close: { #ifdef MS_LOG_DEV uint32_t rtpReceiverId = this->rtpReceiverId; #endif Close(); MS_DEBUG_DEV("RtpReceiver closed [rtpReceiverId:%" PRIu32 "]", rtpReceiverId); request->Accept(); break; } case Channel::Request::MethodId::rtpReceiver_dump: { Json::Value json = toJson(); request->Accept(json); break; } case Channel::Request::MethodId::rtpReceiver_receive: { // Keep a reference to the previous rtpParameters. auto previousRtpParameters = this->rtpParameters; try { this->rtpParameters = new RTC::RtpParameters(request->data); } catch (const MediaSoupError &error) { request->Reject(error.what()); return; } // NOTE: this may throw. If so keep the current parameters. try { this->listener->onRtpReceiverParameters(this); } catch (const MediaSoupError &error) { // Rollback previous parameters. this->rtpParameters = previousRtpParameters; request->Reject(error.what()); return; } // Free the previous rtpParameters. if (previousRtpParameters) delete previousRtpParameters; Json::Value data = this->rtpParameters->toJson(); request->Accept(data); // Fill RTP parameters. FillRtpParameters(); // And notify again. this->listener->onRtpReceiverParametersDone(this); break; } case Channel::Request::MethodId::rtpReceiver_setRtpRawEvent: { static const Json::StaticString k_enabled("enabled"); if (!request->data[k_enabled].isBool()) { request->Reject("Request has invalid data.enabled"); return; } this->rtpRawEventEnabled = request->data[k_enabled].asBool(); request->Accept(); break; } case Channel::Request::MethodId::rtpReceiver_setRtpObjectEvent: { static const Json::StaticString k_enabled("enabled"); if (!request->data[k_enabled].isBool()) { request->Reject("Request has invalid data.enabled"); return; } this->rtpObjectEventEnabled = request->data[k_enabled].asBool(); request->Accept(); break; } default: { MS_ERROR("unknown method"); request->Reject("unknown method"); } } } void RtpReceiver::ReceiveRtpPacket(RTC::RtpPacket* packet) { MS_TRACE(); static const Json::StaticString k_class("class"); static const Json::StaticString k_object("object"); static const Json::StaticString k_payloadType("payloadType"); static const Json::StaticString k_marker("marker"); static const Json::StaticString k_sequenceNumber("sequenceNumber"); static const Json::StaticString k_timestamp("timestamp"); static const Json::StaticString k_ssrc("ssrc"); // TODO: Check if stopped, etc (not yet done). // Process the packet. // TODO: Must check what kind of packet we are checking. For example, RTX // packets (once implemented) should have a different handling. if (!this->rtpStream->ReceivePacket(packet)) return; // Notify the listener. this->listener->onRtpPacket(this, packet); // Emit "rtpraw" if enabled. if (this->rtpRawEventEnabled) { Json::Value event_data(Json::objectValue); event_data[k_class] = "RtpReceiver"; this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpraw", event_data, packet->GetRaw(), packet->GetLength()); } // Emit "rtpobject" is enabled. if (this->rtpObjectEventEnabled) { Json::Value event_data(Json::objectValue); Json::Value json_object(Json::objectValue); event_data[k_class] = "RtpReceiver"; json_object[k_payloadType] = (Json::UInt)packet->GetPayloadType(); json_object[k_marker] = packet->HasMarker(); json_object[k_sequenceNumber] = (Json::UInt)packet->GetSequenceNumber(); json_object[k_timestamp] = (Json::UInt)packet->GetTimestamp(); json_object[k_ssrc] = (Json::UInt)packet->GetSsrc(); event_data[k_object] = json_object; this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpobject", event_data, packet->GetPayload(), packet->GetPayloadLength()); } } void RtpReceiver::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container) { MS_TRACE(); // Proxy the request to the RtpStream. if (this->rtpStream) this->rtpStream->RequestRtpRetransmission(seq, bitmask, container); } void RtpReceiver::FillRtpParameters() { MS_TRACE(); // Set a random muxId. this->rtpParameters->muxId = Utils::Crypto::GetRandomString(8); // TODO: Fill SSRCs with random values and set some mechanism to replace // SSRC values in received RTP packets to match the chosen random values. } void RtpReceiver::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report) { MS_TRACE(); this->receiverReport.reset(new RTC::RTCP::ReceiverReport(report)); this->receiverReport->Serialize(); }; void RtpReceiver::ReceiveRtcpFeedback(RTC::RTCP::FeedbackPsPacket* packet) { MS_TRACE(); this->transport->SendRtcpPacket(packet); }; void RtpReceiver::ReceiveRtcpFeedback(RTC::RTCP::FeedbackRtpPacket* packet) { MS_TRACE(); this->transport->SendRtcpPacket(packet); }; } <commit_msg>RtpReceiver: always check that transport exist before sending RTCP<commit_after>#define MS_CLASS "RTC::RtpReceiver" // #define MS_LOG_DEV #include "RTC/RtpReceiver.h" #include "RTC/Transport.h" #include "Utils.h" #include "MediaSoupError.h" #include "Logger.h" namespace RTC { /* Instance methods. */ RtpReceiver::RtpReceiver(Listener* listener, Channel::Notifier* notifier, uint32_t rtpReceiverId, RTC::Media::Kind kind) : rtpReceiverId(rtpReceiverId), kind(kind), listener(listener), notifier(notifier) { MS_TRACE(); // Create an RtpStream. switch (kind) { case RTC::Media::Kind::VIDEO: case RTC::Media::Kind::DEPTH: this->rtpStream = new RTC::RtpStream(200); // Buffer up to 200 packets. break; case RTC::Media::Kind::AUDIO: this->rtpStream = new RTC::RtpStream(0); // No buffer for audio streams. break; default: ; } } RtpReceiver::~RtpReceiver() { MS_TRACE(); } void RtpReceiver::Close() { MS_TRACE(); static const Json::StaticString k_class("class"); Json::Value event_data(Json::objectValue); if (this->rtpParameters) delete this->rtpParameters; if (this->rtpStream) delete this->rtpStream; // Notify. event_data[k_class] = "RtpReceiver"; this->notifier->Emit(this->rtpReceiverId, "close", event_data); // Notify the listener. this->listener->onRtpReceiverClosed(this); delete this; } Json::Value RtpReceiver::toJson() { MS_TRACE(); static Json::Value null_data(Json::nullValue); static const Json::StaticString k_rtpReceiverId("rtpReceiverId"); static const Json::StaticString k_kind("kind"); static const Json::StaticString k_rtpParameters("rtpParameters"); static const Json::StaticString k_hasTransport("hasTransport"); static const Json::StaticString k_rtpRawEventEnabled("rtpRawEventEnabled"); static const Json::StaticString k_rtpObjectEventEnabled("rtpObjectEventEnabled"); Json::Value json(Json::objectValue); json[k_rtpReceiverId] = (Json::UInt)this->rtpReceiverId; json[k_kind] = RTC::Media::GetJsonString(this->kind); if (this->rtpParameters) json[k_rtpParameters] = this->rtpParameters->toJson(); else json[k_rtpParameters] = null_data; json[k_hasTransport] = this->transport ? true : false; json[k_rtpRawEventEnabled] = this->rtpRawEventEnabled; json[k_rtpObjectEventEnabled] = this->rtpObjectEventEnabled; return json; } void RtpReceiver::HandleRequest(Channel::Request* request) { MS_TRACE(); switch (request->methodId) { case Channel::Request::MethodId::rtpReceiver_close: { #ifdef MS_LOG_DEV uint32_t rtpReceiverId = this->rtpReceiverId; #endif Close(); MS_DEBUG_DEV("RtpReceiver closed [rtpReceiverId:%" PRIu32 "]", rtpReceiverId); request->Accept(); break; } case Channel::Request::MethodId::rtpReceiver_dump: { Json::Value json = toJson(); request->Accept(json); break; } case Channel::Request::MethodId::rtpReceiver_receive: { // Keep a reference to the previous rtpParameters. auto previousRtpParameters = this->rtpParameters; try { this->rtpParameters = new RTC::RtpParameters(request->data); } catch (const MediaSoupError &error) { request->Reject(error.what()); return; } // NOTE: this may throw. If so keep the current parameters. try { this->listener->onRtpReceiverParameters(this); } catch (const MediaSoupError &error) { // Rollback previous parameters. this->rtpParameters = previousRtpParameters; request->Reject(error.what()); return; } // Free the previous rtpParameters. if (previousRtpParameters) delete previousRtpParameters; Json::Value data = this->rtpParameters->toJson(); request->Accept(data); // Fill RTP parameters. FillRtpParameters(); // And notify again. this->listener->onRtpReceiverParametersDone(this); break; } case Channel::Request::MethodId::rtpReceiver_setRtpRawEvent: { static const Json::StaticString k_enabled("enabled"); if (!request->data[k_enabled].isBool()) { request->Reject("Request has invalid data.enabled"); return; } this->rtpRawEventEnabled = request->data[k_enabled].asBool(); request->Accept(); break; } case Channel::Request::MethodId::rtpReceiver_setRtpObjectEvent: { static const Json::StaticString k_enabled("enabled"); if (!request->data[k_enabled].isBool()) { request->Reject("Request has invalid data.enabled"); return; } this->rtpObjectEventEnabled = request->data[k_enabled].asBool(); request->Accept(); break; } default: { MS_ERROR("unknown method"); request->Reject("unknown method"); } } } void RtpReceiver::ReceiveRtpPacket(RTC::RtpPacket* packet) { MS_TRACE(); static const Json::StaticString k_class("class"); static const Json::StaticString k_object("object"); static const Json::StaticString k_payloadType("payloadType"); static const Json::StaticString k_marker("marker"); static const Json::StaticString k_sequenceNumber("sequenceNumber"); static const Json::StaticString k_timestamp("timestamp"); static const Json::StaticString k_ssrc("ssrc"); // TODO: Check if stopped, etc (not yet done). // Process the packet. // TODO: Must check what kind of packet we are checking. For example, RTX // packets (once implemented) should have a different handling. if (!this->rtpStream->ReceivePacket(packet)) return; // Notify the listener. this->listener->onRtpPacket(this, packet); // Emit "rtpraw" if enabled. if (this->rtpRawEventEnabled) { Json::Value event_data(Json::objectValue); event_data[k_class] = "RtpReceiver"; this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpraw", event_data, packet->GetRaw(), packet->GetLength()); } // Emit "rtpobject" is enabled. if (this->rtpObjectEventEnabled) { Json::Value event_data(Json::objectValue); Json::Value json_object(Json::objectValue); event_data[k_class] = "RtpReceiver"; json_object[k_payloadType] = (Json::UInt)packet->GetPayloadType(); json_object[k_marker] = packet->HasMarker(); json_object[k_sequenceNumber] = (Json::UInt)packet->GetSequenceNumber(); json_object[k_timestamp] = (Json::UInt)packet->GetTimestamp(); json_object[k_ssrc] = (Json::UInt)packet->GetSsrc(); event_data[k_object] = json_object; this->notifier->EmitWithBinary(this->rtpReceiverId, "rtpobject", event_data, packet->GetPayload(), packet->GetPayloadLength()); } } void RtpReceiver::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container) { MS_TRACE(); // Proxy the request to the RtpStream. if (this->rtpStream) this->rtpStream->RequestRtpRetransmission(seq, bitmask, container); } void RtpReceiver::FillRtpParameters() { MS_TRACE(); // Set a random muxId. this->rtpParameters->muxId = Utils::Crypto::GetRandomString(8); // TODO: Fill SSRCs with random values and set some mechanism to replace // SSRC values in received RTP packets to match the chosen random values. } void RtpReceiver::ReceiveRtcpReceiverReport(RTC::RTCP::ReceiverReport* report) { MS_TRACE(); this->receiverReport.reset(new RTC::RTCP::ReceiverReport(report)); this->receiverReport->Serialize(); }; void RtpReceiver::ReceiveRtcpFeedback(RTC::RTCP::FeedbackPsPacket* packet) { MS_TRACE(); if (this->transport) this->transport->SendRtcpPacket(packet); }; void RtpReceiver::ReceiveRtcpFeedback(RTC::RTCP::FeedbackRtpPacket* packet) { MS_TRACE(); if (this->transport) this->transport->SendRtcpPacket(packet); }; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <test/agrad/distributions/expect_eq_diffs.hpp> #include <stan/agrad/agrad.hpp> #include <stan/agrad/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp> template <typename T_shape, typename T_inv_scale> void expect_propto(int n1, T_shape alpha1, T_inv_scale beta1, int n2, T_shape alpha2, T_inv_scale beta2, std::string message) { expect_eq_diffs(stan::prob::neg_binomial_log<false>(n1,alpha1,beta1), stan::prob::neg_binomial_log<false>(n2,alpha2,beta2), stan::prob::neg_binomial_log<true>(n1,alpha1,beta1), stan::prob::neg_binomial_log<true>(n2,alpha2,beta2), message); } using stan::agrad::var; TEST(AgradDistributionsNegBinomial,Propto) { int n = 10; expect_propto<var,var>(n,2.5,2.0, n,5.0,3.0, "var: alpha and beta"); } TEST(AgradDistributionsNegBinomial,ProptoAlpha) { int n = 10; double beta = 3.0; expect_propto<var,double>(n, 0.2, beta, n, 6.0, beta, "var: alpha"); } TEST(AgradDistributionsNegBinomial,ProptoBeta) { int n = 10; double alpha = 6.0; expect_propto<double,var>(n, alpha, 1.0, n, alpha, 1.5, "var: beta"); } <commit_msg>updating agrad neg_binomial test<commit_after>#define _LOG_PROB_ neg_binomial_log #include <stan/prob/distributions/univariate/discrete/neg_binomial.hpp> #include <test/agrad/distributions/distribution_test_fixture.hpp> #include <test/agrad/distributions/distribution_tests_1_discrete_2_params.hpp> using std::vector; using std::numeric_limits; using stan::agrad::var; class AgradDistributionsNegBinomial : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters) { vector<double> param(3); param[0] = 10; // n param[1] = 2.0; // alpha param[2] = 1.5; // beta parameters.push_back(param); param[0] = 100; // n param[1] = 3.0; // alpha param[2] = 3.5; // beta parameters.push_back(param); } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); // alpha index.push_back(1U); value.push_back(0); // beta index.push_back(2U); value.push_back(0); } template <class T_shape, class T_inv_scale> var log_prob(const int n, const T_shape& alpha, const T_inv_scale& beta) { using std::log; using stan::math::binomial_coefficient_log; using stan::math::log1m; using stan::prob::include_summand; var logp(0); // Special case where negative binomial reduces to Poisson if (alpha > 1e10) { if (include_summand<true>::value) logp -= lgamma(n + 1.0); if (include_summand<true,T_shape>::value || include_summand<true,T_inv_scale>::value) { typename stan::return_type<T_shape, T_inv_scale>::type lambda; lambda = alpha / beta; logp += multiply_log(n, lambda) - lambda; } return logp; } // More typical cases if (include_summand<true,T_shape>::value) if (n != 0) logp += binomial_coefficient_log<typename stan::scalar_type<T_shape>::type> (n + alpha - 1.0, n); if (include_summand<true,T_shape,T_inv_scale>::value) logp += -n * log1p(beta) + alpha * log(beta / (1 + beta)); return logp; } }; INSTANTIATE_TYPED_TEST_CASE_P(AgradDistributionsNegBinomial, AgradDistributionTestFixture, AgradDistributionsNegBinomial); <|endoftext|>
<commit_before>#include <algorithm> #include <numeric> #include <stdexcept> #include <assert.h> #include "definitions.hpp" using namespace std; namespace craam { /** \mainpage Introduction ------------ Craam is a C++ library for solving *plain*, *robust*, or *optimistic* Markov decision processes. The library also provides basic tools that enable simulation and construction of MDPs from samples. There is also support for state aggregation and abstraction solution methods. The library supports standard finite or infinite horizon discounted MDPs [Puterman2005]. Some basic stochastic shortest path methods are also supported. The library assumes *maximization* over actions. The states and actions must be finite. The robust model extends the regular MDPs [Iyengar2005]. The library allows to model uncertainty in *both* the transitions and rewards, unlike some published papers on this topic. This is modeled by adding an outcome to each action. The outcome is assumed to be minimized by nature, similar to [Filar1997]. In summary, the MDP problem being solved is: \f[v(s) = \max_{a \in \mathcal{A}} \min_{o \in \mathcal{O}} \sum_{s\in\mathcal{S}} ( r(s,a,o,s') + \gamma P(s,a,o,s') v(s') ) ~.\f] Here, \f$\mathcal{S}\f$ are the states, \f$\mathcal{A}\f$ are the actions, \f$\mathcal{O}\f$ are the outcomes. Available algorithms are *value iteration* and *modified policy iteration*. The library support both the plain worst-case outcome method and a worst case with respect to a base distribution. Installation and Build Instruction ---------------------------------- See the README.rst Getting Started --------------- The main interface to the library is through the templated class GRMDP. The templated version of this class enable different definitions of the uncertainty set. The available specializations are: - craam::MDP : plain MDP with no definition of uncertainty - craam::RMDP_D : a robust/uncertain with discrete outcomes with the best/worst one chosen - craam::RMDP_L1 : a robust/uncertain with discrete outcomes with L1 constraints on the uncertainty States, actions, and outcomes are identified using 0-based contiguous indexes. The actions are indexed independently for each states and the outcomes are indexed independently for each state and action pair. Transitions are added through function add_transition. New states, actions, or outcomes are automatically added based on the new transition. Main supported solution methods are: | Method | Algorithm | | ----------------------- | ---------------- | GRMDP::vi_gs | Gauss-Seidel value iteration; runs in a single thread. | GRMDP::vi_jac | Jacobi value iteration; parallelized using OpenMP. | GRMDP::mpi_jac | Jacobi modified policy iteration; parallelized with OpenMP. Generally, modified policy iteration is vastly more efficient than value iteration. | GRMDP::vi_jac_fix | Jacobi value iteration for policy evaluation; parallelized with OpenMP. Each of the methods above supports average, robust, and optimistic computation modes for the Nature. The following is a simple example of formulating and solving a small MDP. \code #include "RMDP.hpp" #include "modeltools.hpp" #include <iostream> #include <vector> using namespace craam; int main(){ MDP mdp(3); // transitions for action 0 add_transition(mdp,0,0,0,1,0); add_transition(mdp,1,0,0,1,1); add_transition(mdp,2,0,1,1,1); // transitions for action 1 add_transition(mdp,0,1,1,1,0); add_transition(mdp,1,1,2,1,0); add_transition(mdp,2,1,2,1,1.1); // solve using Jacobi value iteration auto&& re = mdp.mpi_jac(Uncertainty::Average,0.9); for(auto v : re.valuefunction){ cout << v << " "; } return 0; } \endcode To compile the file, run: \code{.sh} $ g++ -fopenmp -std=c++11 -I<path_to_RAAM.hpp> -L <path_to_libcraam.a> simple.cpp -lcraam \endcode Notice that the order of the arguments matters (`-lcraam` must follow the file name). Also note that the library first needs to be build. See the README file for the instructions. Common Use Cases ---------------- 1. Formulate an uncertain MDP 2. Compute a solution to an uncertain MDP 3. Compute value of a fixed policy 4. Compute an occupancy frequency 5. Simulate transitions of an MDP 6. Construct MDP from samples 7. Simulate a general domain General Assumptions ------------------- - Transition probabilities must be non-negative but do not need to add up to one - Transitions with 0 probabilities may be omitted, except there must be at least one target state in each transition - **State with no actions**: A terminal state with value 0 - **Action with no outcomes**: Terminates with an error - **Outcome with no target states**: Terminates with an error References ---------- [Filar1997] Filar, J., & Vrieze, K. (1997). Competitive Markov decision processes. Springer. [Puterman2005] Puterman, M. L. (2005). Markov decision processes: Discrete stochastic dynamic programming. Handbooks in operations research and management …. John Wiley & Sons, Inc. [Iyengar2005] Iyengar, G. N. G. (2005). Robust dynamic programming. Mathematics of Operations Research, 30(2), 1–29. [Petrik2014] Petrik, M., Subramanian S. (2014). RAAM : The benefits of robustness in approximating aggregated MDPs in reinforcement learning. In Neural Information Processing Systems (NIPS). [Petrik2016] Petrik, M., & Luss, R. (2016). Interpretable Policies for Dynamic Product Recommendations. In Uncertainty in Artificial Intelligence (UAI). */ template <typename T> vector<size_t> sort_indexes(vector<T> const& v) { /** \brief Sort indices by values in ascending order * * \param v List of values * \return Sorted indices */ // initialize original index locations vector<size_t> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];}); return idx; } template vector<size_t> sort_indexes<long>(vector<long> const&); template <typename T> vector<size_t> sort_indexes_desc(vector<T> const& v) { /** \brief Sort indices by values in descending order * * \param v List of values * \return Sorted indices */ // initialize original index locations vector<size_t> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] > v[i2];}); return idx; } pair<numvec,prec_t> worstcase_l1(numvec const& z, numvec const& q, prec_t t){ /** Computes the solution of: min_p p^T * z s.t. ||p - q|| <= t 1^T p = 1 p >= 0 Notes ----- This implementation works in O(n log n) time because of the sort. Using quickselect to choose the right quantile would work in O(n) time. This function does not check whether the probability distribution sums to 1. **/ assert(*min_element(q.begin(), q.end()) >= 0 && *max_element(q.begin(), q.end()) <= 1); assert(z.size() > 0); assert(t >= 0.0 && t <= 2.0); assert(z.size() == q.size()); size_t sz = z.size(); vector<size_t> smallest = sort_indexes<prec_t>(z); numvec o(q); auto k = smallest[0]; auto epsilon = min(t/2, 1-q[k]); o[k] += epsilon; auto i = sz - 1; while(epsilon > 0){ k = smallest[i]; auto diff = min( epsilon, o[k] ); o[k] -= diff; epsilon -= diff; i -= 1; } auto r = inner_product(o.begin(),o.end(),z.begin(), (prec_t) 0.0); return make_pair(move(o),r); } } <commit_msg>furher updates to the documentation<commit_after>#include <algorithm> #include <numeric> #include <stdexcept> #include <assert.h> #include "definitions.hpp" using namespace std; namespace craam { /** \mainpage Introduction ------------ Craam is a C++ library for solving *plain*, *robust*, or *optimistic* Markov decision processes. The library also provides basic tools that enable simulation and construction of MDPs from samples. There is also support for state aggregation and abstraction solution methods. The library supports standard finite or infinite horizon discounted MDPs [Puterman2005]. Some basic stochastic shortest path methods are also supported. The library assumes *maximization* over actions. The states and actions must be finite. The robust model extends the regular MDPs [Iyengar2005]. The library allows to model uncertainty in *both* the transitions and rewards, unlike some published papers on this topic. This is modeled by adding an outcome to each action. The outcome is assumed to be minimized by nature, similar to [Filar1997]. In summary, the MDP problem being solved is: \f[v(s) = \max_{a \in \mathcal{A}} \min_{o \in \mathcal{O}} \sum_{s\in\mathcal{S}} ( r(s,a,o,s') + \gamma P(s,a,o,s') v(s') ) ~.\f] Here, \f$\mathcal{S}\f$ are the states, \f$\mathcal{A}\f$ are the actions, \f$\mathcal{O}\f$ are the outcomes. Available algorithms are *value iteration* and *modified policy iteration*. The library support both the plain worst-case outcome method and a worst case with respect to a base distribution. Installation and Build Instruction ---------------------------------- See the README.rst Getting Started --------------- The main interface to the library is through the templated class GRMDP. The templated version of this class enable different definitions of the uncertainty set. The available specializations are: - craam::MDP : plain MDP with no definition of uncertainty - craam::RMDP_D : a robust/uncertain with discrete outcomes with the best/worst one chosen - craam::RMDP_L1 : a robust/uncertain with discrete outcomes with L1 constraints on the uncertainty States, actions, and outcomes are identified using 0-based contiguous indexes. The actions are indexed independently for each states and the outcomes are indexed independently for each state and action pair. Transitions are added through function add_transition. New states, actions, or outcomes are automatically added based on the new transition. Main supported solution methods are: | Method | Algorithm | | ----------------------- | ---------------- | GRMDP::vi_gs | Gauss-Seidel value iteration; runs in a single thread. | GRMDP::vi_jac | Jacobi value iteration; parallelized using OpenMP. | GRMDP::mpi_jac | Jacobi modified policy iteration; parallelized with OpenMP. Generally, modified policy iteration is vastly more efficient than value iteration. | GRMDP::vi_jac_fix | Jacobi value iteration for policy evaluation; parallelized with OpenMP. Each of the methods above supports average, robust, and optimistic computation modes for the Nature. The following is a simple example of formulating and solving a small MDP. \code #include "RMDP.hpp" #include "modeltools.hpp" #include <iostream> #include <vector> using namespace craam; int main(){ MDP mdp(3); // transitions for action 0 add_transition(mdp,0,0,0,1,0); add_transition(mdp,1,0,0,1,1); add_transition(mdp,2,0,1,1,1); // transitions for action 1 add_transition(mdp,0,1,1,1,0); add_transition(mdp,1,1,2,1,0); add_transition(mdp,2,1,2,1,1.1); // solve using Jacobi value iteration auto&& re = mdp.mpi_jac(Uncertainty::Average,0.9); for(auto v : re.valuefunction){ cout << v << " "; } return 0; } \endcode To compile the file, run: \code{.sh} $ g++ -fopenmp -std=c++14 -I<path_to_RAAM.hpp> -L <path_to_libcraam.a> simple.cpp -lcraam \endcode Notice that the order of the arguments matters (`-lcraam` must follow the file name). Also note that the library first needs to be build. See the README file for the instructions. Common Use Cases ---------------- 1. Formulate an uncertain MDP 2. Compute a solution to an uncertain MDP 3. Compute value of a fixed policy 4. Compute an occupancy frequency 5. Simulate transitions of an MDP 6. Construct MDP from samples 7. Simulate a general domain General Assumptions ------------------- - Transition probabilities must be non-negative but do not need to add up to one - Transitions with 0 probabilities may be omitted, except there must be at least one target state in each transition - **State with no actions**: A terminal state with value 0 - **Action with no outcomes**: Terminates with an error - **Outcome with no target states**: Terminates with an error References ---------- [Filar1997] Filar, J., & Vrieze, K. (1997). Competitive Markov decision processes. Springer. [Puterman2005] Puterman, M. L. (2005). Markov decision processes: Discrete stochastic dynamic programming. Handbooks in operations research and management …. John Wiley & Sons, Inc. [Iyengar2005] Iyengar, G. N. G. (2005). Robust dynamic programming. Mathematics of Operations Research, 30(2), 1–29. [Petrik2014] Petrik, M., Subramanian S. (2014). RAAM : The benefits of robustness in approximating aggregated MDPs in reinforcement learning. In Neural Information Processing Systems (NIPS). [Petrik2016] Petrik, M., & Luss, R. (2016). Interpretable Policies for Dynamic Product Recommendations. In Uncertainty in Artificial Intelligence (UAI). */ template <typename T> vector<size_t> sort_indexes(vector<T> const& v) { /** \brief Sort indices by values in ascending order * * \param v List of values * \return Sorted indices */ // initialize original index locations vector<size_t> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];}); return idx; } template vector<size_t> sort_indexes<long>(vector<long> const&); template <typename T> vector<size_t> sort_indexes_desc(vector<T> const& v) { /** \brief Sort indices by values in descending order * * \param v List of values * \return Sorted indices */ // initialize original index locations vector<size_t> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] > v[i2];}); return idx; } pair<numvec,prec_t> worstcase_l1(numvec const& z, numvec const& q, prec_t t){ /** Computes the solution of: min_p p^T * z s.t. ||p - q|| <= t 1^T p = 1 p >= 0 Notes ----- This implementation works in O(n log n) time because of the sort. Using quickselect to choose the right quantile would work in O(n) time. This function does not check whether the probability distribution sums to 1. **/ assert(*min_element(q.begin(), q.end()) >= 0 && *max_element(q.begin(), q.end()) <= 1); assert(z.size() > 0); assert(t >= 0.0 && t <= 2.0); assert(z.size() == q.size()); size_t sz = z.size(); vector<size_t> smallest = sort_indexes<prec_t>(z); numvec o(q); auto k = smallest[0]; auto epsilon = min(t/2, 1-q[k]); o[k] += epsilon; auto i = sz - 1; while(epsilon > 0){ k = smallest[i]; auto diff = min( epsilon, o[k] ); o[k] -= diff; epsilon -= diff; i -= 1; } auto r = inner_product(o.begin(),o.end(),z.begin(), (prec_t) 0.0); return make_pair(move(o),r); } } <|endoftext|>
<commit_before>#pragma once // pow.hpp: pow functions for posits // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw { namespace unum { // the current shims are NON-COMPLIANT with the posit standard, which says that every function must be // correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results. template<size_t nbits, size_t es> posit<nbits,es> pow(posit<nbits,es> x, posit<nbits, es> y) { return posit<nbits,es>(std::pow(double(x), double(y))); } template<size_t nbits, size_t es> posit<nbits,es> pow(posit<nbits,es> x, int y) { return posit<nbits,es>(std::pow(double(x), double(y))); } } // namespace unum } // namespace sw <commit_msg>WIP: additional mathematical function shims<commit_after>#pragma once // pow.hpp: pow functions for posits // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw { namespace unum { // the current shims are NON-COMPLIANT with the posit standard, which says that every function must be // correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results. template<size_t nbits, size_t es> posit<nbits,es> pow(posit<nbits,es> x, posit<nbits, es> y) { return posit<nbits,es>(std::pow(double(x), double(y))); } template<size_t nbits, size_t es> posit<nbits,es> pow(posit<nbits,es> x, int y) { return posit<nbits,es>(std::pow(double(x), double(y))); } template<size_t nbits, size_t es> posit<nbits,es> pow(posit<nbits,es> x, double y) { return posit<nbits,es>(std::pow(double(x), y)); } } // namespace unum } // namespace sw <|endoftext|>
<commit_before>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * 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 "manager.h" #include "utils.h" #include "server.h" #include <list> #include <stdlib.h> #include <assert.h> #include <sys/sysctl.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> /* for TCP_NODELAY */ #include <sys/socket.h> #include <unistd.h> XapiandManager::XapiandManager(ev::loop_ref *loop_, int http_port_, int binary_port_) : loop(loop_ ? loop_: &dynamic_loop), break_loop(*loop), async_shutdown(*loop), thread_pool("W%d", 10), http_port(http_port_), binary_port(binary_port_) { pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); pthread_mutexattr_init(&servers_mutex_attr); pthread_mutexattr_settype(&servers_mutex_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&servers_mutex, &servers_mutex_attr); break_loop.set<XapiandManager, &XapiandManager::break_loop_cb>(this); break_loop.start(); async_shutdown.set<XapiandManager, &XapiandManager::shutdown_cb>(this); async_shutdown.start(); bind_http(); #ifdef HAVE_REMOTE_PROTOCOL bind_binary(); #endif /* HAVE_REMOTE_PROTOCOL */ assert(http_sock != -1 && binary_sock != -1); LOG_OBJ(this, "CREATED MANAGER!\n"); } XapiandManager::~XapiandManager() { destroy(); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); pthread_mutex_destroy(&servers_mutex); pthread_mutexattr_destroy(&servers_mutex_attr); LOG_OBJ(this, "DELETED MANAGER!\n"); } void XapiandManager::check_tcp_backlog(int tcp_backlog) { #if defined(NET_CORE_SOMAXCONN) int name[3] = {CTL_NET, NET_CORE, NET_CORE_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { LOG_ERR(this, "ERROR: sysctl: %s\n", strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { LOG_ERR(this, "WARNING: The TCP backlog setting of %d cannot be enforced because " "net.core.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #elif defined(KIPC_SOMAXCONN) int name[3] = {CTL_KERN, KERN_IPC, KIPC_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { LOG_ERR(this, "ERROR: sysctl: %s\n", strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { LOG_ERR(this, "WARNING: The TCP backlog setting of %d cannot be enforced because " "kern.ipc.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #endif } void XapiandManager::bind_http() { int tcp_backlog = XAPIAND_TCP_BACKLOG; int error; int optval = 1; struct sockaddr_in addr; struct linger ling = {0, 0}; http_sock = socket(PF_INET, SOCK_STREAM, 0); setsockopt(http_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); #ifdef SO_NOSIGPIPE setsockopt(http_sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)); #endif error = setsockopt(http_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); error = setsockopt(http_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); error = setsockopt(http_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); addr.sin_family = AF_INET; addr.sin_port = htons(http_port); addr.sin_addr.s_addr = INADDR_ANY; if (bind(http_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { LOG_ERR(this, "ERROR: http bind error (sock=%d): %s\n", http_sock, strerror(errno)); ::close(http_sock); http_sock = -1; } else { fcntl(http_sock, F_SETFL, fcntl(http_sock, F_GETFL, 0) | O_NONBLOCK); check_tcp_backlog(tcp_backlog); listen(http_sock, tcp_backlog); } } #ifdef HAVE_REMOTE_PROTOCOL void XapiandManager::bind_binary() { int tcp_backlog = XAPIAND_TCP_BACKLOG; int error; int optval = 1; struct sockaddr_in addr; struct linger ling = {0, 0}; binary_sock = socket(PF_INET, SOCK_STREAM, 0); setsockopt(binary_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); #ifdef SO_NOSIGPIPE setsockopt(binary_sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)); #endif error = setsockopt(binary_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); error = setsockopt(binary_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); error = setsockopt(binary_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); addr.sin_family = AF_INET; addr.sin_port = htons(binary_port); addr.sin_addr.s_addr = INADDR_ANY; if (bind(binary_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { LOG_ERR(this, "ERROR: binary bind error (sock=%d): %s\n", binary_sock, strerror(errno)); ::close(binary_sock); binary_sock = -1; } else { fcntl(binary_sock, F_SETFL, fcntl(binary_sock, F_GETFL, 0) | O_NONBLOCK); check_tcp_backlog(tcp_backlog); listen(binary_sock, tcp_backlog); } } #endif /* HAVE_REMOTE_PROTOCOL */ void XapiandManager::sig_shutdown_handler(int sig) { /* SIGINT is often delivered via Ctrl+C in an interactive session. * If we receive the signal the second time, we interpret this as * the user really wanting to quit ASAP without waiting to persist * on disk. */ time_t now = time(NULL); if (shutdown_now && sig != SIGTERM) { if (sig && shutdown_now + 1 < now) { INFO(this, "You insist... exiting now.\n"); // remove pid file here, use: getpid(); exit(1); /* Exit with an error since this was not a clean shutdown. */ } } else if (shutdown_asap && sig != SIGTERM) { if (shutdown_asap + 1 < now) { shutdown_now = now; INFO(this, "Trying immediate shutdown.\n"); } } else { shutdown_asap = now; switch (sig) { case SIGINT: INFO(this, "Received SIGINT scheduling shutdown...\n"); break; case SIGTERM: INFO(this, "Received SIGTERM scheduling shutdown...\n"); break; default: INFO(this, "Received shutdown signal, scheduling shutdown...\n"); }; } shutdown(); } void XapiandManager::destroy() { pthread_mutex_lock(&qmtx); if (http_sock == -1 && binary_sock == -1) { pthread_mutex_unlock(&qmtx); return; } if (http_sock != -1) { ::close(http_sock); http_sock = -1; } if (binary_sock != -1) { ::close(binary_sock); binary_sock = -1; } pthread_mutex_unlock(&qmtx); LOG_OBJ(this, "DESTROYED MANAGER!\n"); } void XapiandManager::shutdown_cb(ev::async &watcher, int revents) { sig_shutdown_handler(0); } std::list<XapiandServer *>::const_iterator XapiandManager::attach_server(XapiandServer *server) { pthread_mutex_lock(&servers_mutex); std::list<XapiandServer *>::const_iterator iterator = servers.insert(servers.end(), server); pthread_mutex_unlock(&servers_mutex); return iterator; } void XapiandManager::detach_server(XapiandServer *server) { pthread_mutex_lock(&servers_mutex); if (server->iterator != servers.end()) { servers.erase(server->iterator); server->iterator = servers.end(); LOG_OBJ(this, "DETACHED SERVER!\n"); } pthread_mutex_unlock(&servers_mutex); } void XapiandManager::break_loop_cb(ev::async &watcher, int revents) { LOG_OBJ(this, "Breaking manager loop!\n"); loop->break_loop(); } void XapiandManager::shutdown() { pthread_mutex_lock(&servers_mutex); std::list<XapiandServer *>::const_iterator it(servers.begin()); while (it != servers.end()) { XapiandServer *server = *(it++); server->shutdown(); } pthread_mutex_unlock(&servers_mutex); if (shutdown_asap) { destroy(); LOG_OBJ(this, "Finishing thread pool!\n"); thread_pool.finish(); } if (shutdown_now) { break_loop.send(); } } // //void XapiandManager::run() //{ // XapiandServer * server = new XapiandServer(this, loop, http_sock, binary_sock, &database_pool, &thread_pool); // server->run(NULL); // delete server; //} void XapiandManager::run(int num_servers) { #ifdef HAVE_REMOTE_PROTOCOL INFO(this, "Listening on %d (http), %d (xapian)...\n", http_port, binary_port); #else INFO(this, "Listening on %d (http)...\n", http_port); #endif /* HAVE_REMOTE_PROTOCOL */ ThreadPool server_pool("S%d", num_servers); for (int i = 0; i < num_servers; i++) { XapiandServer *server = new XapiandServer(this, NULL, http_sock, binary_sock, &database_pool, &thread_pool); server_pool.addTask(server); } LOG_OBJ(this, "Starting manager loop...\n"); loop->run(); LOG_OBJ(this, "Manager loop ended!\n"); LOG_OBJ(this, "Waiting for threads...\n"); server_pool.finish(); server_pool.join(); LOG_OBJ(this, "Server ended!\n"); } <commit_msg>Towards C++98 compatibility<commit_after>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * 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 "manager.h" #include "utils.h" #include "server.h" #include <list> #include <stdlib.h> #include <assert.h> #include <sys/sysctl.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> /* for TCP_NODELAY */ #include <sys/socket.h> #include <unistd.h> XapiandManager::XapiandManager(ev::loop_ref *loop_, int http_port_, int binary_port_) : loop(loop_ ? loop_: &dynamic_loop), break_loop(*loop), shutdown_asap(0), shutdown_now(0), async_shutdown(*loop), thread_pool("W%d", 10), http_port(http_port_), binary_port(binary_port_) { pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); pthread_mutexattr_init(&servers_mutex_attr); pthread_mutexattr_settype(&servers_mutex_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&servers_mutex, &servers_mutex_attr); break_loop.set<XapiandManager, &XapiandManager::break_loop_cb>(this); break_loop.start(); async_shutdown.set<XapiandManager, &XapiandManager::shutdown_cb>(this); async_shutdown.start(); bind_http(); #ifdef HAVE_REMOTE_PROTOCOL bind_binary(); #endif /* HAVE_REMOTE_PROTOCOL */ assert(http_sock != -1 && binary_sock != -1); LOG_OBJ(this, "CREATED MANAGER!\n"); } XapiandManager::~XapiandManager() { destroy(); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); pthread_mutex_destroy(&servers_mutex); pthread_mutexattr_destroy(&servers_mutex_attr); LOG_OBJ(this, "DELETED MANAGER!\n"); } void XapiandManager::check_tcp_backlog(int tcp_backlog) { #if defined(NET_CORE_SOMAXCONN) int name[3] = {CTL_NET, NET_CORE, NET_CORE_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { LOG_ERR(this, "ERROR: sysctl: %s\n", strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { LOG_ERR(this, "WARNING: The TCP backlog setting of %d cannot be enforced because " "net.core.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #elif defined(KIPC_SOMAXCONN) int name[3] = {CTL_KERN, KERN_IPC, KIPC_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { LOG_ERR(this, "ERROR: sysctl: %s\n", strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { LOG_ERR(this, "WARNING: The TCP backlog setting of %d cannot be enforced because " "kern.ipc.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #endif } void XapiandManager::bind_http() { int tcp_backlog = XAPIAND_TCP_BACKLOG; int error; int optval = 1; struct sockaddr_in addr; struct linger ling = {0, 0}; http_sock = socket(PF_INET, SOCK_STREAM, 0); setsockopt(http_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); #ifdef SO_NOSIGPIPE setsockopt(http_sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)); #endif error = setsockopt(http_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); error = setsockopt(http_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); error = setsockopt(http_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", http_sock, strerror(errno)); addr.sin_family = AF_INET; addr.sin_port = htons(http_port); addr.sin_addr.s_addr = INADDR_ANY; if (bind(http_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { LOG_ERR(this, "ERROR: http bind error (sock=%d): %s\n", http_sock, strerror(errno)); ::close(http_sock); http_sock = -1; } else { fcntl(http_sock, F_SETFL, fcntl(http_sock, F_GETFL, 0) | O_NONBLOCK); check_tcp_backlog(tcp_backlog); listen(http_sock, tcp_backlog); } } #ifdef HAVE_REMOTE_PROTOCOL void XapiandManager::bind_binary() { int tcp_backlog = XAPIAND_TCP_BACKLOG; int error; int optval = 1; struct sockaddr_in addr; struct linger ling = {0, 0}; binary_sock = socket(PF_INET, SOCK_STREAM, 0); setsockopt(binary_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)); #ifdef SO_NOSIGPIPE setsockopt(binary_sock, SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)); #endif error = setsockopt(binary_sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); error = setsockopt(binary_sock, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); error = setsockopt(binary_sock, IPPROTO_TCP, TCP_NODELAY, (void *)&optval, sizeof(optval)); if (error != 0) LOG_ERR(this, "ERROR: setsockopt (sock=%d): %s\n", binary_sock, strerror(errno)); addr.sin_family = AF_INET; addr.sin_port = htons(binary_port); addr.sin_addr.s_addr = INADDR_ANY; if (bind(binary_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { LOG_ERR(this, "ERROR: binary bind error (sock=%d): %s\n", binary_sock, strerror(errno)); ::close(binary_sock); binary_sock = -1; } else { fcntl(binary_sock, F_SETFL, fcntl(binary_sock, F_GETFL, 0) | O_NONBLOCK); check_tcp_backlog(tcp_backlog); listen(binary_sock, tcp_backlog); } } #endif /* HAVE_REMOTE_PROTOCOL */ void XapiandManager::sig_shutdown_handler(int sig) { /* SIGINT is often delivered via Ctrl+C in an interactive session. * If we receive the signal the second time, we interpret this as * the user really wanting to quit ASAP without waiting to persist * on disk. */ time_t now = time(NULL); if (shutdown_now && sig != SIGTERM) { if (sig && shutdown_now + 1 < now) { INFO(this, "You insist... exiting now.\n"); // remove pid file here, use: getpid(); exit(1); /* Exit with an error since this was not a clean shutdown. */ } } else if (shutdown_asap && sig != SIGTERM) { if (shutdown_asap + 1 < now) { shutdown_now = now; INFO(this, "Trying immediate shutdown.\n"); } } else { shutdown_asap = now; switch (sig) { case SIGINT: INFO(this, "Received SIGINT scheduling shutdown...\n"); break; case SIGTERM: INFO(this, "Received SIGTERM scheduling shutdown...\n"); break; default: INFO(this, "Received shutdown signal, scheduling shutdown...\n"); }; } shutdown(); } void XapiandManager::destroy() { pthread_mutex_lock(&qmtx); if (http_sock == -1 && binary_sock == -1) { pthread_mutex_unlock(&qmtx); return; } if (http_sock != -1) { ::close(http_sock); http_sock = -1; } if (binary_sock != -1) { ::close(binary_sock); binary_sock = -1; } pthread_mutex_unlock(&qmtx); LOG_OBJ(this, "DESTROYED MANAGER!\n"); } void XapiandManager::shutdown_cb(ev::async &watcher, int revents) { sig_shutdown_handler(0); } std::list<XapiandServer *>::const_iterator XapiandManager::attach_server(XapiandServer *server) { pthread_mutex_lock(&servers_mutex); std::list<XapiandServer *>::const_iterator iterator = servers.insert(servers.end(), server); pthread_mutex_unlock(&servers_mutex); return iterator; } void XapiandManager::detach_server(XapiandServer *server) { pthread_mutex_lock(&servers_mutex); if (server->iterator != servers.end()) { servers.erase(server->iterator); server->iterator = servers.end(); LOG_OBJ(this, "DETACHED SERVER!\n"); } pthread_mutex_unlock(&servers_mutex); } void XapiandManager::break_loop_cb(ev::async &watcher, int revents) { LOG_OBJ(this, "Breaking manager loop!\n"); loop->break_loop(); } void XapiandManager::shutdown() { pthread_mutex_lock(&servers_mutex); std::list<XapiandServer *>::const_iterator it(servers.begin()); while (it != servers.end()) { XapiandServer *server = *(it++); server->shutdown(); } pthread_mutex_unlock(&servers_mutex); if (shutdown_asap) { destroy(); LOG_OBJ(this, "Finishing thread pool!\n"); thread_pool.finish(); } if (shutdown_now) { break_loop.send(); } } // //void XapiandManager::run() //{ // XapiandServer * server = new XapiandServer(this, loop, http_sock, binary_sock, &database_pool, &thread_pool); // server->run(NULL); // delete server; //} void XapiandManager::run(int num_servers) { #ifdef HAVE_REMOTE_PROTOCOL INFO(this, "Listening on %d (http), %d (xapian)...\n", http_port, binary_port); #else INFO(this, "Listening on %d (http)...\n", http_port); #endif /* HAVE_REMOTE_PROTOCOL */ ThreadPool server_pool("S%d", num_servers); for (int i = 0; i < num_servers; i++) { XapiandServer *server = new XapiandServer(this, NULL, http_sock, binary_sock, &database_pool, &thread_pool); server_pool.addTask(server); } LOG_OBJ(this, "Starting manager loop...\n"); loop->run(); LOG_OBJ(this, "Manager loop ended!\n"); LOG_OBJ(this, "Waiting for threads...\n"); server_pool.finish(); server_pool.join(); LOG_OBJ(this, "Server ended!\n"); } <|endoftext|>
<commit_before>#include "../include/matrix.h" #include <string> template <class T> matrix<T>::matrix(unsigned int x, unsigned int y){ resize(x,y); } template <class T> matrix<T>::matrix(matrix& matrix){ *this = matrix; } template <class T> void matrix<T>::resize(unsigned int x, unsigned int y){ m.resize(x, vector<T>(y)); } template <class T> vector<T> & matrix<T>::operator[](unsigned int i) { return m[i]; } template <class T> matrix<T>& matrix<T>::operator=(matrix& matrix){ m = matrix.m; return (*this); } // template class matrix <int>; template class matrix <double>; template class matrix <float>; template class matrix <char>; template class matrix <string>; template class matrix <bool>; <commit_msg>Added files via upload<commit_after>#include "../include/matrix.h" #include <string> template <class T> matrix<T>::matrix() {} template <class T> matrix<T>::matrix(unsigned int x, unsigned int y){ resize(x,y); } template <class T> matrix<T>::matrix(matrix& matrix){ *this = matrix; } template <class T> void matrix<T>::resize(unsigned int x, unsigned int y){ m.resize(x, vector<T>(y)); } template <class T> vector<T> & matrix<T>::operator[](unsigned int i) { return m[i]; } template <class T> matrix<T>& matrix<T>::operator=(matrix& matrix){ m = matrix.m; return (*this); } // template class matrix <int>; template class matrix <double>; template class matrix <float>; template class matrix <char>; template class matrix <string>; template class matrix <bool>;<|endoftext|>
<commit_before>#include "midiio.h" #include "lpd8_sysex.h" #include "midiportsmodel.h" #include <QGuiApplication> #include <QSocketNotifier> #include <QtDebug> #include <QStandardItemModel> #include <QThread> #include <exception> MidiIO::MidiIO(QObject *parent) : QObject(parent), m_seq_handle(Q_NULLPTR), m_pfds(Q_NULLPTR), m_seq_port(-1), m_ports_model(Q_NULLPTR) { qDebug() << "Opening MIDI sequencer"; if (snd_seq_open(&m_seq_handle, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { throw std::runtime_error("Failed opening sequencer"); } // Poll int npfd = snd_seq_poll_descriptors_count(m_seq_handle, POLLIN); m_pfds = (struct pollfd *)alloca(npfd * sizeof(struct pollfd)); int npfdf = snd_seq_poll_descriptors(m_seq_handle, m_pfds, npfd, POLLIN); for (int i = 0 ; i < npfdf ; ++i) { qDebug() << "Enabling MIDI poll descriptor" << i; QSocketNotifier* n = new QSocketNotifier(m_pfds[i].fd, QSocketNotifier::Read); connect(qGuiApp, &QGuiApplication::aboutToQuit, [=]() { qDebug() << "Disabling MIDI poll descriptor" << i; n->setEnabled(false); } ); connect(n, &QSocketNotifier::activated, this, &MidiIO::readEvents ); } // snd_seq_set_client_event_filter(m_seq_handle, SND_SEQ_EVENT_SYSEX); // Try qUtf8Printable if (snd_seq_set_client_name(m_seq_handle, qPrintable(qApp->applicationName())) < 0) { throw std::runtime_error("Failed setting sequencer name"); } // In port m_seq_port = snd_seq_create_simple_port( m_seq_handle, qPrintable(qGuiApp->applicationName()), SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_DUPLEX | SND_SEQ_PORT_CAP_SUBS_READ | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_APPLICATION); if (m_seq_port < 0) { throw std::runtime_error("Failed setting sequencer port"); } // m_ports_model = new MidiPortsModel(m_seq_handle, m_seq_port, this); m_ports_model = new QStandardItemModel(this); } MidiIO::~MidiIO() { qDebug() << "Closing MIDI sequencer"; if (snd_seq_delete_simple_port(m_seq_handle, m_seq_port) >= 0) { m_seq_port = -1; } else { qWarning() << "Failed deleting sequencer port"; } if (snd_seq_close(m_seq_handle) >= 0) { m_seq_handle = Q_NULLPTR; } else { qWarning() << "Failed closing sequencer"; } } QAbstractItemModel* MidiIO::midiPortsModel() const { Q_CHECK_PTR(m_ports_model); return m_ports_model; } void MidiIO::readEvents() { qDebug(); while (snd_seq_event_input_pending(m_seq_handle, 1) > 0) { snd_seq_event_t *ev; snd_seq_event_input(m_seq_handle, &ev); processEvent(ev); } } void MidiIO::processEvent(snd_seq_event_t* ev) { switch (ev->type) { case SND_SEQ_EVENT_PORT_SUBSCRIBED: processPortSubscribed(ev); break; case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: break; case SND_SEQ_EVENT_PORT_START: break; case SND_SEQ_EVENT_PORT_EXIT: break; case SND_SEQ_EVENT_PORT_CHANGE: break; case SND_SEQ_EVENT_SYSEX: processSysex(ev); default: break; } } void MidiIO::processPortSubscribed(snd_seq_event_t* ev) { Q_CHECK_PTR(ev); Q_ASSERT(ev->type == SND_SEQ_EVENT_PORT_SUBSCRIBED); // sendIdRequest(); } void MidiIO::processSysex(snd_seq_event_t* ev) { Q_CHECK_PTR(ev); Q_ASSERT(ev->type == SND_SEQ_EVENT_SYSEX); QByteArray s( static_cast<const char*>(ev->data.ext.ptr), ev->data.ext.len); switch (sysex::type(s)) { case sysex::TypeProgram: emit programReceived(sysex::toProgram(s)); break; default: break; } emit sysexReceived(s); } void MidiIO::sendIdRequest() const { const unsigned char b[] = {0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7}; const QByteArray sysex(reinterpret_cast<const char*>(b), sizeof(b)); sendSysex(sysex); } void MidiIO::sendSysex(QByteArray sysex) const { snd_seq_event_t ev; snd_seq_ev_clear(&ev); snd_seq_ev_set_subs(&ev); snd_seq_ev_set_direct(&ev); snd_seq_ev_set_source(&ev, m_seq_port); snd_seq_ev_set_sysex(&ev, sysex.length(), sysex.data()); int err = snd_seq_event_output(m_seq_handle, &ev); if (err < 0) { throw std::runtime_error(snd_strerror(err)); } err = 1; while (err > 0) { err = snd_seq_drain_output(m_seq_handle); if (err < 0) { throw std::runtime_error(snd_strerror(err)); } } } void MidiIO::getPrograms() const { for (int i = 1 ; i <= 4 ; ++i) { sendSysex(sysex::getProgram(i)); } } void MidiIO::sendProgram(pProgram program) const { QByteArray s = sysex::setProgram(program); sendSysex(s); } void MidiIO::getProgram(int id) const { Q_ASSERT(id >= 1 && id <= 4); sendSysex(sysex::getProgram(id)); QThread::sleep(1); } enum MidiPortRole { ClientRole = Qt::UserRole + 1, PortRole }; // Template it, baby template<typename T, int Role> void set(QStandardItem* item, T v) { Q_CHECK_PTR(item); item->setData(v, Role); } template<typename T, int Role> T get(const QStandardItem* item) { Q_CHECK_PTR(item); return item->data(Role).value<T>(); } void (&setClient)(QStandardItem*, int) = set<int, ClientRole>; void (&setPort)(QStandardItem*, int) = set<int, PortRole>; int (&client)(const QStandardItem*) = get<int, ClientRole>; int (&port)(const QStandardItem*) = get<int, PortRole>; QStandardItem* takeItemFromAlsaAddress(QList<QStandardItem*>& items, const snd_seq_addr_t* addr) { Q_CHECK_PTR(addr); QStandardItem* item = Q_NULLPTR; foreach (item, items) { if (client(item) == addr->client && port(item) == addr->port) { break; } } if (item) { items.removeAt(items.indexOf(item)); } return item; } void MidiIO::rescanPorts() { Q_CHECK_PTR(m_seq_handle); Q_CHECK_PTR(m_ports_model); // Existing items QList<QStandardItem*> existing; for (int i = 0 ; i < m_ports_model->rowCount() ; ++i) { existing << m_ports_model->item(i); } snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca(&cinfo); snd_seq_port_info_alloca(&pinfo); const int current_client_id = snd_seq_client_id(m_seq_handle); snd_seq_client_info_set_client(cinfo, -1); while (snd_seq_query_next_client(m_seq_handle, cinfo) >= 0) { const int id = snd_seq_client_info_get_client(cinfo); // Filter current client out if (id == current_client_id) { continue; } snd_seq_port_info_set_client(pinfo, id); snd_seq_port_info_set_port(pinfo, -1); while (snd_seq_query_next_port(m_seq_handle, pinfo) >= 0) { const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo); Q_CHECK_PTR(addr); QStandardItem* item = takeItemFromAlsaAddress(existing, addr); if (!item) { item = new QStandardItem(); setClient(item, addr->client); setPort(item, addr->port); m_ports_model->appendRow(item); } item->setText(snd_seq_port_info_get_name(pinfo)); } } // Remove old items int rc = m_ports_model->rowCount(); QStandardItem* item = Q_NULLPTR; foreach (item, existing) { const QModelIndex index = m_ports_model->indexFromItem(item); Q_ASSERT(index.isValid()); QStandardItem* rowItem = Q_NULLPTR; foreach (rowItem, m_ports_model->takeRow(index.row())) { Q_CHECK_PTR(rowItem); delete rowItem; } rc = m_ports_model->rowCount(); Q_UNUSED(rc); } } void MidiIO::connectPort(const QModelIndex& index) { Q_CHECK_PTR(m_ports_model); Q_ASSERT(m_seq_port >= 0); QStandardItem* item = m_ports_model->itemFromIndex(index); Q_CHECK_PTR(item); const int c = client(item); const int p = port(item); if (snd_seq_connect_from(m_seq_handle, m_seq_port, c, p) < 0) { qDebug() << "Cannot connect from"; } if (snd_seq_connect_to(m_seq_handle, m_seq_port, c, p) < 0) { qDebug() << "Cannot connect to"; } } <commit_msg>Filter non exportable / readable / writable port<commit_after>#include "midiio.h" #include "lpd8_sysex.h" #include "midiportsmodel.h" #include <QGuiApplication> #include <QSocketNotifier> #include <QtDebug> #include <QStandardItemModel> #include <QThread> #include <exception> MidiIO::MidiIO(QObject *parent) : QObject(parent), m_seq_handle(Q_NULLPTR), m_pfds(Q_NULLPTR), m_seq_port(-1), m_ports_model(Q_NULLPTR) { qDebug() << "Opening MIDI sequencer"; if (snd_seq_open(&m_seq_handle, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { throw std::runtime_error("Failed opening sequencer"); } // Poll int npfd = snd_seq_poll_descriptors_count(m_seq_handle, POLLIN); m_pfds = (struct pollfd *)alloca(npfd * sizeof(struct pollfd)); int npfdf = snd_seq_poll_descriptors(m_seq_handle, m_pfds, npfd, POLLIN); for (int i = 0 ; i < npfdf ; ++i) { qDebug() << "Enabling MIDI poll descriptor" << i; QSocketNotifier* n = new QSocketNotifier(m_pfds[i].fd, QSocketNotifier::Read); connect(qGuiApp, &QGuiApplication::aboutToQuit, [=]() { qDebug() << "Disabling MIDI poll descriptor" << i; n->setEnabled(false); } ); connect(n, &QSocketNotifier::activated, this, &MidiIO::readEvents ); } // snd_seq_set_client_event_filter(m_seq_handle, SND_SEQ_EVENT_SYSEX); // Try qUtf8Printable if (snd_seq_set_client_name(m_seq_handle, qPrintable(qApp->applicationName())) < 0) { throw std::runtime_error("Failed setting sequencer name"); } // In port m_seq_port = snd_seq_create_simple_port( m_seq_handle, qPrintable(qGuiApp->applicationName()), SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_DUPLEX | SND_SEQ_PORT_CAP_SUBS_READ | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_APPLICATION); if (m_seq_port < 0) { throw std::runtime_error("Failed setting sequencer port"); } // m_ports_model = new MidiPortsModel(m_seq_handle, m_seq_port, this); m_ports_model = new QStandardItemModel(this); } MidiIO::~MidiIO() { qDebug() << "Closing MIDI sequencer"; if (snd_seq_delete_simple_port(m_seq_handle, m_seq_port) >= 0) { m_seq_port = -1; } else { qWarning() << "Failed deleting sequencer port"; } if (snd_seq_close(m_seq_handle) >= 0) { m_seq_handle = Q_NULLPTR; } else { qWarning() << "Failed closing sequencer"; } } QAbstractItemModel* MidiIO::midiPortsModel() const { Q_CHECK_PTR(m_ports_model); return m_ports_model; } void MidiIO::readEvents() { qDebug(); while (snd_seq_event_input_pending(m_seq_handle, 1) > 0) { snd_seq_event_t *ev; snd_seq_event_input(m_seq_handle, &ev); processEvent(ev); } } void MidiIO::processEvent(snd_seq_event_t* ev) { switch (ev->type) { case SND_SEQ_EVENT_PORT_SUBSCRIBED: processPortSubscribed(ev); break; case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: break; case SND_SEQ_EVENT_PORT_START: break; case SND_SEQ_EVENT_PORT_EXIT: break; case SND_SEQ_EVENT_PORT_CHANGE: break; case SND_SEQ_EVENT_SYSEX: processSysex(ev); default: break; } } void MidiIO::processPortSubscribed(snd_seq_event_t* ev) { Q_CHECK_PTR(ev); Q_ASSERT(ev->type == SND_SEQ_EVENT_PORT_SUBSCRIBED); // sendIdRequest(); } void MidiIO::processSysex(snd_seq_event_t* ev) { Q_CHECK_PTR(ev); Q_ASSERT(ev->type == SND_SEQ_EVENT_SYSEX); QByteArray s( static_cast<const char*>(ev->data.ext.ptr), ev->data.ext.len); switch (sysex::type(s)) { case sysex::TypeProgram: emit programReceived(sysex::toProgram(s)); break; default: break; } emit sysexReceived(s); } void MidiIO::sendIdRequest() const { const unsigned char b[] = {0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7}; const QByteArray sysex(reinterpret_cast<const char*>(b), sizeof(b)); sendSysex(sysex); } void MidiIO::sendSysex(QByteArray sysex) const { snd_seq_event_t ev; snd_seq_ev_clear(&ev); snd_seq_ev_set_subs(&ev); snd_seq_ev_set_direct(&ev); snd_seq_ev_set_source(&ev, m_seq_port); snd_seq_ev_set_sysex(&ev, sysex.length(), sysex.data()); int err = snd_seq_event_output(m_seq_handle, &ev); if (err < 0) { throw std::runtime_error(snd_strerror(err)); } err = 1; while (err > 0) { err = snd_seq_drain_output(m_seq_handle); if (err < 0) { throw std::runtime_error(snd_strerror(err)); } } } void MidiIO::getPrograms() const { for (int i = 1 ; i <= 4 ; ++i) { sendSysex(sysex::getProgram(i)); } } void MidiIO::sendProgram(pProgram program) const { QByteArray s = sysex::setProgram(program); sendSysex(s); } void MidiIO::getProgram(int id) const { Q_ASSERT(id >= 1 && id <= 4); sendSysex(sysex::getProgram(id)); QThread::sleep(1); } enum MidiPortRole { ClientRole = Qt::UserRole + 1, PortRole }; // Template it, baby template<typename T, int Role> void set(QStandardItem* item, T v) { Q_CHECK_PTR(item); item->setData(v, Role); } template<typename T, int Role> T get(const QStandardItem* item) { Q_CHECK_PTR(item); return item->data(Role).value<T>(); } void (&setClient)(QStandardItem*, int) = set<int, ClientRole>; void (&setPort)(QStandardItem*, int) = set<int, PortRole>; int (&client)(const QStandardItem*) = get<int, ClientRole>; int (&port)(const QStandardItem*) = get<int, PortRole>; QStandardItem* takeItemFromAlsaAddress(QList<QStandardItem*>& items, const snd_seq_addr_t* addr) { Q_CHECK_PTR(addr); QStandardItem* item = Q_NULLPTR; foreach (item, items) { if (client(item) == addr->client && port(item) == addr->port) { break; } } if (item) { items.removeAt(items.indexOf(item)); } return item; } void MidiIO::rescanPorts() { Q_CHECK_PTR(m_seq_handle); Q_CHECK_PTR(m_ports_model); // Existing items QList<QStandardItem*> existing; for (int i = 0 ; i < m_ports_model->rowCount() ; ++i) { existing << m_ports_model->item(i); } snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca(&cinfo); snd_seq_port_info_alloca(&pinfo); const int current_client_id = snd_seq_client_id(m_seq_handle); snd_seq_client_info_set_client(cinfo, -1); while (snd_seq_query_next_client(m_seq_handle, cinfo) >= 0) { const int id = snd_seq_client_info_get_client(cinfo); // Filter current client and system client (0) if (id == current_client_id || id == 0) { continue; } snd_seq_port_info_set_client(pinfo, id); snd_seq_port_info_set_port(pinfo, -1); while (snd_seq_query_next_port(m_seq_handle, pinfo) >= 0) { const unsigned int caps = snd_seq_port_info_get_capability(pinfo); const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo); Q_CHECK_PTR(addr); // Filter non exportable and non read / write ports if ((caps & SND_SEQ_PORT_CAP_NO_EXPORT) > 0 || (caps & SND_SEQ_PORT_CAP_READ) == 0 || (caps & SND_SEQ_PORT_CAP_WRITE) == 0) { continue; } QStandardItem* item = takeItemFromAlsaAddress(existing, addr); if (!item) { item = new QStandardItem(); setClient(item, addr->client); setPort(item, addr->port); m_ports_model->appendRow(item); } item->setText(snd_seq_port_info_get_name(pinfo)); } } // Remove old items int rc = m_ports_model->rowCount(); QStandardItem* item = Q_NULLPTR; foreach (item, existing) { const QModelIndex index = m_ports_model->indexFromItem(item); Q_ASSERT(index.isValid()); QStandardItem* rowItem = Q_NULLPTR; foreach (rowItem, m_ports_model->takeRow(index.row())) { Q_CHECK_PTR(rowItem); delete rowItem; } rc = m_ports_model->rowCount(); Q_UNUSED(rc); } } void MidiIO::connectPort(const QModelIndex& index) { Q_CHECK_PTR(m_ports_model); Q_ASSERT(m_seq_port >= 0); QStandardItem* item = m_ports_model->itemFromIndex(index); Q_CHECK_PTR(item); const int c = client(item); const int p = port(item); if (snd_seq_connect_from(m_seq_handle, m_seq_port, c, p) < 0) { qDebug() << "Cannot connect from"; } if (snd_seq_connect_to(m_seq_handle, m_seq_port, c, p) < 0) { qDebug() << "Cannot connect to"; } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2014 Micah C Chambers (micahc.vt@gmail.com) * * 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 opt.cpp Contains implementation for base optimizer * *****************************************************************************/ #include "opt.h" #include <iostream> #include <iomanip> namespace npl { /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param valgradfunc * Function which computes the both the energy and * gradient in the underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const ValGradFunc& valgradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0; stop_X = 0; stop_F = 0; stop_F_under = -INFINITY; stop_F_over = INFINITY; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = valgradfunc; m_callback = callback; }; /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_F_under = -INFINITY; stop_F_over = INFINITY; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = [&](const VectorXd& x, double& value, VectorXd& grad) -> int { return !(valfunc(x, value)==0 && gradfunc(x, grad)==0); }; m_callback = callback; }; std::string Optimizer::explainStop(StopReason r) { switch(r) { case ENDGRAD: return "Optimizer stopped due to gradient below threshold."; case ENDSTEP: return "Optimizer stopped due to step size below threshold."; case ENDVALUE: return "Optimizer stopped due to change in value below threshold."; case ENDABSVALUE: return "Optimizer stopped due to surpassing value threshold."; case ENDITERS: return "Optimizer stopped due to number iterations."; case ENDFAIL: return "Optimizer due to failure of callback functions."; } return "Unknown stop condition!"; } /** * @brief Tests a gradient function using the value function. * * @param error Error between analytical and numeric gradient * @param x Position to test * @param stepsize Step to take when testing gradient (will be taken in each * dimension successively) * @param tol Tolerance, error below the tolerance will cause the * function to return 0, higher error will cause the function to return -1 * @param valfunc Function values compute * @param gradfunc Function gradient compute * * @return */ int testgrad(double& error, const VectorXd& x, double stepsize, double tol, const ValFunc& valfunc, const GradFunc& gradfunc) { size_t wid = 18; std::cerr << "Testing Gradient" << std::endl; std::cerr << std::setw(wid) << "Dim" << std::setw(wid) << "Analytic" << std::setw(wid) << "Numeric" << std::endl; VectorXd g(x.rows()); if(gradfunc(x, g) != 0) return -1; double v = 0; double center = 0; if(valfunc(x, center) != 0) return -1; VectorXd step = VectorXd::Zero(x.rows()); VectorXd gbrute(x.rows()); for(size_t dd=0; dd<x.rows(); dd++) { step[dd] = stepsize; if(valfunc(x+step, v) != 0) return -1; step[dd] = 0; gbrute[dd] = (v-center)/stepsize; std::cerr << std::setw(wid) << dd << std::setw(wid) << g[dd] << std::setw(wid) << gbrute[dd] << std::endl; } error = (gbrute - g).norm(); std::cerr << "SumSqr Error: " << error << std::endl; if(error > tol) return -2; return 0; } /** * @brief The number of calls to the Generalized Rosenbrock Gradient Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_G_calls = 0; /** * @brief The number of calls to the Generalized Rosenbrock Value Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_V_calls = 0; /** * @brief Returns the number of times the Value and Gradient functions for the * Generalized Rosenbrock Function were called. * * @param vcalls Value calls * @param gcalls Gradient calls */ void gRosenbrock_callCounts(size_t& vcalls, size_t& gcalls) { gcalls = gRosenbrock_G_calls; vcalls = gRosenbrock_V_calls; } /** * @brief Implements generized rosenbrock value * * @param x Position vector * @param v values * * @return */ int gRosenbrock_V(const VectorXd& x, double& v) { gRosenbrock_V_calls++;; v = 0; for(size_t ii=0; ii<x.rows()-1; ii++) v += pow(x[ii]-1,2)+100*pow(x[ii+1]-x[ii]*x[ii], 2); // i=N-1 size_t ii=x.rows()-1; v += pow(x[ii]-1,2)+100*pow(-x[ii]*x[ii], 2); return 0; } /** * @brief Implements generized rosenbrock gradient * * @param x Position vector * @param gradient Gradient at the position * * @return */ int gRosenbrock_G(const VectorXd& x, VectorXd& gradient) { gRosenbrock_G_calls++;; // gradient.resize(x.rows()); for(size_t ii=1; ii<x.rows()-1; ii++) gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); // boundaries size_t ii=0; gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]; ii=x.rows()-1; gradient[ii] = 2*(x[ii]-1)-400*(-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); return 0; } } <commit_msg>measure relative error in gradient test<commit_after>/****************************************************************************** * Copyright 2014 Micah C Chambers (micahc.vt@gmail.com) * * 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 opt.cpp Contains implementation for base optimizer * *****************************************************************************/ #include "opt.h" #include <iostream> #include <iomanip> namespace npl { /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param valgradfunc * Function which computes the both the energy and * gradient in the underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const ValGradFunc& valgradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0; stop_X = 0; stop_F = 0; stop_F_under = -INFINITY; stop_F_over = INFINITY; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = valgradfunc; m_callback = callback; }; /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_F_under = -INFINITY; stop_F_over = INFINITY; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = [&](const VectorXd& x, double& value, VectorXd& grad) -> int { return !(valfunc(x, value)==0 && gradfunc(x, grad)==0); }; m_callback = callback; }; std::string Optimizer::explainStop(StopReason r) { switch(r) { case ENDGRAD: return "Optimizer stopped due to gradient below threshold."; case ENDSTEP: return "Optimizer stopped due to step size below threshold."; case ENDVALUE: return "Optimizer stopped due to change in value below threshold."; case ENDABSVALUE: return "Optimizer stopped due to surpassing value threshold."; case ENDITERS: return "Optimizer stopped due to number iterations."; case ENDFAIL: return "Optimizer due to failure of callback functions."; } return "Unknown stop condition!"; } /** * @brief Tests a gradient function using the value function. * * @param error Error between analytical and numeric gradient * @param x Position to test * @param stepsize Step to take when testing gradient (will be taken in each * dimension successively) * @param tol Tolerance, error below the tolerance will cause the * function to return 0, higher error will cause the function to return -1 * @param valfunc Function values compute * @param gradfunc Function gradient compute * * @return */ int testgrad(double& error, const VectorXd& x, double stepsize, double tol, const ValFunc& valfunc, const GradFunc& gradfunc) { size_t wid = 18; std::cerr << "Testing Gradient" << std::endl; std::cerr << std::setw(wid) << "Dim" << std::setw(wid) << "Analytic" << std::setw(wid) << "Numeric" << std::endl; VectorXd g(x.rows()); if(gradfunc(x, g) != 0) return -1; double v = 0; double center = 0; if(valfunc(x, center) != 0) return -1; VectorXd step = VectorXd::Zero(x.rows()); VectorXd gbrute(x.rows()); for(size_t dd=0; dd<x.rows(); dd++) { step[dd] = stepsize; if(valfunc(x+step, v) != 0) return -1; step[dd] = 0; gbrute[dd] = (v-center)/stepsize; std::cerr << std::setw(wid) << dd << std::setw(wid) << g[dd] << std::setw(wid) << gbrute[dd] << std::endl; } double unscerror = (gbrute - g).norm(); error = unscerror/gbrute.norm(); std::cerr << "SumSqr Error: " << unscerror << std::endl; std::cerr << "Relative Error: " << error << std::endl; if(error > tol) return -2; return 0; } /** * @brief The number of calls to the Generalized Rosenbrock Gradient Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_G_calls = 0; /** * @brief The number of calls to the Generalized Rosenbrock Value Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_V_calls = 0; /** * @brief Returns the number of times the Value and Gradient functions for the * Generalized Rosenbrock Function were called. * * @param vcalls Value calls * @param gcalls Gradient calls */ void gRosenbrock_callCounts(size_t& vcalls, size_t& gcalls) { gcalls = gRosenbrock_G_calls; vcalls = gRosenbrock_V_calls; } /** * @brief Implements generized rosenbrock value * * @param x Position vector * @param v values * * @return */ int gRosenbrock_V(const VectorXd& x, double& v) { gRosenbrock_V_calls++;; v = 0; for(size_t ii=0; ii<x.rows()-1; ii++) v += pow(x[ii]-1,2)+100*pow(x[ii+1]-x[ii]*x[ii], 2); // i=N-1 size_t ii=x.rows()-1; v += pow(x[ii]-1,2)+100*pow(-x[ii]*x[ii], 2); return 0; } /** * @brief Implements generized rosenbrock gradient * * @param x Position vector * @param gradient Gradient at the position * * @return */ int gRosenbrock_G(const VectorXd& x, VectorXd& gradient) { gRosenbrock_G_calls++;; // gradient.resize(x.rows()); for(size_t ii=1; ii<x.rows()-1; ii++) gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); // boundaries size_t ii=0; gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]; ii=x.rows()-1; gradient[ii] = 2*(x[ii]-1)-400*(-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); return 0; } } <|endoftext|>
<commit_before>/** * @file options.cc * @author Konrad Zemek * @copyright (C) 2014 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "options.h" #include "version.h" #include "logging.h" #include "oneException.h" #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/xpressive/xpressive.hpp> #include <fstream> #include <functional> #include <sstream> #include <vector> #include <utility> using namespace boost::program_options; namespace one { namespace client { Options::Options() : m_common("Common config file and environment options") , m_restricted("Global config file restricted options") , m_commandline("General options") , m_fuse("FUSE options") , m_hidden("Hidden commandline options") { setDescriptions(); } Options::~Options() {} void Options::setDescriptions() { // Common options found in environment, global and user config files add_provider_hostname(m_common); add_provider_port(m_common); add_peer_certificate_file(m_common); add_no_check_certificate(m_common); add_fuse_group_id(m_common); add_enable_attr_cache(m_common); add_attr_cache_expiration_time(m_common); add_log_dir(m_common); add_fuse_id(m_common); add_jobscheduler_threads(m_common); add_enable_dir_prefetch(m_common); add_enable_parallel_getattr(m_common); add_enable_permission_checking(m_common); add_enable_location_cache(m_common); add_global_registry_url(m_common); add_global_registry_port(m_common); add_authentication(m_common); // Restricted options exclusive to global config file add_enable_env_option_override(m_restricted); add_cluster_ping_interval(m_restricted); add_alive_meta_connections_count(m_restricted); add_alive_data_connections_count(m_restricted); add_write_buffer_max_size(m_restricted); add_read_buffer_max_size(m_restricted); add_write_buffer_max_file_size(m_restricted); add_read_buffer_max_file_size(m_restricted); add_file_buffer_prefered_block_size(m_restricted); // General commandline options add_switch_help(m_commandline); add_switch_version(m_commandline); add_config(m_commandline); add_authentication(m_commandline); add_switch_debug(m_commandline); add_switch_debug_gsi(m_commandline); add_switch_no_check_certificate(m_commandline); // FUSE-specific commandline options m_fuse.add_options()(",o", value<std::vector<std::string>>()->value_name("opt,..."), "mount options")(",f", "foreground operation")( ",s", "disable multi-threaded operation"); // Hidden commandline options (positional) m_hidden.add_options()("mountpoint", value<std::string>(), "mount point"); } void Options::parseConfigs(const int argc, const char *const argv[]) { if (argc > 0) argv0 = argv[0]; try { if (!parseCommandLine(argc, argv)) return; } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing command line arguments: " << e.what(); throw OneException("", e.what()); } variables_map fileConfigMap; try { parseUserConfig(fileConfigMap); } catch (boost::program_options::unknown_option &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); if (m_restricted.find_nothrow(e.get_option_name(), false)) throw OneException("", "restricted option '" + e.get_option_name() + "' found in user configuration file"); throw OneException("", e.what()); } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); throw OneException("", e.what()); } try { parseGlobalConfig(fileConfigMap); } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing global configuration file:" << e.what(); throw OneException("", e.what()); } // If override is allowed then we merge in environment variables first if (fileConfigMap.at("enable_env_option_override").as<bool>()) { parseEnv(); m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); } else { m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); parseEnv(); } notify(m_vm); } /** * Parses commandline-options with dashes as commandline_options with * underscores. * @param str The command line argument to parse. * @returns A pair of argument name and argument value parsed from the input * string. The argument name has dashes replaced with underscores. */ static std::pair<std::string, std::string> cmdParser(const std::string &str) { using namespace boost::xpressive; static const sregex rex = sregex::compile(R"(\s*--([\w\-]+)(?:=(\S+))?\s*)"); smatch what; if (regex_match(str, what, rex)) return std::make_pair( boost::algorithm::replace_all_copy(what[1].str(), "-", "_"), what.size() > 1 ? what[2].str() : std::string()); return std::pair<std::string, std::string>(); } bool Options::parseCommandLine(const int argc, const char *const argv[]) { positional_options_description pos; pos.add("mountpoint", 1); options_description all("Allowed options"); all.add(m_commandline).add(m_fuse).add(m_hidden); store(command_line_parser(argc, argv) .options(all) .positional(pos) .extra_parser(cmdParser) .run(), m_vm); return !m_vm.count("help") && !m_vm.count("version"); } void Options::parseUserConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; if (!m_vm.count("config")) return; const path userConfigPath = absolute(m_vm.at("config").as<std::string>()); std::ifstream userConfig(userConfigPath.c_str()); if (userConfig) LOG(INFO) << "Parsing user configuration file " << userConfigPath; else LOG(WARNING) << "Couldn't open user configuration file " << userConfigPath; store(parse_config_file(userConfig, m_common), fileConfigMap); } void Options::parseGlobalConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; options_description global("Global configuration"); global.add(m_restricted).add(m_common); const path globalConfigPath = path(oneclient_INSTALL_PATH) / oneclient_CONFIG_DIR / GLOBAL_CONFIG_FILE; std::ifstream globalConfig(globalConfigPath.c_str()); if (globalConfig) LOG(INFO) << "Parsing global configuration file " << globalConfigPath; else LOG(WARNING) << "Couldn't open global configuration file " << globalConfigPath; store(parse_config_file(globalConfig, global), fileConfigMap); } std::string Options::mapEnvNames(std::string env) const { boost::algorithm::to_lower(env); if (m_common.find_nothrow(env, false) && m_vm.count(env) == 0) { LOG(INFO) << "Using environment configuration variable " << env; return env; } return std::string(); } void Options::parseEnv() { LOG(INFO) << "Parsing environment variables"; store(parse_environment(m_common, std::bind(&Options::mapEnvNames, this, std::placeholders::_1)), m_vm); } struct fuse_args Options::getFuseArgs() const { struct fuse_args args = FUSE_ARGS_INIT(0, nullptr); fuse_opt_add_arg(&args, argv0.c_str()); fuse_opt_add_arg(&args, "-obig_writes"); if (m_vm.count("debug")) fuse_opt_add_arg(&args, "-d"); if (m_vm.count("-f")) fuse_opt_add_arg(&args, "-f"); if (m_vm.count("-s")) fuse_opt_add_arg(&args, "-s"); if (m_vm.count("-o")) { for (const auto &opt : m_vm.at("-o").as<std::vector<std::string>>()) fuse_opt_add_arg(&args, ("-o" + opt).c_str()); } if (m_vm.count("mountpoint")) fuse_opt_add_arg( &args, m_vm.at("mountpoint").as<std::string>().c_str()); return args; } std::string Options::describeCommandlineOptions() const { options_description visible(""); visible.add(m_commandline).add(m_fuse); std::stringstream ss; ss << visible; return ss.str(); } } // namespace client } // namespace one <commit_msg>VFS-1120 Return the logs' do develop version.<commit_after>/** * @file options.cc * @author Konrad Zemek * @copyright (C) 2014 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "options.h" #include "version.h" #include "logging.h" #include "oneException.h" #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/xpressive/xpressive.hpp> #include <fstream> #include <functional> #include <sstream> #include <vector> #include <utility> using namespace boost::program_options; namespace one { namespace client { Options::Options() : m_common("Common config file and environment options") , m_restricted("Global config file restricted options") , m_commandline("General options") , m_fuse("FUSE options") , m_hidden("Hidden commandline options") { setDescriptions(); } Options::~Options() {} void Options::setDescriptions() { // Common options found in environment, global and user config files add_provider_hostname(m_common); add_provider_port(m_common); add_peer_certificate_file(m_common); add_no_check_certificate(m_common); add_fuse_group_id(m_common); add_enable_attr_cache(m_common); add_attr_cache_expiration_time(m_common); add_log_dir(m_common); add_fuse_id(m_common); add_jobscheduler_threads(m_common); add_enable_dir_prefetch(m_common); add_enable_parallel_getattr(m_common); add_enable_permission_checking(m_common); add_enable_location_cache(m_common); add_global_registry_url(m_common); add_global_registry_port(m_common); add_authentication(m_common); // Restricted options exclusive to global config file add_enable_env_option_override(m_restricted); add_cluster_ping_interval(m_restricted); add_alive_meta_connections_count(m_restricted); add_alive_data_connections_count(m_restricted); add_write_buffer_max_size(m_restricted); add_read_buffer_max_size(m_restricted); add_write_buffer_max_file_size(m_restricted); add_read_buffer_max_file_size(m_restricted); add_file_buffer_prefered_block_size(m_restricted); // General commandline options add_switch_help(m_commandline); add_switch_version(m_commandline); add_config(m_commandline); add_authentication(m_commandline); add_switch_debug(m_commandline); add_switch_debug_gsi(m_commandline); add_switch_no_check_certificate(m_commandline); // FUSE-specific commandline options m_fuse.add_options()(",o", value<std::vector<std::string>>()->value_name("opt,..."), "mount options")(",f", "foreground operation")( ",s", "disable multi-threaded operation"); // Hidden commandline options (positional) m_hidden.add_options()("mountpoint", value<std::string>(), "mount point"); } void Options::parseConfigs(const int argc, const char *const argv[]) { if (argc > 0) argv0 = argv[0]; try { if (!parseCommandLine(argc, argv)) return; } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing command line arguments: " << e.what(); throw OneException("", e.what()); } variables_map fileConfigMap; try { parseUserConfig(fileConfigMap); } catch (boost::program_options::unknown_option &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); if (m_restricted.find_nothrow(e.get_option_name(), false)) throw OneException("", "restricted option '" + e.get_option_name() + "' found in user configuration file"); throw OneException("", e.what()); } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); throw OneException("", e.what()); } try { parseGlobalConfig(fileConfigMap); } catch (boost::program_options::error &e) { LOG(ERROR) << "Error while parsing global configuration file: " << e.what(); throw OneException("", e.what()); } // If override is allowed then we merge in environment variables first if (fileConfigMap.at("enable_env_option_override").as<bool>()) { parseEnv(); m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); } else { m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); parseEnv(); } notify(m_vm); } /** * Parses commandline-options with dashes as commandline_options with * underscores. * @param str The command line argument to parse. * @returns A pair of argument name and argument value parsed from the input * string. The argument name has dashes replaced with underscores. */ static std::pair<std::string, std::string> cmdParser(const std::string &str) { using namespace boost::xpressive; static const sregex rex = sregex::compile(R"(\s*--([\w\-]+)(?:=(\S+))?\s*)"); smatch what; if (regex_match(str, what, rex)) return std::make_pair( boost::algorithm::replace_all_copy(what[1].str(), "-", "_"), what.size() > 1 ? what[2].str() : std::string()); return std::pair<std::string, std::string>(); } bool Options::parseCommandLine(const int argc, const char *const argv[]) { positional_options_description pos; pos.add("mountpoint", 1); options_description all("Allowed options"); all.add(m_commandline).add(m_fuse).add(m_hidden); store(command_line_parser(argc, argv) .options(all) .positional(pos) .extra_parser(cmdParser) .run(), m_vm); return !m_vm.count("help") && !m_vm.count("version"); } void Options::parseUserConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; if (!m_vm.count("config")) return; const path userConfigPath = absolute(m_vm.at("config").as<std::string>()); std::ifstream userConfig(userConfigPath.c_str()); if (userConfig) LOG(INFO) << "Parsing user configuration file: '" << userConfigPath << "'"; else LOG(WARNING) << "Couldn't open user configuration file: '" << userConfigPath << "'"; store(parse_config_file(userConfig, m_common), fileConfigMap); } void Options::parseGlobalConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; options_description global("Global configuration"); global.add(m_restricted).add(m_common); const path globalConfigPath = path(oneclient_INSTALL_PATH) / oneclient_CONFIG_DIR / GLOBAL_CONFIG_FILE; std::ifstream globalConfig(globalConfigPath.c_str()); if (globalConfig) LOG(INFO) << "Parsing global configuration file: '" << globalConfigPath << "'"; else LOG(WARNING) << "Couldn't open global configuration file: '" << globalConfigPath << "'"; store(parse_config_file(globalConfig, global), fileConfigMap); } std::string Options::mapEnvNames(std::string env) const { boost::algorithm::to_lower(env); if (m_common.find_nothrow(env, false) && m_vm.count(env) == 0) { LOG(INFO) << "Using environment configuration variable: '" << env << "'"; return env; } return std::string(); } void Options::parseEnv() { LOG(INFO) << "Parsing environment variables"; store(parse_environment(m_common, std::bind(&Options::mapEnvNames, this, std::placeholders::_1)), m_vm); } struct fuse_args Options::getFuseArgs() const { struct fuse_args args = FUSE_ARGS_INIT(0, nullptr); fuse_opt_add_arg(&args, argv0.c_str()); fuse_opt_add_arg(&args, "-obig_writes"); if (m_vm.count("debug")) fuse_opt_add_arg(&args, "-d"); if (m_vm.count("-f")) fuse_opt_add_arg(&args, "-f"); if (m_vm.count("-s")) fuse_opt_add_arg(&args, "-s"); if (m_vm.count("-o")) { for (const auto &opt : m_vm.at("-o").as<std::vector<std::string>>()) fuse_opt_add_arg(&args, ("-o" + opt).c_str()); } if (m_vm.count("mountpoint")) fuse_opt_add_arg( &args, m_vm.at("mountpoint").as<std::string>().c_str()); return args; } std::string Options::describeCommandlineOptions() const { options_description visible(""); visible.add(m_commandline).add(m_fuse); std::stringstream ss; ss << visible; return ss.str(); } } // namespace client } // namespace one <|endoftext|>
<commit_before>#include "output.hpp" #include "config.hpp" #include <utility> #include <fstream> #include <climits> #include <boost/filesystem.hpp> using namespace synth; static std::string relativeUrl(fs::path const& from, fs::path const& to) { if (to == from) return std::string(); fs::path r = to.lexically_relative(from.parent_path()); return r == "." ? std::string() : r.string(); } bool Markup::empty() const { return beginOffset == endOffset || (attrs == TokenAttributes::none && !isRef()); } fs::path HighlightedFile::dstPath() const { fs::path r = inOutDir->second / fname; r += ".html"; return r; } void HighlightedFile::prepareOutput() { // ORDER BY beginOffset ASC, endOffset DESC std::sort( markups.begin(), markups.end(), [] (Markup const& lhs, Markup const& rhs) { return lhs.beginOffset != rhs.beginOffset ? lhs.beginOffset < rhs.beginOffset : lhs.endOffset > rhs.endOffset; }); } static char const* getTokenKindCssClass(TokenAttributes attrs) { // These CSS classes are the ones Pygments uses. using Tk = TokenAttributes; SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch(attrs & Tk::maskKind) { case Tk::attr: return "nd"; // Name.Decorator case Tk::cmmt: return "c"; // Comment case Tk::constant: return "no"; // Name.Constant case Tk::func: return "nf"; // Name.Function case Tk::kw: return "k"; // Keyword case Tk::kwDecl: return "kd"; // Keyword.Declaration case Tk::lbl: return "nl"; // Name.Label case Tk::lit: return "l"; // Literal case Tk::litChr: return "sc"; // String.Char case Tk::litKw: return "kc"; // Keyword.Constant case Tk::litNum: return "m"; // Number case Tk::litNumFlt: return "mf"; // Number.Float case Tk::litNumIntBin: return "mb"; // Number.Binary case Tk::litNumIntDecLong: return "ml"; // Number.Integer.Long case Tk::litNumIntHex: return "mh"; // Number.Hex case Tk::litNumIntOct: return "mo"; // Number.Oct case Tk::litStr: return "s"; // String case Tk::namesp: return "nn"; // Name.Namespace case Tk::op: return "o"; // Operator case Tk::opWord: return "ow"; // Operator.Word case Tk::pre: return "cp"; // Comment.Preproc case Tk::preIncludeFile: return "cpf"; // Comment.PreprocFile case Tk::punct: return "p"; // Punctuation case Tk::ty: return "nc"; // Name.Class case Tk::tyBuiltin: return "kt"; // Keyword.Type case Tk::varGlobal: return "vg"; // Name.Variable.Global case Tk::varLocal: return "nv"; // Name.Variable case Tk::varNonstaticMember: return "vi"; // Name.Variable.Instance case Tk::varStaticMember: return "vc"; // Name.Variable.Class case Tk::none: return ""; default: assert(false && "Unexpected token kind!"); } SYNTH_DISCLANGWARN_END } static void writeCssClasses(TokenAttributes attrs, std::ostream& out) { if ((attrs & TokenAttributes::flagDef) != TokenAttributes::none) out << "def "; if ((attrs & TokenAttributes::flagDecl) != TokenAttributes::none) out << "decl "; out << getTokenKindCssClass(attrs); } static void writeBeginTag( Markup const& m, fs::path const& outPath, std::ostream& out) { if (m.empty()) return; out << '<'; if (m.isRef()) { out << "a href=\""; out << relativeUrl(outPath, m.refd.file->dstPath()); if (m.refd.lineno != 0) out << "#L" << m.refd.lineno; out << "\" "; } else { out << "span "; } if (m.attrs != TokenAttributes::none) { out << "class=\""; writeCssClasses(m.attrs, out); out << "\" "; } out << '>'; } static void writeEndTag(Markup const& m, std::ostream& out) { if (m.isRef()) out << "</a>"; else if (!m.empty()) out << "</span>"; } static void writeAllEnds( std::ostream& out, std::vector<Markup const*> const& activeTags) { auto rit = activeTags.rbegin(); auto rend = activeTags.rend(); for (; rit != rend; ++rit) writeEndTag(**rit, out); } namespace { struct OutputState { std::istream& in; std::ostream& out; unsigned lineno; std::vector<Markup const*> const& activeTags; fs::path const& outPath; }; } // anonymous namespace static bool copyWithLinenosUntil(OutputState& state, unsigned offset) { if (state.lineno == 0) { ++state.lineno; state.out << "<span id=\"L1\" class=\"Ln\">"; } while (state.in && state.in.tellg() < offset) { int ch = state.in.get(); if (ch == std::istream::traits_type::eof()) { state.out << "</span>\n"; return false; } else { switch (ch) { case '\n': { writeAllEnds(state.out, state.activeTags); ++state.lineno; state.out << "</span>\n<span id=\"L" << state.lineno << "\" class=\"Ln\">"; for (auto const& m: state.activeTags) writeBeginTag(*m, state.outPath, state.out); } break; case '<': state.out << "&lt;"; break; case '>': state.out << "&gt;"; break; case '&': state.out << "&amp;"; break; case '\r': // Discard. break; default: state.out.put(static_cast<char>(ch)); break; } } } return true; } static void copyWithLinenosUntilNoEof(OutputState& state, unsigned offset) { bool eof = !copyWithLinenosUntil(state, offset); if (eof) { throw std::runtime_error( "unexpected EOF in input source " + state.outPath.string() + " at line " + std::to_string(state.lineno)); } } void HighlightedFile::writeTo(std::ostream& out) const { fs::path outPath = dstPath(); std::ifstream in(srcPath().c_str()); if (!in) { throw std::runtime_error( "Could not reopen source " + srcPath().string()); } std::vector<Markup const*> activeTags; OutputState state {in, out, 0, activeTags, outPath}; for (auto const& m : markups) { while (!activeTags.empty() && m.beginOffset >= activeTags.back()->endOffset ) { Markup const& mEnd = *activeTags.back(); copyWithLinenosUntilNoEof(state, mEnd.endOffset); writeEndTag(mEnd, out); activeTags.pop_back(); } copyWithLinenosUntilNoEof(state, m.beginOffset); writeBeginTag(m, state.outPath, out); activeTags.push_back(&m); } bool eof = !copyWithLinenosUntil(state, UINT_MAX); assert(eof); writeAllEnds(out, activeTags); } <commit_msg>output: Fix warnings in release.<commit_after>#include "output.hpp" #include "config.hpp" #include <utility> #include <fstream> #include <climits> #include <boost/filesystem.hpp> #include <boost/assert.hpp> using namespace synth; static std::string relativeUrl(fs::path const& from, fs::path const& to) { if (to == from) return std::string(); fs::path r = to.lexically_relative(from.parent_path()); return r == "." ? std::string() : r.string(); } bool Markup::empty() const { return beginOffset == endOffset || (attrs == TokenAttributes::none && !isRef()); } fs::path HighlightedFile::dstPath() const { fs::path r = inOutDir->second / fname; r += ".html"; return r; } void HighlightedFile::prepareOutput() { // ORDER BY beginOffset ASC, endOffset DESC std::sort( markups.begin(), markups.end(), [] (Markup const& lhs, Markup const& rhs) { return lhs.beginOffset != rhs.beginOffset ? lhs.beginOffset < rhs.beginOffset : lhs.endOffset > rhs.endOffset; }); } static char const* getTokenKindCssClass(TokenAttributes attrs) { // These CSS classes are the ones Pygments uses. using Tk = TokenAttributes; SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch(attrs & Tk::maskKind) { case Tk::attr: return "nd"; // Name.Decorator case Tk::cmmt: return "c"; // Comment case Tk::constant: return "no"; // Name.Constant case Tk::func: return "nf"; // Name.Function case Tk::kw: return "k"; // Keyword case Tk::kwDecl: return "kd"; // Keyword.Declaration case Tk::lbl: return "nl"; // Name.Label case Tk::lit: return "l"; // Literal case Tk::litChr: return "sc"; // String.Char case Tk::litKw: return "kc"; // Keyword.Constant case Tk::litNum: return "m"; // Number case Tk::litNumFlt: return "mf"; // Number.Float case Tk::litNumIntBin: return "mb"; // Number.Binary case Tk::litNumIntDecLong: return "ml"; // Number.Integer.Long case Tk::litNumIntHex: return "mh"; // Number.Hex case Tk::litNumIntOct: return "mo"; // Number.Oct case Tk::litStr: return "s"; // String case Tk::namesp: return "nn"; // Name.Namespace case Tk::op: return "o"; // Operator case Tk::opWord: return "ow"; // Operator.Word case Tk::pre: return "cp"; // Comment.Preproc case Tk::preIncludeFile: return "cpf"; // Comment.PreprocFile case Tk::punct: return "p"; // Punctuation case Tk::ty: return "nc"; // Name.Class case Tk::tyBuiltin: return "kt"; // Keyword.Type case Tk::varGlobal: return "vg"; // Name.Variable.Global case Tk::varLocal: return "nv"; // Name.Variable case Tk::varNonstaticMember: return "vi"; // Name.Variable.Instance case Tk::varStaticMember: return "vc"; // Name.Variable.Class case Tk::none: return ""; default: assert(false && "Unexpected token kind!"); return ""; } SYNTH_DISCLANGWARN_END } static void writeCssClasses(TokenAttributes attrs, std::ostream& out) { if ((attrs & TokenAttributes::flagDef) != TokenAttributes::none) out << "def "; if ((attrs & TokenAttributes::flagDecl) != TokenAttributes::none) out << "decl "; out << getTokenKindCssClass(attrs); } static void writeBeginTag( Markup const& m, fs::path const& outPath, std::ostream& out) { if (m.empty()) return; out << '<'; if (m.isRef()) { out << "a href=\""; out << relativeUrl(outPath, m.refd.file->dstPath()); if (m.refd.lineno != 0) out << "#L" << m.refd.lineno; out << "\" "; } else { out << "span "; } if (m.attrs != TokenAttributes::none) { out << "class=\""; writeCssClasses(m.attrs, out); out << "\" "; } out << '>'; } static void writeEndTag(Markup const& m, std::ostream& out) { if (m.isRef()) out << "</a>"; else if (!m.empty()) out << "</span>"; } static void writeAllEnds( std::ostream& out, std::vector<Markup const*> const& activeTags) { auto rit = activeTags.rbegin(); auto rend = activeTags.rend(); for (; rit != rend; ++rit) writeEndTag(**rit, out); } namespace { struct OutputState { std::istream& in; std::ostream& out; unsigned lineno; std::vector<Markup const*> const& activeTags; fs::path const& outPath; }; } // anonymous namespace static bool copyWithLinenosUntil(OutputState& state, unsigned offset) { if (state.lineno == 0) { ++state.lineno; state.out << "<span id=\"L1\" class=\"Ln\">"; } while (state.in && state.in.tellg() < offset) { int ch = state.in.get(); if (ch == std::istream::traits_type::eof()) { state.out << "</span>\n"; return false; } else { switch (ch) { case '\n': { writeAllEnds(state.out, state.activeTags); ++state.lineno; state.out << "</span>\n<span id=\"L" << state.lineno << "\" class=\"Ln\">"; for (auto const& m: state.activeTags) writeBeginTag(*m, state.outPath, state.out); } break; case '<': state.out << "&lt;"; break; case '>': state.out << "&gt;"; break; case '&': state.out << "&amp;"; break; case '\r': // Discard. break; default: state.out.put(static_cast<char>(ch)); break; } } } return true; } static void copyWithLinenosUntilNoEof(OutputState& state, unsigned offset) { bool eof = !copyWithLinenosUntil(state, offset); if (eof) { throw std::runtime_error( "unexpected EOF in input source " + state.outPath.string() + " at line " + std::to_string(state.lineno)); } } void HighlightedFile::writeTo(std::ostream& out) const { fs::path outPath = dstPath(); std::ifstream in(srcPath().c_str()); if (!in) { throw std::runtime_error( "Could not reopen source " + srcPath().string()); } std::vector<Markup const*> activeTags; OutputState state {in, out, 0, activeTags, outPath}; for (auto const& m : markups) { while (!activeTags.empty() && m.beginOffset >= activeTags.back()->endOffset ) { Markup const& mEnd = *activeTags.back(); copyWithLinenosUntilNoEof(state, mEnd.endOffset); writeEndTag(mEnd, out); activeTags.pop_back(); } copyWithLinenosUntilNoEof(state, m.beginOffset); writeBeginTag(m, state.outPath, out); activeTags.push_back(&m); } BOOST_VERIFY(!copyWithLinenosUntil(state, UINT_MAX)); writeAllEnds(out, activeTags); } <|endoftext|>
<commit_before>#ifndef VG_PACKER_HPP_INCLUDED #define VG_PACKER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size = 0); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits, vector<vg::id_t> node_ids); ostream& as_edge_table(ostream& out, vector<vg::id_t> node_ids); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); size_t coverage_size(void); size_t edge_coverage(Edge& e) const; size_t edge_coverage(size_t i) const; size_t edge_count(void) const; size_t edge_vector_size(void) const; private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted = false; // dynamic model gcsa::CounterArray coverage_dynamic; gcsa::CounterArray edge_coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length = 0; size_t edit_count = 0; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) dac_vector<> edge_coverage_civ; // edge coverage (compacted) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; Edge edge_from_mappings(const Mapping& m, const Mapping& n); }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <commit_msg>swtich to vlc_vector for edge pack<commit_after>#ifndef VG_PACKER_HPP_INCLUDED #define VG_PACKER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size = 0); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits, vector<vg::id_t> node_ids); ostream& as_edge_table(ostream& out, vector<vg::id_t> node_ids); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); size_t coverage_size(void); size_t edge_coverage(Edge& e) const; size_t edge_coverage(size_t i) const; size_t edge_count(void) const; size_t edge_vector_size(void) const; private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted = false; // dynamic model gcsa::CounterArray coverage_dynamic; gcsa::CounterArray edge_coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length = 0; size_t edit_count = 0; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) vlc_vector<> edge_coverage_civ; // edge coverage (compacted edge_coverage_dynamic) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; Edge edge_from_mappings(const Mapping& m, const Mapping& n); }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <|endoftext|>
<commit_before>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } PrototypeAST *Parser::visitFunctionDeclaration(){ int bkup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // prototype if(Tokens->getCurString() == ";"){ // 再定義されていないか確認 if( PrototypeTable.find(proto->getName()) != PrototypeTable.end() || (FunctionTable.find(proto->getName()) != FunctionTable.end() && FunctionTable[proto->getName()] != proto->getParamNum()) ){ fprintf(stderr, "Function : %s is redefined", proto->getName().c_str()); SAFE_DELETE(proto); return NULL; } // プロトタイプ宣言テーブルに追加 PrototypeTable[proto->getName()] = proto->getParamNum(); Tokens->getNextToken(); return proto; } else{ SAFE_DELETE(proto); Tokens->applyTokenIndex(bkup); return NULL; } } FunctionAST *Parser::visitFunctionDefinition(){ int bkup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // 本来であればここで再定義されていないか確認 FunctionStmtAST *func_stmt = visitFunctionStatement(proto); } PrototypeAST *Parser::visitPrototype(){ int bkup = Tokens->getCurIndex(); bool is_first_param = true; std::vector<std::string> param_list; while(true){ if(!is_first_param && Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == ","){ Tokens->getNextToken(); } if(Tokens->getCurType() == TOK_INT){ Tokens->getNextToken(); } else{ break; } if(Tokens->getCurType() == TOK_IDENTIFIRE){ param_list.push_back(Tokens->getCurString()); Tokens->getNextToken(); } else{ Tokens->applyTokenIndex(bkup); return NULL; } } } FunctionStmtAST *Parser::visitFunctionStatement(PrototypeAST *proto){ int bkup = Tokens->getCurIndex(); if(Tokens->getCurString() == "{"){ Tokens->getNextToken(); } else{ return NULL; } FunctionStmtAST *func_stmt = new FunctionStmtAST(); for(int i = 0; i < proto->getparamNum(); i++){ VariableDeclAST *vdecl = new VariableDeclAST(proto->getParamName(i)); vdecl->setDeclType(VariableDeclAST::param); func_stmt->addVariableDeclaration(vdecl); VariableTable.push_back(vdecl->getName()); } /* omit */ else if(var_decl = visitVariableDeclaration()){ while(var_decl){ var_decl->setDeclType(VariableDeclAST::local); /* TODO : 二重宣言のチェック */ func_stmt->addVariableDeclaration(var_decl); VariableTable.push_back(var_decl->getName()); var_decl = visitVariabeDeclaration(); } if(stmt = visitStatement()){ while(stmt){ last_stmt = stmt; func_stmt -> addStatement(stmt); stmt = visitStatement(); } } } else{ SAFE_DELETE(func_stmt); Tokens->applyTokenIndex(bkup); return NULL; } /* TODO : 戻り値の確認 */ if(Tokens->getCurString() == "}"){ Tokens->getNextToken(); return func_stmt; } else{ SAFE_DELETE(func_stmt); Tokens->applyTokenIndex(bkup); return NULL; } } BaseAST *Parser::visitAssignmentExpression(){ int bkup = Tokens-> getCurIndex(); BaseAST *lhs; if(Tokens->getCurType() == TOK_IDENTIFIRE){ /* TODO : 変数の宣言確認 */ lhs = new VariableAST(Tokens->getCurString()); Tokens->getNextToken(); BaseAST *rhs; if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == "="){ Tokens->getNextToken(); if(rhs = visit AdditiveExpression(NULL)){ return new BinaryExprAST("=", lhs, rhs); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); } } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); } } BaseAST *add_expr = visitAdditiveExpression(NULL); if(add_expr){ return add_expr; } return NULL; } BaseAST *Parser::visitPrimaryExpression(){ int bkup = Tokens->getCurIndex(); if(Tokens->getCurType() == TOK_IDENTIFIER){ /* TODO : 変数の宣言確認 */ std::string var_name = Tokens->getCurString(); Tokens->getNextToken(); return new VariableAST(var_name); } else if(Tokens->getCurType() == TOK_DIGIT){ int val = Tokens->getCurNumVal(); Tokens->getNextToken(); return new NumberAST(val); } else if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString == "-"){ /* omit */ } return NULL; } BaseAST *Parser::visitPostfixExpression(){ int bkup = Tokens->getCurIndex(); /* omit */ if(Tokens->getCurType() == TOK_IDENTIFIRE){ /* TODO : 関数の宣言確認 */ std::string Callee = Tokens->getCurString(); Tokens->getNextToken(); if(Tokens->getCurType() != TOK_SYMBOL || Tokens->getCurString() != "("){ Tokens->applyTokenIndex(bkup); return NULL; } Tokens->getNextToken(); std::vector<BaseAST*> args; BaseAST *assign_expr = visitAssignmentExpression(); if(assign_expr){ args.push_back(assign_expr); while(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == ","){ Tokens->getNextToken(); assign_expre = visitAssignmentExpression(); if(assign_expre){ args.push_back(assign_expr); } else{ break; } } } /* TODO : 引数の数を確認 */ if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString == ")"){ Tokens->getNextToken(); return new CallExprAST(Callee, args); } else{ for(int i = 0; i < args.size(); i++){ SAFE_DELETE(args[i]); } Tokens->applyTokenIndex(bkup); return NULL; } } else{ return NULL; } } BaseAST *Parser::visitAdditiveExpression(BaseAST *lhs){ int bkup = Tokens->getCurIndex(); if(!lhs){ lhs = visitMultiplicativeExpression(NULL); } if(!lhs){ return NULL; } BaseAST *rhs; if(Tokens->getCurType() == TOR_SYMBOL && Tokens->getCurString() == "+"){ Tokens->getNextToken(); rhs = visitMultiplcativeExpression(NULL); if(rhs){ return visitAdditiveExpression(new BinaryExprAST("+", lhs, rhs)); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); return NULL; } } else if(Tokens->getCurType() == TOR_SYMBOL && Tokens->getCurString() == "-"){ Tokens->getNextToken(); rhs = visitMultiplcativeExpression(NULL); if(rhs){ return visitAdditiveExpression(new BinaryExprAST("-", lhs, rhs)); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); return NULL; } } return lhs; } BaseAST *Parser::visitExpressionStatement(){ BaseAST *assign_expr; if(Tokens->getCurString() == ";"){ Tokens->getNextToken(); return new NullExprAST(); } else if(assign_expr = visitAssignmentExpression()){ if(Tokens->getCurString() == ";"){ Tokens->getNextToken(); return assign_expr; } } return NULL; } <commit_msg>5.26 関数宣言の重複確認<commit_after>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } PrototypeAST *Parser::visitFunctionDeclaration(){ int bkup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // prototype if(Tokens->getCurString() == ";"){ // 再定義されていないか確認 if( PrototypeTable.find(proto->getName()) != PrototypeTable.end() || (FunctionTable.find(proto->getName()) != FunctionTable.end() && FunctionTable[proto->getName()] != proto->getParamNum()) ){ fprintf(stderr, "Function : %s is redefined", proto->getName().c_str()); SAFE_DELETE(proto); return NULL; } // プロトタイプ宣言テーブルに追加 PrototypeTable[proto->getName()] = proto->getParamNum(); Tokens->getNextToken(); return proto; } else{ SAFE_DELETE(proto); Tokens->applyTokenIndex(bkup); return NULL; } } FunctionAST *Parser::visitFunctionDefinition(){ int bkup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } else if(// 関数定義の重複が無いか確認 (PrototypeTable.find(proto->getName() != PrototypeTable.end() && PrototypeTable[proto->getName()] != proto->getParamNum()) || FunctionTable.find(proto->getName()) != FunctionTable.end()){ fprintf(stderr, "Function : %s is redefined", proto->getName().c_str()); SADE_DELETE(proto); return NULL } VariableTable.clear(); FunctionStmtAST *func_stmt = visitFunctionStatement(proto); if(func_stmt){ FunctionTable[proto->getName()] = proto->getParamNum(); return new FunctionAST(proto, func_stmt); } /* omit */ } PrototypeAST *Parser::visitPrototype(){ int bkup = Tokens->getCurIndex(); bool is_first_param = true; std::vector<std::string> param_list; while(true){ if(!is_first_param && Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == ","){ Tokens->getNextToken(); } if(Tokens->getCurType() == TOK_INT){ Tokens->getNextToken(); } else{ break; } if(Tokens->getCurType() == TOK_IDENTIFIRE){ param_list.push_back(Tokens->getCurString()); Tokens->getNextToken(); } else{ Tokens->applyTokenIndex(bkup); return NULL; } } } FunctionStmtAST *Parser::visitFunctionStatement(PrototypeAST *proto){ int bkup = Tokens->getCurIndex(); if(Tokens->getCurString() == "{"){ Tokens->getNextToken(); } else{ return NULL; } FunctionStmtAST *func_stmt = new FunctionStmtAST(); for(int i = 0; i < proto->getparamNum(); i++){ VariableDeclAST *vdecl = new VariableDeclAST(proto->getParamName(i)); vdecl->setDeclType(VariableDeclAST::param); func_stmt->addVariableDeclaration(vdecl); VariableTable.push_back(vdecl->getName()); } /* omit */ else if(var_decl = visitVariableDeclaration()){ while(var_decl){ var_decl->setDeclType(VariableDeclAST::local); /* TODO : 二重宣言のチェック */ func_stmt->addVariableDeclaration(var_decl); VariableTable.push_back(var_decl->getName()); var_decl = visitVariabeDeclaration(); } if(stmt = visitStatement()){ while(stmt){ last_stmt = stmt; func_stmt -> addStatement(stmt); stmt = visitStatement(); } } } else{ SAFE_DELETE(func_stmt); Tokens->applyTokenIndex(bkup); return NULL; } /* TODO : 戻り値の確認 */ if(Tokens->getCurString() == "}"){ Tokens->getNextToken(); return func_stmt; } else{ SAFE_DELETE(func_stmt); Tokens->applyTokenIndex(bkup); return NULL; } } BaseAST *Parser::visitAssignmentExpression(){ int bkup = Tokens-> getCurIndex(); BaseAST *lhs; if(Tokens->getCurType() == TOK_IDENTIFIRE){ /* TODO : 変数の宣言確認 */ lhs = new VariableAST(Tokens->getCurString()); Tokens->getNextToken(); BaseAST *rhs; if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == "="){ Tokens->getNextToken(); if(rhs = visit AdditiveExpression(NULL)){ return new BinaryExprAST("=", lhs, rhs); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); } } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); } } BaseAST *add_expr = visitAdditiveExpression(NULL); if(add_expr){ return add_expr; } return NULL; } BaseAST *Parser::visitPrimaryExpression(){ int bkup = Tokens->getCurIndex(); if(Tokens->getCurType() == TOK_IDENTIFIER){ /* TODO : 変数の宣言確認 */ std::string var_name = Tokens->getCurString(); Tokens->getNextToken(); return new VariableAST(var_name); } else if(Tokens->getCurType() == TOK_DIGIT){ int val = Tokens->getCurNumVal(); Tokens->getNextToken(); return new NumberAST(val); } else if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString == "-"){ /* omit */ } return NULL; } BaseAST *Parser::visitPostfixExpression(){ int bkup = Tokens->getCurIndex(); /* omit */ if(Tokens->getCurType() == TOK_IDENTIFIRE){ /* TODO : 関数の宣言確認 */ std::string Callee = Tokens->getCurString(); Tokens->getNextToken(); if(Tokens->getCurType() != TOK_SYMBOL || Tokens->getCurString() != "("){ Tokens->applyTokenIndex(bkup); return NULL; } Tokens->getNextToken(); std::vector<BaseAST*> args; BaseAST *assign_expr = visitAssignmentExpression(); if(assign_expr){ args.push_back(assign_expr); while(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == ","){ Tokens->getNextToken(); assign_expre = visitAssignmentExpression(); if(assign_expre){ args.push_back(assign_expr); } else{ break; } } } /* TODO : 引数の数を確認 */ if(Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString == ")"){ Tokens->getNextToken(); return new CallExprAST(Callee, args); } else{ for(int i = 0; i < args.size(); i++){ SAFE_DELETE(args[i]); } Tokens->applyTokenIndex(bkup); return NULL; } } else{ return NULL; } } BaseAST *Parser::visitAdditiveExpression(BaseAST *lhs){ int bkup = Tokens->getCurIndex(); if(!lhs){ lhs = visitMultiplicativeExpression(NULL); } if(!lhs){ return NULL; } BaseAST *rhs; if(Tokens->getCurType() == TOR_SYMBOL && Tokens->getCurString() == "+"){ Tokens->getNextToken(); rhs = visitMultiplcativeExpression(NULL); if(rhs){ return visitAdditiveExpression(new BinaryExprAST("+", lhs, rhs)); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); return NULL; } } else if(Tokens->getCurType() == TOR_SYMBOL && Tokens->getCurString() == "-"){ Tokens->getNextToken(); rhs = visitMultiplcativeExpression(NULL); if(rhs){ return visitAdditiveExpression(new BinaryExprAST("-", lhs, rhs)); } else{ SAFE_DELETE(lhs); Tokens->applyTokenIndex(bkup); return NULL; } } return lhs; } BaseAST *Parser::visitExpressionStatement(){ BaseAST *assign_expr; if(Tokens->getCurString() == ";"){ Tokens->getNextToken(); return new NullExprAST(); } else if(assign_expr = visitAssignmentExpression()){ if(Tokens->getCurString() == ";"){ Tokens->getNextToken(); return assign_expr; } } return NULL; } <|endoftext|>
<commit_before>#include "planet.h" #include <qmath.h> Planet::Planet(QVector3D p, QVector3D v, float m) : position(p), velocity(v) { setMass(m); } void Planet::updatePath(){ if(path.isEmpty() || (path.back() - this->position).lengthSquared() > pathRecordDistance){ path.append(this->position); } // doing this even if it hasn't been recorded allows it to get shorter. if(path.size() > pathLength){ path.remove(0); } } float Planet::radius() const { return radius_p; } void Planet::setMass(const float &m){ mass_p = m; radius_p = 0.0f; if(m > 0.0f){ radius_p = pow((3.0f * m / 4.0f) * M_PI, 1.0f / 3.0f); } } float Planet::mass() const { return mass_p; } unsigned int Planet::pathLength = 200; float Planet::pathRecordDistance = 0.1f; <commit_msg>use a while loop to limit path.<commit_after>#include "planet.h" #include <qmath.h> Planet::Planet(QVector3D p, QVector3D v, float m) : position(p), velocity(v) { setMass(m); } void Planet::updatePath(){ if(path.isEmpty() || (path.back() - this->position).lengthSquared() > pathRecordDistance){ path.append(this->position); } while(path.size() > pathLength){ path.remove(0); } } float Planet::radius() const { return radius_p; } void Planet::setMass(const float &m){ mass_p = m; radius_p = 0.0f; if(m > 0.0f){ radius_p = pow((3.0f * m / 4.0f) * M_PI, 1.0f / 3.0f); } } float Planet::mass() const { return mass_p; } unsigned int Planet::pathLength = 200; float Planet::pathRecordDistance = 0.1f; <|endoftext|>
<commit_before>#include <stdio.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/param.h> // for MAXPATHLEN #include <fcntl.h> #include <thread> #include <stdexcept> #include <zip.h> #include <jansson.h> #if defined(ARCH_WIN) #include <windows.h> #include <direct.h> #define mkdir(_dir, _perms) _mkdir(_dir) #else #include <dlfcn.h> #endif #include <dirent.h> #include "plugin.hpp" #include "app.hpp" #include "asset.hpp" #include "util/request.hpp" namespace rack { std::list<Plugin*> gPlugins; std::string gToken; static bool isDownloading = false; static float downloadProgress = 0.0; static std::string downloadName; static std::string loginStatus; Plugin::~Plugin() { for (Model *model : models) { delete model; } } void Plugin::addModel(Model *model) { assert(!model->plugin); model->plugin = this; models.push_back(model); } static int loadPlugin(std::string path) { std::string libraryFilename; #if ARCH_LIN libraryFilename = path + "/" + "plugin.so"; #elif ARCH_WIN libraryFilename = path + "/" + "plugin.dll"; #elif ARCH_MAC libraryFilename = path + "/" + "plugin.dylib"; #endif // Load dynamic/shared library #if ARCH_WIN SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); HINSTANCE handle = LoadLibrary(libraryFilename.c_str()); SetErrorMode(0); if (!handle) { int error = GetLastError(); warn("Failed to load library %s: %d", libraryFilename.c_str(), error); return -1; } #elif ARCH_LIN || ARCH_MAC void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW); if (!handle) { warn("Failed to load library %s: %s", libraryFilename.c_str(), dlerror()); return -1; } #endif // Call plugin's init() function typedef void (*InitCallback)(Plugin *); InitCallback initCallback; #if ARCH_WIN initCallback = (InitCallback) GetProcAddress(handle, "init"); #elif ARCH_LIN || ARCH_MAC initCallback = (InitCallback) dlsym(handle, "init"); #endif if (!initCallback) { warn("Failed to read init() symbol in %s", libraryFilename.c_str()); return -2; } // Construct and initialize Plugin instance Plugin *plugin = new Plugin(); plugin->path = path; plugin->handle = handle; initCallback(plugin); // Reject plugin if slug already exists for (Plugin *p : gPlugins) { if (plugin->slug == p->slug) { warn("Plugin \"%s\" is already loaded, not attempting to load it again"); // TODO // Fix memory leak with `plugin` here return -1; } } // Add plugin to list gPlugins.push_back(plugin); info("Loaded plugin %s", libraryFilename.c_str()); return 0; } static void loadPlugins(std::string path) { DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { if (d->d_name[0] == '.') continue; loadPlugin(path + "/" + d->d_name); } closedir(dir); } } //////////////////// // plugin helpers //////////////////// static int extractZipHandle(zip_t *za, const char *dir) { int err = 0; for (int i = 0; i < zip_get_num_entries(za, 0); i++) { zip_stat_t zs; err = zip_stat_index(za, i, 0, &zs); if (err) return err; int nameLen = strlen(zs.name); char path[MAXPATHLEN]; snprintf(path, sizeof(path), "%s/%s", dir, zs.name); if (zs.name[nameLen - 1] == '/') { err = mkdir(path, 0755); if (err && errno != EEXIST) return err; } else { zip_file_t *zf = zip_fopen_index(za, i, 0); if (!zf) return 1; FILE *outFile = fopen(path, "wb"); if (!outFile) continue; while (1) { char buffer[4096]; int len = zip_fread(zf, buffer, sizeof(buffer)); if (len <= 0) break; fwrite(buffer, 1, len, outFile); } err = zip_fclose(zf); if (err) return err; fclose(outFile); } } return 0; } static int extractZip(const char *filename, const char *dir) { int err = 0; zip_t *za = zip_open(filename, 0, &err); if (!za) return 1; if (!err) { err = extractZipHandle(za, dir); } zip_close(za); return err; } static bool syncPlugin(json_t *pluginJ, bool dryRun) { json_t *slugJ = json_object_get(pluginJ, "slug"); if (!slugJ) return false; std::string slug = json_string_value(slugJ); // Get community version std::string version; json_t *versionJ = json_object_get(pluginJ, "version"); if (versionJ) { version = json_string_value(versionJ); } // Check whether we already have a plugin with the same slug and version for (Plugin *plugin : gPlugins) { if (plugin->slug == slug) { // plugin->version might be blank, so adding a version of the manifest will update the plugin if (plugin->version == version) return false; } } json_t *nameJ = json_object_get(pluginJ, "name"); if (!nameJ) return false; std::string name = json_string_value(nameJ); std::string download; std::string sha256; json_t *downloadsJ = json_object_get(pluginJ, "downloads"); if (downloadsJ) { #if defined(ARCH_WIN) #define DOWNLOADS_ARCH "win" #elif defined(ARCH_MAC) #define DOWNLOADS_ARCH "mac" #elif defined(ARCH_LIN) #define DOWNLOADS_ARCH "lin" #endif json_t *archJ = json_object_get(downloadsJ, DOWNLOADS_ARCH); if (archJ) { // Get download URL json_t *downloadJ = json_object_get(archJ, "download"); if (downloadJ) download = json_string_value(downloadJ); // Get SHA256 hash json_t *sha256J = json_object_get(archJ, "sha256"); if (sha256J) sha256 = json_string_value(sha256J); } } json_t *productIdJ = json_object_get(pluginJ, "productId"); if (productIdJ) { download = gApiHost; download += "/download"; download += "?slug="; download += slug; download += "&token="; download += requestEscape(gToken); } if (download.empty()) { warn("Could not get download URL for plugin %s", slug.c_str()); return false; } // If plugin is not loaded, download the zip file to /plugins downloadName = name; downloadProgress = 0.0; // Download zip std::string pluginsDir = assetLocal("plugins"); std::string pluginPath = pluginsDir + "/" + slug; std::string zipPath = pluginPath + ".zip"; bool success = requestDownload(download, zipPath, &downloadProgress); if (!success) { warn("Plugin %s download was unsuccessful"); return false; } if (!sha256.empty()) { // Check SHA256 hash std::string actualSha256 = requestSHA256File(zipPath); if (actualSha256 != sha256) { warn("Plugin %s does not match expected SHA256 checksum", slug.c_str()); return false; } } // Unzip file int err = extractZip(zipPath.c_str(), pluginsDir.c_str()); if (!err) { // Delete zip remove(zipPath.c_str()); // Load plugin // loadPlugin(pluginPath); } downloadName = ""; return true; } bool pluginSync(bool dryRun) { if (gToken.empty()) return false; bool available = false; if (!dryRun) { isDownloading = true; downloadProgress = 0.0; downloadName = "Updating plugins..."; } json_t *resJ = NULL; json_t *communityResJ = NULL; try { // Download plugin slugs json_t *reqJ = json_object(); json_object_set(reqJ, "version", json_string(gApplicationVersion.c_str())); json_object_set(reqJ, "token", json_string(gToken.c_str())); resJ = requestJson(METHOD_GET, gApiHost + "/plugins", reqJ); json_decref(reqJ); if (!resJ) throw std::runtime_error("No response from server"); json_t *errorJ = json_object_get(resJ, "error"); if (errorJ) throw std::runtime_error(json_string_value(errorJ)); // Download community plugins communityResJ = requestJson(METHOD_GET, gApiHost + "/community/plugins", NULL); if (!communityResJ) throw std::runtime_error("No response from server"); json_t *communityErrorJ = json_object_get(communityResJ, "error"); if (communityErrorJ) throw std::runtime_error(json_string_value(communityErrorJ)); // Check each plugin in list of plugin slugs json_t *pluginSlugsJ = json_object_get(resJ, "plugins"); json_t *communityPluginsJ = json_object_get(communityResJ, "plugins"); size_t index; json_t *pluginSlugJ; json_array_foreach(pluginSlugsJ, index, pluginSlugJ) { std::string slug = json_string_value(pluginSlugJ); // Search for plugin slug in community size_t communityIndex; json_t *communityPluginJ = NULL; json_array_foreach(communityPluginsJ, communityIndex, communityPluginJ) { json_t *communitySlugJ = json_object_get(communityPluginJ, "slug"); if (!communitySlugJ) continue; std::string communitySlug = json_string_value(communitySlugJ); if (slug == communitySlug) break; } // Sync plugin if (syncPlugin(communityPluginJ, dryRun)) { available = true; } else { warn("Plugin %s not found in community", slug.c_str()); } } } catch (std::runtime_error &e) { warn("Plugin sync error: %s", e.what()); } if (communityResJ) json_decref(communityResJ); if (resJ) json_decref(resJ); if (!dryRun) { isDownloading = false; } return available; } //////////////////// // plugin API //////////////////// void pluginInit() { tagsInit(); // Load core // This function is defined in core.cpp Plugin *coreManufacturer = new Plugin(); init(coreManufacturer); gPlugins.push_back(coreManufacturer); // Load plugins from global directory std::string globalPlugins = assetGlobal("plugins"); info("Loading plugins from %s", globalPlugins.c_str()); loadPlugins(globalPlugins); // Load plugins from local directory std::string localPlugins = assetLocal("plugins"); if (globalPlugins != localPlugins) { mkdir(localPlugins.c_str(), 0755); info("Loading plugins from %s", localPlugins.c_str()); loadPlugins(localPlugins); } } void pluginDestroy() { for (Plugin *plugin : gPlugins) { // Free library handle #if defined(ARCH_WIN) if (plugin->handle) FreeLibrary((HINSTANCE)plugin->handle); #elif defined(ARCH_LIN) || defined(ARCH_MAC) if (plugin->handle) dlclose(plugin->handle); #endif // For some reason this segfaults. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins. // delete plugin; } gPlugins.clear(); } void pluginLogIn(std::string email, std::string password) { json_t *reqJ = json_object(); json_object_set(reqJ, "email", json_string(email.c_str())); json_object_set(reqJ, "password", json_string(password.c_str())); json_t *resJ = requestJson(METHOD_POST, gApiHost + "/token", reqJ); json_decref(reqJ); if (resJ) { json_t *errorJ = json_object_get(resJ, "error"); if (errorJ) { const char *errorStr = json_string_value(errorJ); loginStatus = errorStr; } else { json_t *tokenJ = json_object_get(resJ, "token"); if (tokenJ) { const char *tokenStr = json_string_value(tokenJ); gToken = tokenStr; loginStatus = ""; } } json_decref(resJ); } } void pluginLogOut() { gToken = ""; } void pluginCancelDownload() { // TODO } bool pluginIsLoggedIn() { return gToken != ""; } bool pluginIsDownloading() { return isDownloading; } float pluginGetDownloadProgress() { return downloadProgress; } std::string pluginGetDownloadName() { return downloadName; } std::string pluginGetLoginStatus() { return loginStatus; } Plugin *pluginGetPlugin(std::string pluginSlug) { for (Plugin *plugin : gPlugins) { if (plugin->slug == pluginSlug) { return plugin; } } return NULL; } Model *pluginGetModel(std::string pluginSlug, std::string modelSlug) { Plugin *plugin = pluginGetPlugin(pluginSlug); if (plugin) { for (Model *model : plugin->models) { if (model->slug == modelSlug) { return model; } } } return NULL; } } // namespace rack <commit_msg>Do not load plugins from global directory<commit_after>#include <stdio.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/param.h> // for MAXPATHLEN #include <fcntl.h> #include <thread> #include <stdexcept> #include <zip.h> #include <jansson.h> #if defined(ARCH_WIN) #include <windows.h> #include <direct.h> #define mkdir(_dir, _perms) _mkdir(_dir) #else #include <dlfcn.h> #endif #include <dirent.h> #include "plugin.hpp" #include "app.hpp" #include "asset.hpp" #include "util/request.hpp" namespace rack { std::list<Plugin*> gPlugins; std::string gToken; static bool isDownloading = false; static float downloadProgress = 0.0; static std::string downloadName; static std::string loginStatus; Plugin::~Plugin() { for (Model *model : models) { delete model; } } void Plugin::addModel(Model *model) { assert(!model->plugin); model->plugin = this; models.push_back(model); } static int loadPlugin(std::string path) { std::string libraryFilename; #if ARCH_LIN libraryFilename = path + "/" + "plugin.so"; #elif ARCH_WIN libraryFilename = path + "/" + "plugin.dll"; #elif ARCH_MAC libraryFilename = path + "/" + "plugin.dylib"; #endif // Load dynamic/shared library #if ARCH_WIN SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); HINSTANCE handle = LoadLibrary(libraryFilename.c_str()); SetErrorMode(0); if (!handle) { int error = GetLastError(); warn("Failed to load library %s: %d", libraryFilename.c_str(), error); return -1; } #elif ARCH_LIN || ARCH_MAC void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW); if (!handle) { warn("Failed to load library %s: %s", libraryFilename.c_str(), dlerror()); return -1; } #endif // Call plugin's init() function typedef void (*InitCallback)(Plugin *); InitCallback initCallback; #if ARCH_WIN initCallback = (InitCallback) GetProcAddress(handle, "init"); #elif ARCH_LIN || ARCH_MAC initCallback = (InitCallback) dlsym(handle, "init"); #endif if (!initCallback) { warn("Failed to read init() symbol in %s", libraryFilename.c_str()); return -2; } // Construct and initialize Plugin instance Plugin *plugin = new Plugin(); plugin->path = path; plugin->handle = handle; initCallback(plugin); // Reject plugin if slug already exists for (Plugin *p : gPlugins) { if (plugin->slug == p->slug) { warn("Plugin \"%s\" is already loaded, not attempting to load it again"); // TODO // Fix memory leak with `plugin` here return -1; } } // Add plugin to list gPlugins.push_back(plugin); info("Loaded plugin %s", libraryFilename.c_str()); return 0; } static void loadPlugins(std::string path) { DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { if (d->d_name[0] == '.') continue; loadPlugin(path + "/" + d->d_name); } closedir(dir); } } //////////////////// // plugin helpers //////////////////// static int extractZipHandle(zip_t *za, const char *dir) { int err = 0; for (int i = 0; i < zip_get_num_entries(za, 0); i++) { zip_stat_t zs; err = zip_stat_index(za, i, 0, &zs); if (err) return err; int nameLen = strlen(zs.name); char path[MAXPATHLEN]; snprintf(path, sizeof(path), "%s/%s", dir, zs.name); if (zs.name[nameLen - 1] == '/') { err = mkdir(path, 0755); if (err && errno != EEXIST) return err; } else { zip_file_t *zf = zip_fopen_index(za, i, 0); if (!zf) return 1; FILE *outFile = fopen(path, "wb"); if (!outFile) continue; while (1) { char buffer[4096]; int len = zip_fread(zf, buffer, sizeof(buffer)); if (len <= 0) break; fwrite(buffer, 1, len, outFile); } err = zip_fclose(zf); if (err) return err; fclose(outFile); } } return 0; } static int extractZip(const char *filename, const char *dir) { int err = 0; zip_t *za = zip_open(filename, 0, &err); if (!za) return 1; if (!err) { err = extractZipHandle(za, dir); } zip_close(za); return err; } static bool syncPlugin(json_t *pluginJ, bool dryRun) { json_t *slugJ = json_object_get(pluginJ, "slug"); if (!slugJ) return false; std::string slug = json_string_value(slugJ); // Get community version std::string version; json_t *versionJ = json_object_get(pluginJ, "version"); if (versionJ) { version = json_string_value(versionJ); } // Check whether we already have a plugin with the same slug and version for (Plugin *plugin : gPlugins) { if (plugin->slug == slug) { // plugin->version might be blank, so adding a version of the manifest will update the plugin if (plugin->version == version) return false; } } json_t *nameJ = json_object_get(pluginJ, "name"); if (!nameJ) return false; std::string name = json_string_value(nameJ); std::string download; std::string sha256; json_t *downloadsJ = json_object_get(pluginJ, "downloads"); if (downloadsJ) { #if defined(ARCH_WIN) #define DOWNLOADS_ARCH "win" #elif defined(ARCH_MAC) #define DOWNLOADS_ARCH "mac" #elif defined(ARCH_LIN) #define DOWNLOADS_ARCH "lin" #endif json_t *archJ = json_object_get(downloadsJ, DOWNLOADS_ARCH); if (archJ) { // Get download URL json_t *downloadJ = json_object_get(archJ, "download"); if (downloadJ) download = json_string_value(downloadJ); // Get SHA256 hash json_t *sha256J = json_object_get(archJ, "sha256"); if (sha256J) sha256 = json_string_value(sha256J); } } json_t *productIdJ = json_object_get(pluginJ, "productId"); if (productIdJ) { download = gApiHost; download += "/download"; download += "?slug="; download += slug; download += "&token="; download += requestEscape(gToken); } if (download.empty()) { warn("Could not get download URL for plugin %s", slug.c_str()); return false; } // If plugin is not loaded, download the zip file to /plugins downloadName = name; downloadProgress = 0.0; // Download zip std::string pluginsDir = assetLocal("plugins"); std::string pluginPath = pluginsDir + "/" + slug; std::string zipPath = pluginPath + ".zip"; bool success = requestDownload(download, zipPath, &downloadProgress); if (!success) { warn("Plugin %s download was unsuccessful"); return false; } if (!sha256.empty()) { // Check SHA256 hash std::string actualSha256 = requestSHA256File(zipPath); if (actualSha256 != sha256) { warn("Plugin %s does not match expected SHA256 checksum", slug.c_str()); return false; } } // Unzip file int err = extractZip(zipPath.c_str(), pluginsDir.c_str()); if (!err) { // Delete zip remove(zipPath.c_str()); // Load plugin // loadPlugin(pluginPath); } downloadName = ""; return true; } bool pluginSync(bool dryRun) { if (gToken.empty()) return false; bool available = false; if (!dryRun) { isDownloading = true; downloadProgress = 0.0; downloadName = "Updating plugins..."; } json_t *resJ = NULL; json_t *communityResJ = NULL; try { // Download plugin slugs json_t *reqJ = json_object(); json_object_set(reqJ, "version", json_string(gApplicationVersion.c_str())); json_object_set(reqJ, "token", json_string(gToken.c_str())); resJ = requestJson(METHOD_GET, gApiHost + "/plugins", reqJ); json_decref(reqJ); if (!resJ) throw std::runtime_error("No response from server"); json_t *errorJ = json_object_get(resJ, "error"); if (errorJ) throw std::runtime_error(json_string_value(errorJ)); // Download community plugins communityResJ = requestJson(METHOD_GET, gApiHost + "/community/plugins", NULL); if (!communityResJ) throw std::runtime_error("No response from server"); json_t *communityErrorJ = json_object_get(communityResJ, "error"); if (communityErrorJ) throw std::runtime_error(json_string_value(communityErrorJ)); // Check each plugin in list of plugin slugs json_t *pluginSlugsJ = json_object_get(resJ, "plugins"); json_t *communityPluginsJ = json_object_get(communityResJ, "plugins"); size_t index; json_t *pluginSlugJ; json_array_foreach(pluginSlugsJ, index, pluginSlugJ) { std::string slug = json_string_value(pluginSlugJ); // Search for plugin slug in community size_t communityIndex; json_t *communityPluginJ = NULL; json_array_foreach(communityPluginsJ, communityIndex, communityPluginJ) { json_t *communitySlugJ = json_object_get(communityPluginJ, "slug"); if (!communitySlugJ) continue; std::string communitySlug = json_string_value(communitySlugJ); if (slug == communitySlug) break; } // Sync plugin if (syncPlugin(communityPluginJ, dryRun)) { available = true; } else { warn("Plugin %s not found in community", slug.c_str()); } } } catch (std::runtime_error &e) { warn("Plugin sync error: %s", e.what()); } if (communityResJ) json_decref(communityResJ); if (resJ) json_decref(resJ); if (!dryRun) { isDownloading = false; } return available; } //////////////////// // plugin API //////////////////// void pluginInit() { tagsInit(); // TODO // If `<local>/plugins/Fundamental` doesn't exist, unzip global Fundamental.zip package into `<local>/plugins` // TODO // Find all ZIP packages in `<local>/plugins` and unzip them. // Display error if failure // Load core // This function is defined in core.cpp Plugin *coreManufacturer = new Plugin(); init(coreManufacturer); gPlugins.push_back(coreManufacturer); // Load plugins from local directory std::string localPlugins = assetLocal("plugins"); mkdir(localPlugins.c_str(), 0755); info("Loading plugins from %s", localPlugins.c_str()); loadPlugins(localPlugins); } void pluginDestroy() { for (Plugin *plugin : gPlugins) { // Free library handle #if defined(ARCH_WIN) if (plugin->handle) FreeLibrary((HINSTANCE)plugin->handle); #elif defined(ARCH_LIN) || defined(ARCH_MAC) if (plugin->handle) dlclose(plugin->handle); #endif // For some reason this segfaults. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins. // delete plugin; } gPlugins.clear(); } void pluginLogIn(std::string email, std::string password) { json_t *reqJ = json_object(); json_object_set(reqJ, "email", json_string(email.c_str())); json_object_set(reqJ, "password", json_string(password.c_str())); json_t *resJ = requestJson(METHOD_POST, gApiHost + "/token", reqJ); json_decref(reqJ); if (resJ) { json_t *errorJ = json_object_get(resJ, "error"); if (errorJ) { const char *errorStr = json_string_value(errorJ); loginStatus = errorStr; } else { json_t *tokenJ = json_object_get(resJ, "token"); if (tokenJ) { const char *tokenStr = json_string_value(tokenJ); gToken = tokenStr; loginStatus = ""; } } json_decref(resJ); } } void pluginLogOut() { gToken = ""; } void pluginCancelDownload() { // TODO } bool pluginIsLoggedIn() { return gToken != ""; } bool pluginIsDownloading() { return isDownloading; } float pluginGetDownloadProgress() { return downloadProgress; } std::string pluginGetDownloadName() { return downloadName; } std::string pluginGetLoginStatus() { return loginStatus; } Plugin *pluginGetPlugin(std::string pluginSlug) { for (Plugin *plugin : gPlugins) { if (plugin->slug == pluginSlug) { return plugin; } } return NULL; } Model *pluginGetModel(std::string pluginSlug, std::string modelSlug) { Plugin *plugin = pluginGetPlugin(pluginSlug); if (plugin) { for (Model *model : plugin->models) { if (model->slug == modelSlug) { return model; } } } return NULL; } } // namespace rack <|endoftext|>
<commit_before>#include "razors.hpp" #include "compiler.hpp" #include "estd.hpp" #include "glresource_types.hpp" #include "gldebug.hpp" #include "glframebuffers.hpp" #include "glinlines.hpp" #include "glshaders.hpp" #include "gltexturing.hpp" BEGIN_NOWARN_BLOCK #include "stb_perlin.h" END_NOWARN_BLOCK #include <GL/glew.h> #include <memory> #include <string> #include <cmath> static const double TAU = 6.28318530717958647692528676655900576839433879875021; struct Framebuffer { Framebuffer(int desiredWidth, int desiredHeight) { createImageCaptureFramebuffer(output, result, depthbuffer, { desiredWidth, desiredHeight }); width = desiredWidth; height = desiredHeight; } FramebufferResource output; TextureResource result; RenderbufferResource depthbuffer; int width; int height; }; struct Geometry { size_t indicesCount; BufferResource indices; BufferResource vertices; BufferResource texcoords; }; // as a sequence of triangles static void define2dQuadTriangles(Geometry& geometry, float x, float y, float width, float height, float umin, float vmin, float umax, float vmax) { GLuint indices[] = { 0, 1, 2, 2, 3, 0, }; geometry.indicesCount = sizeof indices / sizeof indices[0]; withElementBuffer(geometry.indices, [&indices]() { glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STREAM_DRAW); }); withArrayBuffer(geometry.vertices, [=]() { float vertices[] = { x, y, x, y + height, x + width, y + height, x + width, y, }; glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STREAM_DRAW); }); withArrayBuffer(geometry.texcoords, [=]() { float texcoords[] = { umin, vmin, umin, vmax, umax, vmax, umax, vmin, }; glBufferData(GL_ARRAY_BUFFER, sizeof texcoords, texcoords, GL_STREAM_DRAW); }); } class Razors { public: Razors(std::pair<int, int> resolution = viewport()) : previousFrame(resolution.first, resolution.second), resultFrame(resolution.first, resolution.second) {} Framebuffer previousFrame; Framebuffer resultFrame; }; static void perlin_noise(uint32_t* data, int width, int height, float zplane=0.0f) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint8_t values[4]; float alpha = 0.0; for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) { float val = 0.5f + stb_perlin_noise3(glfloat(13.0 * x / width), glfloat(17.0 * y / height), zplane); if (i == 0) { alpha = val; } else { val *= alpha; } if (val > 1.0) { val = 1.0; } else if (val < 0.0) { val = 0.0; } values[i] = (int) (255 * val) & 0xff; } data[x + y*width] = (values[0] << 24) | (values[1] << 16) | (values[2] << 8) | values[3]; } } } struct RenderingProgram { GLuint programId; GLsizei elementCount; VertexArrayResource array; }; static void defineRenderingProgram(RenderingProgram& renderingProgram, ShaderProgramResource const& program, Geometry const& geometry) { auto const programId = program.id; renderingProgram.programId = programId; renderingProgram.elementCount = geometry.indicesCount; withVertexArray(renderingProgram.array, [&program,&geometry,programId]() { GLuint const position_attrib = glGetAttribLocation(program.id, "position"); GLuint const texcoord_attrib = glGetAttribLocation(program.id, "texcoord"); glBindBuffer(GL_ARRAY_BUFFER, geometry.texcoords.id); glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, geometry.vertices.id); glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry.indices.id); glEnableVertexAttribArray(position_attrib); glEnableVertexAttribArray(texcoord_attrib); validate(program); }); } static void drawTriangles(RenderingProgram const& primitive, TextureResource const& texture) { withTexture(texture, [&primitive]() { auto const program = primitive.programId; glUseProgram(program); auto const resolutionLoc = glGetUniformLocation(program, "iResolution"); if (resolutionLoc) { GLint wh[4]; glGetIntegerv(GL_VIEWPORT, wh); glUniform3f(resolutionLoc, glfloat(wh[2]), glfloat(wh[3]), 0.0f); } withVertexArray(primitive.array, [&primitive]() { glDrawElements(GL_TRIANGLES, primitive.elementCount, GL_UNSIGNED_INT, 0); }); glUseProgram(0); }); } struct SimpleShaderProgram : public ShaderProgramResource { VertexShaderResource vertexShader; FragmentShaderResource fragmentShader; }; static void defineProgram(SimpleShaderProgram& program, std::string const& vertexShaderSource, std::string const& fragmentShaderSource) { compile(program.vertexShader, vertexShaderSource); compile(program.fragmentShader, fragmentShaderSource); glAttachShader(program.id, program.vertexShader.id); glAttachShader(program.id, program.fragmentShader.id); glLinkProgram(program.id); withShaderProgram(program, [&program]() { GLint textureLoc = glGetUniformLocation(program.id, "tex"); GLint colorLoc = glGetUniformLocation(program.id, "g_color"); GLint transformLoc = glGetUniformLocation(program.id, "transform"); float idmatrix[4*4] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; glUniformMatrix4fv(transformLoc, 1, GL_FALSE, idmatrix); glUniform4f(colorLoc, 1.0f, 1.0f, 1.0f, 1.0f); glUniform1i(textureLoc, 0); // bind to texture unit 0 }); } #include "inlineshaders.hpp" static void withPremultipliedAlphaBlending(std::function<void()> fn) { glEnable(GL_BLEND); glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable (GL_DEPTH_TEST); glDepthMask (GL_FALSE); fn(); glDepthMask (GL_TRUE); glEnable (GL_DEPTH_TEST); glDisable(GL_BLEND); } static int nextPowerOfTwo(int number) { return static_cast<int> (pow(2.0, ceil(log2(number)))); } static void seed() { static struct Seed { Seed() { auto resolution = viewport(); auto plane = 0.0f; for (auto const& texture : textures) { withTexture(texture, [&]() { defineNonMipmappedARGB32Texture (nextPowerOfTwo(resolution.first), nextPowerOfTwo(resolution.second), [=](uint32_t* pixels, int width, int height) { perlin_noise(pixels, width, height, plane); }); }); plane += 0.9f; } define2dQuadTriangles(quadTris, -1.0, -1.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0); defineProgram(program, defaultVS, defaultFS); defineRenderingProgram(texturedQuad, program, quadTris); }; TextureResource textures[4]; Geometry quadTris; SimpleShaderProgram program; RenderingProgram texturedQuad; } all; if (all.program.id > 0) { static int i = 0; withPremultipliedAlphaBlending ([&] () { auto colorLoc = glGetUniformLocation(all.program.id, "g_color"); auto period = 24; withShaderProgram(all.program, [=]() { auto origin = period*(i/period); auto maxAlpha = 0.09f; auto const alpha = maxAlpha * sin(TAU * (i - origin)/(2.0 * period)); glUniform4f(colorLoc, glfloat(alpha*1.0), glfloat(alpha*1.0), glfloat(alpha*1.0), glfloat(alpha)); }); drawTriangles(all.texturedQuad, all.textures[i/10 % 4]); }); OGL_TRACE; i++; } } RazorsResource makeRazors() { return estd::make_unique<Razors>(); } static void withOutputTo(Framebuffer const& framebuffer, std::function<void()> draw) { auto resolution = viewport(); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.output.id); glDrawBuffer (GL_COLOR_ATTACHMENT0); glReadBuffer (GL_COLOR_ATTACHMENT0); glViewport (0, 0, framebuffer.width, framebuffer.height); draw(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glReadBuffer (GL_BACK); glDrawBuffer (GL_BACK); glViewport(0, 0, resolution.first, resolution.second); } static void projectFramebuffer(Framebuffer const& source, float const scale = 1.0f) { static struct Projector { Projector () { define2dQuadTriangles(quadGeometry, -1.0, -1.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0); defineProgram(program, defaultVS, projectorFS); defineRenderingProgram(texturedQuad, program, quadGeometry); } Geometry quadGeometry; SimpleShaderProgram program; RenderingProgram texturedQuad; } all; if (all.program.id > 0) { // respect source projector's aspect ratio float const yfactor = glfloat(source.height) / glfloat(source.width); define2dQuadTriangles(all.quadGeometry, -1.0f, -yfactor, 2.0f, 2.0f * yfactor, 0.0f, 0.0f, 1.0f, 1.0f); GLint colorLoc = glGetUniformLocation(all.program.id, "g_color"); GLint transformLoc = glGetUniformLocation(all.program.id, "transform"); // scale to screen auto resolution = viewport(); float const targetYFactor = glfloat(resolution.second) / glfloat( resolution.first); float idmatrix[4*4] = { scale, 0.01f, 0.0f, 0.0f, -0.01f, scale / targetYFactor, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; withShaderProgram (all.program, [transformLoc,colorLoc,&idmatrix]() { glUniformMatrix4fv(transformLoc, 1, GL_FALSE, idmatrix); auto const alpha = 0.9998f; glUniform4f(colorLoc, alpha*1.0f, alpha*1.0f, alpha*1.0f, alpha); }); drawTriangles(all.texturedQuad, source.result); } } void draw(Razors& self, double ms) { OGL_TRACE; withOutputTo(self.previousFrame, [&self,ms] () { clear(); projectFramebuffer(self.resultFrame, glfloat(0.990f + 0.010f * sin(TAU * ms / 5000.0))); }); withOutputTo(self.resultFrame, [&self] () { clear(); projectFramebuffer(self.previousFrame, 1.004f); seed(); }); clear(); projectFramebuffer(self.resultFrame); } <commit_msg>some tweaking<commit_after>#include "razors.hpp" #include "compiler.hpp" #include "estd.hpp" #include "glresource_types.hpp" #include "gldebug.hpp" #include "glframebuffers.hpp" #include "glinlines.hpp" #include "glshaders.hpp" #include "gltexturing.hpp" BEGIN_NOWARN_BLOCK #include "stb_perlin.h" END_NOWARN_BLOCK #include <GL/glew.h> #include <memory> #include <string> #include <cmath> static const double TAU = 6.28318530717958647692528676655900576839433879875021; struct Framebuffer { Framebuffer(int desiredWidth, int desiredHeight) { createImageCaptureFramebuffer(output, result, depthbuffer, { desiredWidth, desiredHeight }); width = desiredWidth; height = desiredHeight; } FramebufferResource output; TextureResource result; RenderbufferResource depthbuffer; int width; int height; }; struct Geometry { size_t indicesCount; BufferResource indices; BufferResource vertices; BufferResource texcoords; }; // as a sequence of triangles static void define2dQuadTriangles(Geometry& geometry, float x, float y, float width, float height, float umin, float vmin, float umax, float vmax) { GLuint indices[] = { 0, 1, 2, 2, 3, 0, }; geometry.indicesCount = sizeof indices / sizeof indices[0]; withElementBuffer(geometry.indices, [&indices]() { glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STREAM_DRAW); }); withArrayBuffer(geometry.vertices, [=]() { float vertices[] = { x, y, x, y + height, x + width, y + height, x + width, y, }; glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STREAM_DRAW); }); withArrayBuffer(geometry.texcoords, [=]() { float texcoords[] = { umin, vmin, umin, vmax, umax, vmax, umax, vmin, }; glBufferData(GL_ARRAY_BUFFER, sizeof texcoords, texcoords, GL_STREAM_DRAW); }); } class Razors { public: Razors(std::pair<int, int> resolution = viewport()) : previousFrame(resolution.first, resolution.second), resultFrame(resolution.first, resolution.second) {} Framebuffer previousFrame; Framebuffer resultFrame; }; static void perlin_noise(uint32_t* data, int width, int height, float zplane=0.0f) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint8_t values[4]; float alpha = 0.0; for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) { float val = 0.5f + stb_perlin_noise3(glfloat(13.0 * x / width), glfloat(17.0 * y / height), zplane); if (i == 0) { alpha = val; } else { val *= alpha; } if (val > 1.0) { val = 1.0; } else if (val < 0.0) { val = 0.0; } values[i] = (int) (255 * val) & 0xff; } data[x + y*width] = (values[0] << 24) | (values[1] << 16) | (values[2] << 8) | values[3]; } } } struct RenderingProgram { GLuint programId; GLsizei elementCount; VertexArrayResource array; }; static void defineRenderingProgram(RenderingProgram& renderingProgram, ShaderProgramResource const& program, Geometry const& geometry) { auto const programId = program.id; renderingProgram.programId = programId; renderingProgram.elementCount = geometry.indicesCount; withVertexArray(renderingProgram.array, [&program,&geometry,programId]() { GLuint const position_attrib = glGetAttribLocation(program.id, "position"); GLuint const texcoord_attrib = glGetAttribLocation(program.id, "texcoord"); glBindBuffer(GL_ARRAY_BUFFER, geometry.texcoords.id); glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, geometry.vertices.id); glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry.indices.id); glEnableVertexAttribArray(position_attrib); glEnableVertexAttribArray(texcoord_attrib); validate(program); }); } static void drawTriangles(RenderingProgram const& primitive, TextureResource const& texture) { withTexture(texture, [&primitive]() { auto const program = primitive.programId; glUseProgram(program); auto const resolutionLoc = glGetUniformLocation(program, "iResolution"); if (resolutionLoc) { GLint wh[4]; glGetIntegerv(GL_VIEWPORT, wh); glUniform3f(resolutionLoc, glfloat(wh[2]), glfloat(wh[3]), 0.0f); } withVertexArray(primitive.array, [&primitive]() { glDrawElements(GL_TRIANGLES, primitive.elementCount, GL_UNSIGNED_INT, 0); }); glUseProgram(0); }); } struct SimpleShaderProgram : public ShaderProgramResource { VertexShaderResource vertexShader; FragmentShaderResource fragmentShader; }; static void defineProgram(SimpleShaderProgram& program, std::string const& vertexShaderSource, std::string const& fragmentShaderSource) { compile(program.vertexShader, vertexShaderSource); compile(program.fragmentShader, fragmentShaderSource); glAttachShader(program.id, program.vertexShader.id); glAttachShader(program.id, program.fragmentShader.id); glLinkProgram(program.id); withShaderProgram(program, [&program]() { GLint textureLoc = glGetUniformLocation(program.id, "tex"); GLint colorLoc = glGetUniformLocation(program.id, "g_color"); GLint transformLoc = glGetUniformLocation(program.id, "transform"); float idmatrix[4*4] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; glUniformMatrix4fv(transformLoc, 1, GL_FALSE, idmatrix); glUniform4f(colorLoc, 1.0f, 1.0f, 1.0f, 1.0f); glUniform1i(textureLoc, 0); // bind to texture unit 0 }); } #include "inlineshaders.hpp" static void withPremultipliedAlphaBlending(std::function<void()> fn) { glEnable(GL_BLEND); glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable (GL_DEPTH_TEST); glDepthMask (GL_FALSE); fn(); glDepthMask (GL_TRUE); glEnable (GL_DEPTH_TEST); glDisable(GL_BLEND); } static int nextPowerOfTwo(int number) { return static_cast<int> (pow(2.0, ceil(log2(number)))); } static void seed() { static struct Seed { Seed() { auto resolution = viewport(); auto plane = 0.0f; for (auto const& texture : textures) { withTexture(texture, [&]() { defineNonMipmappedARGB32Texture (nextPowerOfTwo(resolution.first), nextPowerOfTwo(resolution.second), [=](uint32_t* pixels, int width, int height) { perlin_noise(pixels, width, height, plane); }); }); plane += 0.9f; } define2dQuadTriangles(quadTris, -1.0, -1.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0); defineProgram(program, defaultVS, defaultFS); defineRenderingProgram(texturedQuad, program, quadTris); }; TextureResource textures[4]; Geometry quadTris; SimpleShaderProgram program; RenderingProgram texturedQuad; } all; if (all.program.id > 0) { static int i = 0; withPremultipliedAlphaBlending ([&] () { auto colorLoc = glGetUniformLocation(all.program.id, "g_color"); auto period = 29; withShaderProgram(all.program, [=]() { auto origin = period*(i/period); auto maxAlpha = 0.12f; auto const alpha = maxAlpha * sin(TAU * (i - origin)/(2.0 * period)); glUniform4f(colorLoc, glfloat(alpha*1.0), glfloat(alpha*1.0), glfloat(alpha*1.0), glfloat(alpha)); }); drawTriangles(all.texturedQuad, all.textures[i/10 % 4]); }); OGL_TRACE; i++; } } RazorsResource makeRazors() { return estd::make_unique<Razors>(); } static void withOutputTo(Framebuffer const& framebuffer, std::function<void()> draw) { auto resolution = viewport(); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.output.id); glDrawBuffer (GL_COLOR_ATTACHMENT0); glReadBuffer (GL_COLOR_ATTACHMENT0); glViewport (0, 0, framebuffer.width, framebuffer.height); draw(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glReadBuffer (GL_BACK); glDrawBuffer (GL_BACK); glViewport(0, 0, resolution.first, resolution.second); } static void projectFramebuffer(Framebuffer const& source, float const scale = 1.0f) { static struct Projector { Projector () { define2dQuadTriangles(quadGeometry, -1.0, -1.0, 2.0, 2.0, 0.0, 0.0, 1.0, 1.0); defineProgram(program, defaultVS, projectorFS); defineRenderingProgram(texturedQuad, program, quadGeometry); } Geometry quadGeometry; SimpleShaderProgram program; RenderingProgram texturedQuad; } all; if (all.program.id > 0) { // respect source projector's aspect ratio float const yfactor = glfloat(source.height) / glfloat(source.width); define2dQuadTriangles(all.quadGeometry, -1.0f, -yfactor, 2.0f, 2.0f * yfactor, 0.0f, 0.0f, 1.0f, 1.0f); GLint colorLoc = glGetUniformLocation(all.program.id, "g_color"); GLint transformLoc = glGetUniformLocation(all.program.id, "transform"); // scale to screen auto resolution = viewport(); float const targetYFactor = glfloat(resolution.second) / glfloat( resolution.first); float idmatrix[4*4] = { scale, 0.01f, 0.0f, 0.0f, -0.01f, scale / targetYFactor, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; withShaderProgram (all.program, [transformLoc,colorLoc,&idmatrix]() { glUniformMatrix4fv(transformLoc, 1, GL_FALSE, idmatrix); auto const alpha = 0.9998f; glUniform4f(colorLoc, alpha*1.0f, alpha*1.0f, alpha*1.0f, alpha); }); drawTriangles(all.texturedQuad, source.result); } } void draw(Razors& self, double ms) { OGL_TRACE; withOutputTo(self.previousFrame, [&self,ms] () { clear(); projectFramebuffer(self.resultFrame, glfloat(0.990f + 0.010f * sin(TAU * ms / 5000.0))); seed(); }); withOutputTo(self.resultFrame, [&self] () { clear(); projectFramebuffer(self.previousFrame, 1.004f); }); clear(); projectFramebuffer(self.resultFrame); } <|endoftext|>
<commit_before>#include "gmml/internal/residue.h" #include <stdexcept> #include "gmml/internal/atom.h" #include "gmml/internal/graph.h" #include "gmml/internal/structure.h" #include "gmml/internal/stubs/utils.h" using std::string; using std::vector; namespace gmml { Residue::Residue() : name_(""), bonds_(new Graph), head_(-1), tail_(-1) {} Residue::Residue(const string& name) : name_(name), bonds_(new Graph), head_(-1), tail_(-1) {} Residue::Residue(const Structure& structure, const string& name) : name_(name) { for (Structure::const_iterator it = structure.begin(); it != structure.end(); ++it) { atoms_.push_back((*it)->clone()); } bonds_ = structure.bonds()->clone(); head_ = structure.head(); tail_ = structure.tail(); } Residue::Residue(const string& name, const vector<Atom*> *atoms, const Graph *bonds) : name_(name), head_(-1), tail_(-1) { set_atoms(atoms); if (bonds != NULL) bonds_ = bonds->clone(); else bonds_ = new Graph(size()); } Residue::~Residue() { STLDeleteContainerPointers(atoms_.begin(), atoms_.end()); if (bonds_ != NULL) delete bonds_; } void Residue::append(const Atom *atom) { atoms_.push_back(atom->clone()); } int Residue::get_index(const string& atom_name) const { for (const_iterator it = begin(); it != end(); ++it) { if ((*it)->name() == atom_name) { return std::distance(begin(), it); } } return -1; } const vector<size_t>& Residue::bonds(int index) const { return bonds_->edges(index); } void Residue::remove_atom(int index) { if (index < 0 || index >= size()) { throw std::invalid_argument("Invalid residue index " + to_string(index) + "."); } bonds_->remove_vertex(index); delete atoms_[index]; atoms_.erase(atoms_.begin() + index); if (head_ == index) { head_ = -1; } else if (head_ != -1 && head_ > index) { head_--; } if (tail_ == index) { tail_ = -1; } else if (tail_ != -1 && tail_ > index) { tail_--; } } void Residue::remove_atom(const std::string& name) { int index = get_index(name); if (index == -1) { throw std::invalid_argument("Invalid atom name " + name + "."); } remove_atom(index); } void Residue::set_atoms(const vector<Atom*> *atoms) { STLDeleteContainerPointers(atoms_.begin(), atoms_.end()); atoms_.clear(); std::vector<Atom*>::const_iterator it = atoms->begin(); while (it != atoms->end()) { atoms_.push_back((*it)->clone()); ++it; } } void Residue::set_bonds(const Graph *bonds) { if (bonds_ != NULL) delete bonds_; if (bonds != NULL) bonds_ = bonds->clone(); else bonds_ = NULL; } Atom *Residue::atoms(const std::string& atom_name) { for (int i = 0; i < atoms_.size(); i++) { if (atoms_[i]->name() == atom_name) return atoms_[i]; } return NULL; } void Residue::clone_from(const Residue *residue) { name_ = residue->name(); set_atoms(&residue->atoms_); set_bonds(residue->bonds_); head_ = residue->head(); tail_ = residue->tail(); } void IndexedResidue::set_atom_index(const string& atom_name, int index) { for (int i = 0; i < static_cast<int>(size()); i++) { if (atoms(i)->name() == atom_name) { indices_[i] = index; break; } } } int IndexedResidue::get_atom_index(const string& atom_name) const { for (int i = 0; i < static_cast<int>(size()); i++) { if (atoms(i)->name() == atom_name) { return indices_[i]; } } return -1; } } // namespace gmml <commit_msg>Fix bug in removing atoms from residues.<commit_after>#include "gmml/internal/residue.h" #include <stdexcept> #include "gmml/internal/atom.h" #include "gmml/internal/graph.h" #include "gmml/internal/structure.h" #include "gmml/internal/stubs/utils.h" using std::string; using std::vector; namespace gmml { Residue::Residue() : name_(""), bonds_(new Graph), head_(-1), tail_(-1) {} Residue::Residue(const string& name) : name_(name), bonds_(new Graph), head_(-1), tail_(-1) {} Residue::Residue(const Structure& structure, const string& name) : name_(name) { for (Structure::const_iterator it = structure.begin(); it != structure.end(); ++it) { atoms_.push_back((*it)->clone()); } bonds_ = structure.bonds()->clone(); head_ = structure.head(); tail_ = structure.tail(); } Residue::Residue(const string& name, const vector<Atom*> *atoms, const Graph *bonds) : name_(name), head_(-1), tail_(-1) { set_atoms(atoms); if (bonds != NULL) bonds_ = bonds->clone(); else bonds_ = new Graph(size()); } Residue::~Residue() { STLDeleteContainerPointers(atoms_.begin(), atoms_.end()); if (bonds_ != NULL) delete bonds_; } void Residue::append(const Atom *atom) { atoms_.push_back(atom->clone()); } int Residue::get_index(const string& atom_name) const { for (const_iterator it = begin(); it != end(); ++it) { if ((*it)->name() == atom_name) { return std::distance(begin(), it); } } return -1; } const vector<size_t>& Residue::bonds(int index) const { return bonds_->edges(index); } void Residue::remove_atom(int index) { if (index < 0 || index >= size()) { throw std::invalid_argument("Invalid residue index " + to_string(index) + "."); } if (bonds_ != NULL) { bonds_->remove_vertex(index); } delete atoms_[index]; atoms_.erase(atoms_.begin() + index); if (head_ == index) { head_ = -1; } else if (head_ != -1 && head_ > index) { head_--; } if (tail_ == index) { tail_ = -1; } else if (tail_ != -1 && tail_ > index) { tail_--; } } void Residue::remove_atom(const std::string& name) { int index = get_index(name); if (index == -1) { throw std::invalid_argument("Invalid atom name " + name + "."); } remove_atom(index); } void Residue::set_atoms(const vector<Atom*> *atoms) { STLDeleteContainerPointers(atoms_.begin(), atoms_.end()); atoms_.clear(); std::vector<Atom*>::const_iterator it = atoms->begin(); while (it != atoms->end()) { atoms_.push_back((*it)->clone()); ++it; } } void Residue::set_bonds(const Graph *bonds) { if (bonds_ != NULL) delete bonds_; if (bonds != NULL) bonds_ = bonds->clone(); else bonds_ = NULL; } Atom *Residue::atoms(const std::string& atom_name) { for (int i = 0; i < atoms_.size(); i++) { if (atoms_[i]->name() == atom_name) return atoms_[i]; } return NULL; } void Residue::clone_from(const Residue *residue) { name_ = residue->name(); set_atoms(&residue->atoms_); set_bonds(residue->bonds_); head_ = residue->head(); tail_ = residue->tail(); } void IndexedResidue::set_atom_index(const string& atom_name, int index) { for (int i = 0; i < static_cast<int>(size()); i++) { if (atoms(i)->name() == atom_name) { indices_[i] = index; break; } } } int IndexedResidue::get_atom_index(const string& atom_name) const { for (int i = 0; i < static_cast<int>(size()); i++) { if (atoms(i)->name() == atom_name) { return indices_[i]; } } return -1; } } // namespace gmml <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/tokenizer.hpp> //Boost tokenizer #include <unistd.h> // Fork() #include <sys/types.h> // Wait() #include <sys/wait.h> // Wait() #include <vector> #include <stdio.h> //Perror() #include <errno.h> // Perror() #include <algorithm> using namespace std; using namespace boost; // Chose to write function comparing c-strings rather than copy to string then compare // Used for checking exit command bool cStringEqual(char* c1, char* c2) { int i; for(i = 0; c1[i] != '\n' && c2[i] != '\n'; ++i) { if(c1[i] != c2[i]) { return false; } } if(c1[i] != '\n' || c2[i] != '\n') { return false; } return true; } int main() { while(true) //Shell runs until the exit command { cout << "$"; // Prints command prompt string commandLine; getline(cin, commandLine); // Accounts for comments by removing parts that are comments // TODO: Account for escape character + comment (\#) if(commandLine.find(" #") != string::npos) { commandLine = commandLine.substr(commandLine.find(" #")); } // Finds locations of connectors; a && b, && has a location of 3 vector<unsigned int> connectorLocs; unsigned int marker = 0; // Marks location to start find() from unsigned int loc = commandLine.find("&&", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "&&" loc = commandLine.find("&&", marker); } marker = 0; loc = commandLine.find("||", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "||" loc = commandLine.find("||", marker); } marker = 0; loc = commandLine.find(";", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 1; // Starts searching after ";" loc = commandLine.find(";", marker); } connectorLocs.push_back(0); // Will be sorted and put in beginning sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring connectorLocs.push_back(commandLine.size()); // One past end index will act like connector // Runs through subcommands and runs each one // Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected) for(unsigned int i = 0; i < connectorLocs.size() - 1; ++i) // # of subcommands == # of connectors - 1 (including 0, one-past-end) { // For parsing line of commands; delimiter is whitespace, each token will be a command or an argument vector<char*> args; char_separator<char> delim(" "); tokenizer<char_separator<char>> tok(commandLine.substr(connectorLocs.at(i), connectorLocs.at(i+1) - connectorLocs.at(i)), delim); // First token is the command, other tokens are the arguments for(auto iter = tok.begin(); iter != tok.end(); ++iter) { args.push_back(const_cast<char*> (iter->c_str())); } char* exitCString = const_cast<char*> ("exit"); if(cStringEqual(args.at(0), exitCString)) // if command is exit, exit shell { exit(0); } // Executes commands/takes care of errors int pid = fork(); if(pid == -1) // If fork fails { perror("Fork error"); exit(1); } else { if(pid == 0) // Child process { execvp(args.at(0), &args.at(0)); // Following don't run if execvp succeeds perror("Command execution error"); _exit(1); } else // Parent process { int status; // Status isn't used but might use in future? if(wait(&status) == -1) // If child process has error { perror("Child process error"); // exits if next connector is && or one-past-end element // continues if next connector is ; or || if(connectorLocs.at(i+1) == commandLine.size() || commandLine.at(connectorLocs.at(i+1)) == '&') { break; } } } } } } return 0; } <commit_msg>Bugfixes<commit_after>#include <iostream> #include <string> #include <boost/tokenizer.hpp> //Boost tokenizer #include <unistd.h> // Fork() #include <sys/types.h> // Wait() #include <sys/wait.h> // Wait() #include <vector> #include <stdio.h> //Perror() #include <errno.h> // Perror() #include <algorithm> using namespace std; using namespace boost; // Chose to write function comparing c-strings rather than copy to string then compare // Used for checking exit command bool cStringEqual(char* c1, char* c2) { int i; for(i = 0; c1[i] != '\n' && c2[i] != '\n'; ++i) { if(c1[i] != c2[i]) { return false; } } if(c1[i] != '\n' || c2[i] != '\n') { return false; } return true; } int main() { while(true) //Shell runs until the exit command { cout << "$"; // Prints command prompt string commandLine; getline(cin, commandLine); cout << 1 << endl; // DEBUGGING // Accounts for comments by removing parts that are comments // TODO: Account for escape character + comment (\#) if(commandLine.find(" #") != string::npos) { commandLine = commandLine.substr(commandLine.find(" #")); } cout << 2 << endl; // DEBUGGING // Finds locations of connectors; a && b, && has a location of 3 vector<unsigned int> connectorLocs; unsigned int marker = 0; // Marks location to start find() from while(commandLine.find("&&", marker) != string::npos)//loc != string::npos) { connectorLocs.push_back(commandLine.find("&&", marker)); marker = commandLine.find("&&", marker) + 2;//loc + 2; // Starts searching after "&&" } cout << 4 << endl; marker = 0; while(commandLine.find("||", marker) != string::npos) { connectorLocs.push_back(commandLine.find("||", marker)); marker = commandLine.find("||", marker) + 2; // Starts searching after "||" } marker = 0; while(commandLine.find(";", marker) != string::npos) { connectorLocs.push_back(commandLine.find(";", marker)); marker = commandLine.find(";", marker)+ 1; // Starts searching after ";" } connectorLocs.push_back(0); // Will be sorted and put in beginning sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring connectorLocs.push_back(commandLine.size()); // One past end index will act like connector cout << 3 << endl; // DEBUGGING // Runs through subcommands and runs each one // Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected) for(unsigned int i = 0; i < connectorLocs.size() - 1; ++i) // # of subcommands == # of connectors - 1 (including 0, one-past-end) { // For parsing line of commands; delimiter is whitespace, each token will be a command or an argument vector<char*> args; char_separator<char> delim(" "); tokenizer<char_separator<char>> tok(commandLine.substr(connectorLocs.at(i), connectorLocs.at(i+1) - connectorLocs.at(i)), delim); // First token is the command, other tokens are the arguments for(auto iter = tok.begin(); iter != tok.end(); ++iter) { args.push_back(const_cast<char*> (iter->c_str())); } char* exitCString = const_cast<char*> ("exit"); if(cStringEqual(args.at(0), exitCString)) // if command is exit, exit shell { exit(0); } // Executes commands/takes care of errors int pid = fork(); if(pid == -1) // If fork fails { perror("Fork error"); exit(1); } else { if(pid == 0) // Child process { execvp(args.at(0), &args.at(0)); // Following don't run if execvp succeeds perror("Command execution error"); _exit(1); } else // Parent process { int status; // Status isn't used but might use in future? if(wait(&status) == -1) // If child process has error { perror("Child process error"); // exits if next connector is && or one-past-end element // continues if next connector is ; or || if(connectorLocs.at(i+1) == commandLine.size() || commandLine.at(connectorLocs.at(i+1)) == '&') { break; } } } } } } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <fstream> #include <iostream> #include <memory> #include <set> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/string/split.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #include "paddle/fluid/platform/dynload/cupti.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DECLARE_int32(paddle_num_threads); DEFINE_int32(multiple_of_cupti_buffer_size, 1, "Multiple of the CUPTI device buffer size. If the timestamps have " "been dropped when you are profiling, try increasing this value."); namespace paddle { namespace framework { #ifdef _WIN32 #define strdup _strdup #endif std::once_flag gflags_init_flag; std::once_flag glog_init_flag; std::once_flag p2p_init_flag; std::once_flag glog_warning_once_flag; bool InitGflags(std::vector<std::string> argv) { bool successed = false; std::call_once(gflags_init_flag, [&]() { FLAGS_logtostderr = true; // NOTE(zhiqiu): dummy is needed, since the function // ParseNewCommandLineFlags in gflags.cc starts processing // commandline strings from idx 1. // The reason is, it assumes that the first one (idx 0) is // the filename of executable file. argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } VLOG(1) << "Before Parse: argc is " << argc << ", Init commandline: " << line; google::ParseCommandLineFlags(&argc, &arr, true); VLOG(1) << "After Parse: argc is " << argc; successed = true; }); return successed; } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitCupti() { #ifdef PADDLE_WITH_CUPTI if (FLAGS_multiple_of_cupti_buffer_size == 1) return; size_t attrValue = 0, attrValueSize = sizeof(size_t); #define MULTIPLY_ATTR_VALUE(attr) \ { \ PADDLE_ENFORCE(!platform::dynload::cuptiActivityGetAttribute( \ attr, &attrValueSize, &attrValue)); \ attrValue *= FLAGS_multiple_of_cupti_buffer_size; \ LOG(WARNING) << "Set " #attr " " << attrValue << " byte"; \ PADDLE_ENFORCE(!platform::dynload::cuptiActivitySetAttribute( \ attr, &attrValueSize, &attrValue)); \ } MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE); MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP); #if CUDA_VERSION >= 9000 MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE); #endif #undef MULTIPLY_ATTR_VALUE #endif } void InitDevices(bool init_p2p) { // CUPTI attribute should be set before any CUDA context is created (see CUPTI // documentation about CUpti_ActivityAttribute). InitCupti(); /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { // use user specified GPUs in single-node multi-process mode. devices = platform::GetSelectedDevices(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; for (size_t i = 0; i < devices.size(); ++i) { // In multi process multi gpu mode, we may have gpuid = 7 // but count = 1. if (devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::MayIUse(platform::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::MayIUse(platform::avx512f)) { if (platform::MayIUse(platform::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::MayIUse(platform::avx2)) { if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } #ifndef _WIN32 void SignalHandle(const char *data, int size) { auto file_path = string::Sprintf("/tmp/paddle.%d.dump_info", ::getpid()); try { // The signal is coming line by line but we print general guide just once std::call_once(glog_warning_once_flag, [&]() { LOG(WARNING) << "Warning: PaddlePaddle catches a failure signal, it may " "not work properly\n"; LOG(WARNING) << "You could check whether you killed PaddlePaddle " "thread/process accidentally or report the case to " "PaddlePaddle\n"; LOG(WARNING) << "The detail failure signal is:\n\n"; }); LOG(WARNING) << std::string(data, size); std::ofstream dump_info; dump_info.open(file_path, std::ios::app); dump_info << std::string(data, size); dump_info.close(); } catch (...) { } } #endif void InitGLOG(const std::string &prog_name) { std::call_once(glog_init_flag, [&]() { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); google::InstallFailureWriter(&SignalHandle); #endif }); } } // namespace framework } // namespace paddle <commit_msg>use vector instead of pointer, test=develop (#24620)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <fstream> #include <iostream> #include <memory> #include <set> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/string/split.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #include "paddle/fluid/platform/dynload/cupti.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DECLARE_int32(paddle_num_threads); DEFINE_int32(multiple_of_cupti_buffer_size, 1, "Multiple of the CUPTI device buffer size. If the timestamps have " "been dropped when you are profiling, try increasing this value."); namespace paddle { namespace framework { #ifdef _WIN32 #define strdup _strdup #endif std::once_flag gflags_init_flag; std::once_flag glog_init_flag; std::once_flag p2p_init_flag; std::once_flag glog_warning_once_flag; bool InitGflags(std::vector<std::string> args) { bool successed = false; std::call_once(gflags_init_flag, [&]() { FLAGS_logtostderr = true; // NOTE(zhiqiu): dummy is needed, since the function // ParseNewCommandLineFlags in gflags.cc starts processing // commandline strings from idx 1. // The reason is, it assumes that the first one (idx 0) is // the filename of executable file. args.insert(args.begin(), "dummy"); std::vector<char *> argv; std::string line; int argc = args.size(); for (auto &arg : args) { argv.push_back(const_cast<char *>(arg.data())); line += arg; line += ' '; } VLOG(1) << "Before Parse: argc is " << argc << ", Init commandline: " << line; char **arr = argv.data(); google::ParseCommandLineFlags(&argc, &arr, true); successed = true; VLOG(1) << "After Parse: argc is " << argc; }); return successed; } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitCupti() { #ifdef PADDLE_WITH_CUPTI if (FLAGS_multiple_of_cupti_buffer_size == 1) return; size_t attrValue = 0, attrValueSize = sizeof(size_t); #define MULTIPLY_ATTR_VALUE(attr) \ { \ PADDLE_ENFORCE(!platform::dynload::cuptiActivityGetAttribute( \ attr, &attrValueSize, &attrValue)); \ attrValue *= FLAGS_multiple_of_cupti_buffer_size; \ LOG(WARNING) << "Set " #attr " " << attrValue << " byte"; \ PADDLE_ENFORCE(!platform::dynload::cuptiActivitySetAttribute( \ attr, &attrValueSize, &attrValue)); \ } MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE); MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP); #if CUDA_VERSION >= 9000 MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE); #endif #undef MULTIPLY_ATTR_VALUE #endif } void InitDevices(bool init_p2p) { // CUPTI attribute should be set before any CUDA context is created (see CUPTI // documentation about CUpti_ActivityAttribute). InitCupti(); /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { // use user specified GPUs in single-node multi-process mode. devices = platform::GetSelectedDevices(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; for (size_t i = 0; i < devices.size(); ++i) { // In multi process multi gpu mode, we may have gpuid = 7 // but count = 1. if (devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::MayIUse(platform::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::MayIUse(platform::avx512f)) { if (platform::MayIUse(platform::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::MayIUse(platform::avx2)) { if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } #ifndef _WIN32 void SignalHandle(const char *data, int size) { auto file_path = string::Sprintf("/tmp/paddle.%d.dump_info", ::getpid()); try { // The signal is coming line by line but we print general guide just once std::call_once(glog_warning_once_flag, [&]() { LOG(WARNING) << "Warning: PaddlePaddle catches a failure signal, it may " "not work properly\n"; LOG(WARNING) << "You could check whether you killed PaddlePaddle " "thread/process accidentally or report the case to " "PaddlePaddle\n"; LOG(WARNING) << "The detail failure signal is:\n\n"; }); LOG(WARNING) << std::string(data, size); std::ofstream dump_info; dump_info.open(file_path, std::ios::app); dump_info << std::string(data, size); dump_info.close(); } catch (...) { } } #endif void InitGLOG(const std::string &prog_name) { std::call_once(glog_init_flag, [&]() { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); google::InstallFailureWriter(&SignalHandle); #endif }); } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <fstream> #include <iostream> #include <memory> #include <set> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/string/split.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #include "paddle/fluid/platform/dynload/cupti.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DECLARE_int32(paddle_num_threads); DEFINE_int32(multiple_of_cupti_buffer_size, 1, "Multiple of the CUPTI device buffer size. If the timestamps have " "been dropped when you are profiling, try increasing this value."); namespace paddle { namespace framework { #ifdef _WIN32 #define strdup _strdup #endif std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { FLAGS_logtostderr = true; argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(1) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitCupti() { #ifdef PADDLE_WITH_CUPTI if (FLAGS_multiple_of_cupti_buffer_size == 1) return; size_t attrValue = 0, attrValueSize = sizeof(size_t); #define MULTIPLY_ATTR_VALUE(attr) \ { \ PADDLE_ENFORCE(!platform::dynload::cuptiActivityGetAttribute( \ attr, &attrValueSize, &attrValue)); \ attrValue *= FLAGS_multiple_of_cupti_buffer_size; \ LOG(WARNING) << "Set " #attr " " << attrValue << " byte"; \ PADDLE_ENFORCE(!platform::dynload::cuptiActivitySetAttribute( \ attr, &attrValueSize, &attrValue)); \ } MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE); MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP); #if CUDA_VERSION >= 9000 MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE); #endif #undef MULTIPLY_ATTR_VALUE #endif } void InitDevices(bool init_p2p) { // CUPTI attribute should be set before any CUDA context is created (see CUPTI // documentation about CUpti_ActivityAttribute). InitCupti(); /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { // use user specified GPUs in single-node multi-process mode. devices = platform::GetSelectedDevices(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; for (size_t i = 0; i < devices.size(); ++i) { // In multi process multi gpu mode, we may have gpuid = 7 // but count = 1. if (devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::MayIUse(platform::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::MayIUse(platform::avx512f)) { if (platform::MayIUse(platform::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::MayIUse(platform::avx2)) { if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } #ifndef _WIN32 void SignalHandle(const char *data, int size) { auto file_path = string::Sprintf("/tmp/paddle.%d.dump_info", ::getpid()); try { LOG(WARNING) << std::string(data, size); std::ofstream dump_info; dump_info.open(file_path, std::ios::app); dump_info << std::string(data, size); dump_info.close(); } catch (...) { } } #endif void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); google::InstallFailureWriter(&SignalHandle); #endif } } // namespace framework } // namespace paddle <commit_msg>Add warning message when initialize GLOG failed. (#21487)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> // for strdup #include <algorithm> #include <fstream> #include <iostream> #include <memory> #include <set> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/string/split.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #include "paddle/fluid/platform/dynload/cupti.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DECLARE_int32(paddle_num_threads); DEFINE_int32(multiple_of_cupti_buffer_size, 1, "Multiple of the CUPTI device buffer size. If the timestamps have " "been dropped when you are profiling, try increasing this value."); namespace paddle { namespace framework { #ifdef _WIN32 #define strdup _strdup #endif std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; std::once_flag glog_warning_once_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { FLAGS_logtostderr = true; argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(1) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitCupti() { #ifdef PADDLE_WITH_CUPTI if (FLAGS_multiple_of_cupti_buffer_size == 1) return; size_t attrValue = 0, attrValueSize = sizeof(size_t); #define MULTIPLY_ATTR_VALUE(attr) \ { \ PADDLE_ENFORCE(!platform::dynload::cuptiActivityGetAttribute( \ attr, &attrValueSize, &attrValue)); \ attrValue *= FLAGS_multiple_of_cupti_buffer_size; \ LOG(WARNING) << "Set " #attr " " << attrValue << " byte"; \ PADDLE_ENFORCE(!platform::dynload::cuptiActivitySetAttribute( \ attr, &attrValueSize, &attrValue)); \ } MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE); MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP); #if CUDA_VERSION >= 9000 MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE); #endif #undef MULTIPLY_ATTR_VALUE #endif } void InitDevices(bool init_p2p) { // CUPTI attribute should be set before any CUDA context is created (see CUPTI // documentation about CUpti_ActivityAttribute). InitCupti(); /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { // use user specified GPUs in single-node multi-process mode. devices = platform::GetSelectedDevices(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; for (size_t i = 0; i < devices.size(); ++i) { // In multi process multi gpu mode, we may have gpuid = 7 // but count = 1. if (devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::MayIUse(platform::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::MayIUse(platform::avx512f)) { if (platform::MayIUse(platform::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::MayIUse(platform::avx2)) { if (platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::MayIUse(platform::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } #ifndef _WIN32 void SignalHandle(const char *data, int size) { auto file_path = string::Sprintf("/tmp/paddle.%d.dump_info", ::getpid()); try { // The signal is coming line by line but we print general guide just once std::call_once(glog_warning_once_flag, [&]() { LOG(WARNING) << "Initialize GLOG failed, PaddlePaddle may not be able to " "print GLOG\n"; LOG(WARNING) << "You could check whether you killed GLOG initialize " "process or PaddlePaddle process accidentally\n"; LOG(WARNING) << "The detail failure signal is:\n\n"; }); LOG(WARNING) << std::string(data, size); std::ofstream dump_info; dump_info.open(file_path, std::ios::app); dump_info << std::string(data, size); dump_info.close(); } catch (...) { } } #endif void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); google::InstallFailureWriter(&SignalHandle); #endif } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved. #include <string> #include "libj/string.h" namespace libj { const Size NO_POS = -1; const Char NO_CHAR = -1; class StringImpl : public String { public: Size length() const { return str8_ ? str8_->length() : str32_ ? str32_->length() : 0; } Char charAt(Size index) const { if (index >= length()) return NO_CHAR; return str8_ ? str8_->at(index) : str32_ ? str32_->at(index) : NO_CHAR; } Cptr substring(Size begin) const { if (begin > length()) { Cptr p(static_cast<String*>(0)); return p; } else if (begin == 0) { Cptr p(this); return p; } else if (str8_) { Cptr p(new StringImpl(str8_, begin)); return p; } else { // if (str32_) Cptr p(new StringImpl(str32_, begin)); return p; } } Cptr substring(Size begin, Size end) const { Size len = length(); if (begin > len || end > len || begin > end) { Cptr p(static_cast<String*>(0)); return p; } else if (begin == 0 && end == len) { Cptr p(this); return p; } else if (str8_) { Cptr p(new StringImpl(str8_, begin, end - begin)); return p; } else { // if (str32_) Cptr p(new StringImpl(str32_, begin, end - begin)); return p; } } Cptr concat(Cptr other) const { if (!other || other->isEmpty()) { return this->toString(); } else if (this->isEmpty()) { return other->toString(); } if (this->str8_ && other->isAscii()) { StringImpl* s = new StringImpl(str8_); Size len = other->length(); for (Size i = 0; i < len; i++) s->str8_->push_back(static_cast<int8_t>(other->charAt(i))); Cptr p(s); return p; } else if (this->str8_ && !other->isAscii()) { StringImpl* s = new StringImpl(); s->str32_ = new Str32(); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); len = other->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } else if (this->str32_ && other->isAscii()) { StringImpl* s = new StringImpl(str32_); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } else { // if (this->str32_ && !other->isAscii()) StringImpl* s = new StringImpl(str32_); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } } Int compareTo(Type<Object>::Cptr that) const { Int result = Object::compareTo(that); if (result) return result; Type<String>::Cptr other = LIBJ_STATIC_CPTR_CAST(String)(that); Size len1 = this->length(); Size len2 = other->length(); Size len = len1 < len2 ? len1 : len2; for (Size i = 0; i < len; i++) { Char c1 = this->charAt(i); Char c2 = other->charAt(i); if (c1 != c2) return c1 - c2; } return len1 - len2; } bool startsWith(Cptr other, Size offset) const { Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return false; for (Size i = 0; i < len2; i++) if (this->charAt(offset + i) != other->charAt(i)) return false; return true; } bool endsWith(Cptr other) const { Size len1 = this->length(); Size len2 = other->length(); if (len1 < len2) return false; Size pos = len1 - len2; for (Size i = 0; i < len2; i++) if (this->charAt(pos + i) != other->charAt(i)) return false; return true; } Size indexOf(Char c, Size offset) const { Size len = length(); for (Size i = offset; i < len; i++) if (charAt(i) == c) return i; return NO_POS; } Size indexOf(Cptr other, Size offset) const { // TODO(PL): make it more efficient Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return NO_POS; Size n = len1 - len2 + 1; for (Size i = offset; i < n; i++) if (startsWith(other, i)) return i; return NO_POS; } Size lastIndexOf(Char c, Size offset) const { Size len = length(); if (len == 0) return NO_POS; for (Size i = offset < len ? offset : len-1; ; i--) { if (charAt(i) == c) return i; if (i == 0) break; } return NO_POS; } Size lastIndexOf(Cptr other, Size offset) const { // TODO(PL): make it more efficient Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return NO_POS; Size from = len1 - len2; from = offset < from ? offset : from; for (Size i = from; ; i--) { if (startsWith(other, i)) return i; if (i == 0) break; } return NO_POS; } bool isEmpty() const { return length() == 0; } bool isAscii() const { return str8_ ? true : str32_ ? false : true; } Cptr toLowerCase() const { Size len = length(); if (isAscii()) { Str8* s = new Str8(); for (Size i = 0; i < len; i++) { char c = static_cast<char>(charAt(i)); if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; *s += c; } Cptr p(new StringImpl(s, 0)); return p; } else { Str32* s = new Str32(); for (Size i = 0; i < len; i++) { Char c = charAt(i); if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; *s += c; } Cptr p(new StringImpl(0, s)); return p; } } Cptr toUpperCase() const { Size len = length(); if (isAscii()) { Str8* s = new Str8(); for (Size i = 0; i < len; i++) { char c = static_cast<char>(charAt(i)); if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *s += c; } Cptr p(new StringImpl(s, 0)); return p; } else { Str32* s = new Str32(); for (Size i = 0; i < len; i++) { Char c = charAt(i); if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *s += c; } Cptr p(new StringImpl(0, s)); return p; } } Cptr toString() const { Cptr p(new StringImpl(this)); return p; } public: static Cptr create() { Cptr p(new StringImpl()); return p; } static Cptr create(const void* data, Encoding enc, Size max) { // TODO(PL): temp if (enc == ASCII) { Cptr p(new StringImpl(static_cast<const char*>(data), max)); return p; } else if (enc == UTF8) { // TODO(PL): use ConvertUTF8toUTF32 Cptr p(new StringImpl()); return p; } else { Cptr p(new StringImpl()); return p; } } private: typedef std::basic_string<char> Str8; typedef std::basic_string<Char> Str32; Str8* str8_; Str32* str32_; StringImpl() : str8_(0) , str32_(0) {} StringImpl(const Str8* s) : str8_(s ? new Str8(*s) : 0) , str32_(0) {} StringImpl(const Str32* s) : str8_(0) , str32_(s ? new Str32(*s) : 0) {} StringImpl(const Str8* s, Size pos, Size count = NO_POS) : str8_(s ? new Str8(*s, pos, count) : 0) , str32_(0) {} StringImpl(const Str32* s, Size pos, Size count = NO_POS) : str8_(0) , str32_(s ? new Str32(*s, pos, count) : 0) {} StringImpl(const char* data, Size count = NO_POS) : str8_(0) , str32_(0) { if (!data) return; for (Size i = 0; i < count; i++) { if (data[i] == 0) { str8_ = new Str8(data); return; } } str8_ = new Str8(data, count); } StringImpl(const Char* data, Size count = NO_POS) : str8_(0) , str32_(0) { if (!data) return; for (Size i = 0; i < count; i++) { if (data[i] == 0) { str32_ = new Str32(data); return; } } str32_ = new Str32(data, count); } StringImpl(Str8* s8, Str32* s32) : str8_(s8) , str32_(s32) { } StringImpl(const StringImpl* s) : str8_(s->str8_ ? new Str8(*(s->str8_)) : 0) , str32_(s->str32_ ? new Str32(*(s->str32_)) : 0) { } public: ~StringImpl() { delete str8_; delete str32_; } }; Type<String>::Cptr String::create() { return StringImpl::create(); } Type<String>::Cptr String::create(const void* data, Encoding enc, Size max) { return StringImpl::create(data, enc, max); } static Type<String>::Cptr LIBJ_STR_TRUE = String::create("true"); static Type<String>::Cptr LIBJ_STR_FALSE = String::create("false"); static Type<String>::Cptr booleanToString(const Value& val) { Boolean b; to<Boolean>(val, &b); return b ? LIBJ_STR_TRUE : LIBJ_STR_FALSE; } static Type<String>::Cptr byteToString(const Value& val) { Byte b; to<Byte>(val, &b); const Size len = (8 / 3) + 3; char s[len]; snprintf(s, len, "%d", b); return String::create(s); } static Type<String>::Cptr shortToString(const Value& val) { Short sh; to<Short>(val, &sh); const Size len = (16 / 3) + 3; char s[len]; snprintf(s, len, "%d", sh); return String::create(s); } static Type<String>::Cptr intToString(const Value& val) { Int i; to<Int>(val, &i); const Size len = (32 / 3) + 3; char s[len]; snprintf(s, len, "%d", i); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr longToString(const Value& val) { Long l; to<Long>(val, &l); const Size len = (64 / 3) + 3; char s[len]; snprintf(s, len, "%lld", l); return String::create(s); } static Type<String>::Cptr floatToString(const Value& val) { Float f; to<Float>(val, &f); const Size len = (32 / 3) + 5; char s[len]; snprintf(s, len, "%f", f); return String::create(s); } static Type<String>::Cptr doubleToString(const Value& val) { Double d; to<Double>(val, &d); const Size len = (64 / 3) + 5; char s[len]; snprintf(s, len, "%lf", d); return String::create(s); } static Type<String>::Cptr sizeToString(const Value& val) { Size n; to<Size>(val, &n); const Size len = (sizeof(Size) / 3) + 3; char s[len]; snprintf(s, len, "%zd", n); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr typeIdToString(const Value& val) { TypeId t; to<TypeId>(val, &t); const Size len = (sizeof(TypeId) / 3) + 3; char s[len]; snprintf(s, len, "%zd", t); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr objectToString(const Value& val) { Type<Object>::Cptr o = toCptr<Object>(val); if (o) return o->toString(); else { LIBJ_NULL_CPTR(String, nullp); return nullp; } } Type<String>::Cptr String::valueOf(const Value& val) { if (val.empty()) { LIBJ_NULL_CPTR(String, nullp); return nullp; } else if (val.type() == Type<Boolean>::id()) { return booleanToString(val); } else if (val.type() == Type<Byte>::id()) { return byteToString(val); } else if (val.type() == Type<Short>::id()) { return shortToString(val); } else if (val.type() == Type<Int>::id()) { return intToString(val); } else if (val.type() == Type<Long>::id()) { return longToString(val); } else if (val.type() == Type<Float>::id()) { return floatToString(val); } else if (val.type() == Type<Double>::id()) { return doubleToString(val); } else if (val.type() == Type<Size>::id()) { return sizeToString(val); } else if (val.type() == Type<TypeId>::id()) { return typeIdToString(val); } else if (val.instanceOf(Type<Object>::id())) { return objectToString(val); } else { LIBJ_NULL_CPTR(String, nullp); return nullp; } } } // namespace libj <commit_msg>include stdio.h<commit_after>// Copyright (c) 2012 Plenluno All rights reserved. #include <string> #include <stdio.h> #include "libj/string.h" namespace libj { const Size NO_POS = -1; const Char NO_CHAR = -1; class StringImpl : public String { public: Size length() const { return str8_ ? str8_->length() : str32_ ? str32_->length() : 0; } Char charAt(Size index) const { if (index >= length()) return NO_CHAR; return str8_ ? str8_->at(index) : str32_ ? str32_->at(index) : NO_CHAR; } Cptr substring(Size begin) const { if (begin > length()) { Cptr p(static_cast<String*>(0)); return p; } else if (begin == 0) { Cptr p(this); return p; } else if (str8_) { Cptr p(new StringImpl(str8_, begin)); return p; } else { // if (str32_) Cptr p(new StringImpl(str32_, begin)); return p; } } Cptr substring(Size begin, Size end) const { Size len = length(); if (begin > len || end > len || begin > end) { Cptr p(static_cast<String*>(0)); return p; } else if (begin == 0 && end == len) { Cptr p(this); return p; } else if (str8_) { Cptr p(new StringImpl(str8_, begin, end - begin)); return p; } else { // if (str32_) Cptr p(new StringImpl(str32_, begin, end - begin)); return p; } } Cptr concat(Cptr other) const { if (!other || other->isEmpty()) { return this->toString(); } else if (this->isEmpty()) { return other->toString(); } if (this->str8_ && other->isAscii()) { StringImpl* s = new StringImpl(str8_); Size len = other->length(); for (Size i = 0; i < len; i++) s->str8_->push_back(static_cast<int8_t>(other->charAt(i))); Cptr p(s); return p; } else if (this->str8_ && !other->isAscii()) { StringImpl* s = new StringImpl(); s->str32_ = new Str32(); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); len = other->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } else if (this->str32_ && other->isAscii()) { StringImpl* s = new StringImpl(str32_); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } else { // if (this->str32_ && !other->isAscii()) StringImpl* s = new StringImpl(str32_); Size len = this->length(); for (Size i = 0; i < len; i++) s->str32_->push_back(other->charAt(i)); Cptr p(s); return p; } } Int compareTo(Type<Object>::Cptr that) const { Int result = Object::compareTo(that); if (result) return result; Type<String>::Cptr other = LIBJ_STATIC_CPTR_CAST(String)(that); Size len1 = this->length(); Size len2 = other->length(); Size len = len1 < len2 ? len1 : len2; for (Size i = 0; i < len; i++) { Char c1 = this->charAt(i); Char c2 = other->charAt(i); if (c1 != c2) return c1 - c2; } return len1 - len2; } bool startsWith(Cptr other, Size offset) const { Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return false; for (Size i = 0; i < len2; i++) if (this->charAt(offset + i) != other->charAt(i)) return false; return true; } bool endsWith(Cptr other) const { Size len1 = this->length(); Size len2 = other->length(); if (len1 < len2) return false; Size pos = len1 - len2; for (Size i = 0; i < len2; i++) if (this->charAt(pos + i) != other->charAt(i)) return false; return true; } Size indexOf(Char c, Size offset) const { Size len = length(); for (Size i = offset; i < len; i++) if (charAt(i) == c) return i; return NO_POS; } Size indexOf(Cptr other, Size offset) const { // TODO(PL): make it more efficient Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return NO_POS; Size n = len1 - len2 + 1; for (Size i = offset; i < n; i++) if (startsWith(other, i)) return i; return NO_POS; } Size lastIndexOf(Char c, Size offset) const { Size len = length(); if (len == 0) return NO_POS; for (Size i = offset < len ? offset : len-1; ; i--) { if (charAt(i) == c) return i; if (i == 0) break; } return NO_POS; } Size lastIndexOf(Cptr other, Size offset) const { // TODO(PL): make it more efficient Size len1 = this->length(); Size len2 = other->length(); if (len1 < offset + len2) return NO_POS; Size from = len1 - len2; from = offset < from ? offset : from; for (Size i = from; ; i--) { if (startsWith(other, i)) return i; if (i == 0) break; } return NO_POS; } bool isEmpty() const { return length() == 0; } bool isAscii() const { return str8_ ? true : str32_ ? false : true; } Cptr toLowerCase() const { Size len = length(); if (isAscii()) { Str8* s = new Str8(); for (Size i = 0; i < len; i++) { char c = static_cast<char>(charAt(i)); if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; *s += c; } Cptr p(new StringImpl(s, 0)); return p; } else { Str32* s = new Str32(); for (Size i = 0; i < len; i++) { Char c = charAt(i); if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; *s += c; } Cptr p(new StringImpl(0, s)); return p; } } Cptr toUpperCase() const { Size len = length(); if (isAscii()) { Str8* s = new Str8(); for (Size i = 0; i < len; i++) { char c = static_cast<char>(charAt(i)); if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *s += c; } Cptr p(new StringImpl(s, 0)); return p; } else { Str32* s = new Str32(); for (Size i = 0; i < len; i++) { Char c = charAt(i); if (c >= 'a' && c <= 'z') c -= 'a' - 'A'; *s += c; } Cptr p(new StringImpl(0, s)); return p; } } Cptr toString() const { Cptr p(new StringImpl(this)); return p; } public: static Cptr create() { Cptr p(new StringImpl()); return p; } static Cptr create(const void* data, Encoding enc, Size max) { // TODO(PL): temp if (enc == ASCII) { Cptr p(new StringImpl(static_cast<const char*>(data), max)); return p; } else if (enc == UTF8) { // TODO(PL): use ConvertUTF8toUTF32 Cptr p(new StringImpl()); return p; } else { Cptr p(new StringImpl()); return p; } } private: typedef std::basic_string<char> Str8; typedef std::basic_string<Char> Str32; Str8* str8_; Str32* str32_; StringImpl() : str8_(0) , str32_(0) {} StringImpl(const Str8* s) : str8_(s ? new Str8(*s) : 0) , str32_(0) {} StringImpl(const Str32* s) : str8_(0) , str32_(s ? new Str32(*s) : 0) {} StringImpl(const Str8* s, Size pos, Size count = NO_POS) : str8_(s ? new Str8(*s, pos, count) : 0) , str32_(0) {} StringImpl(const Str32* s, Size pos, Size count = NO_POS) : str8_(0) , str32_(s ? new Str32(*s, pos, count) : 0) {} StringImpl(const char* data, Size count = NO_POS) : str8_(0) , str32_(0) { if (!data) return; for (Size i = 0; i < count; i++) { if (data[i] == 0) { str8_ = new Str8(data); return; } } str8_ = new Str8(data, count); } StringImpl(const Char* data, Size count = NO_POS) : str8_(0) , str32_(0) { if (!data) return; for (Size i = 0; i < count; i++) { if (data[i] == 0) { str32_ = new Str32(data); return; } } str32_ = new Str32(data, count); } StringImpl(Str8* s8, Str32* s32) : str8_(s8) , str32_(s32) { } StringImpl(const StringImpl* s) : str8_(s->str8_ ? new Str8(*(s->str8_)) : 0) , str32_(s->str32_ ? new Str32(*(s->str32_)) : 0) { } public: ~StringImpl() { delete str8_; delete str32_; } }; Type<String>::Cptr String::create() { return StringImpl::create(); } Type<String>::Cptr String::create(const void* data, Encoding enc, Size max) { return StringImpl::create(data, enc, max); } static Type<String>::Cptr LIBJ_STR_TRUE = String::create("true"); static Type<String>::Cptr LIBJ_STR_FALSE = String::create("false"); static Type<String>::Cptr booleanToString(const Value& val) { Boolean b; to<Boolean>(val, &b); return b ? LIBJ_STR_TRUE : LIBJ_STR_FALSE; } static Type<String>::Cptr byteToString(const Value& val) { Byte b; to<Byte>(val, &b); const Size len = (8 / 3) + 3; char s[len]; snprintf(s, len, "%d", b); return String::create(s); } static Type<String>::Cptr shortToString(const Value& val) { Short sh; to<Short>(val, &sh); const Size len = (16 / 3) + 3; char s[len]; snprintf(s, len, "%d", sh); return String::create(s); } static Type<String>::Cptr intToString(const Value& val) { Int i; to<Int>(val, &i); const Size len = (32 / 3) + 3; char s[len]; snprintf(s, len, "%d", i); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr longToString(const Value& val) { Long l; to<Long>(val, &l); const Size len = (64 / 3) + 3; char s[len]; snprintf(s, len, "%lld", l); return String::create(s); } static Type<String>::Cptr floatToString(const Value& val) { Float f; to<Float>(val, &f); const Size len = (32 / 3) + 5; char s[len]; snprintf(s, len, "%f", f); return String::create(s); } static Type<String>::Cptr doubleToString(const Value& val) { Double d; to<Double>(val, &d); const Size len = (64 / 3) + 5; char s[len]; snprintf(s, len, "%lf", d); return String::create(s); } static Type<String>::Cptr sizeToString(const Value& val) { Size n; to<Size>(val, &n); const Size len = (sizeof(Size) / 3) + 3; char s[len]; snprintf(s, len, "%zd", n); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr typeIdToString(const Value& val) { TypeId t; to<TypeId>(val, &t); const Size len = (sizeof(TypeId) / 3) + 3; char s[len]; snprintf(s, len, "%zd", t); Type<String>::Cptr p = String::create(s); return p; } static Type<String>::Cptr objectToString(const Value& val) { Type<Object>::Cptr o = toCptr<Object>(val); if (o) return o->toString(); else { LIBJ_NULL_CPTR(String, nullp); return nullp; } } Type<String>::Cptr String::valueOf(const Value& val) { if (val.empty()) { LIBJ_NULL_CPTR(String, nullp); return nullp; } else if (val.type() == Type<Boolean>::id()) { return booleanToString(val); } else if (val.type() == Type<Byte>::id()) { return byteToString(val); } else if (val.type() == Type<Short>::id()) { return shortToString(val); } else if (val.type() == Type<Int>::id()) { return intToString(val); } else if (val.type() == Type<Long>::id()) { return longToString(val); } else if (val.type() == Type<Float>::id()) { return floatToString(val); } else if (val.type() == Type<Double>::id()) { return doubleToString(val); } else if (val.type() == Type<Size>::id()) { return sizeToString(val); } else if (val.type() == Type<TypeId>::id()) { return typeIdToString(val); } else if (val.instanceOf(Type<Object>::id())) { return objectToString(val); } else { LIBJ_NULL_CPTR(String, nullp); return nullp; } } } // namespace libj <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <algorithm> #include <cassert> #include <miopen/errors.hpp> #include <miopen/logger.hpp> #include <miopen/tensor.hpp> #include <numeric> #include <string> namespace miopen { TensorDescriptor::TensorDescriptor() {} TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens) : lens(plens), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } this->CalculateStrides(); } TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens, std::initializer_list<std::size_t> pstrides) : lens(plens), strides(pstrides), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } } TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size) : lens(plens, plens + size), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } this->CalculateStrides(); } TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, const int* pstrides, int size) : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } } void TensorDescriptor::CalculateStrides() { strides.clear(); strides.resize(lens.size(), 0); strides.back() = 1; std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>()); } const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; } const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; } int TensorDescriptor::GetSize() const { assert(lens.size() == strides.size()); return lens.size(); } std::size_t TensorDescriptor::GetElementSize() const { assert(lens.size() == strides.size()); return std::accumulate( lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>()); } miopenDataType_t TensorDescriptor::GetType() const { return this->type; } std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const { assert(l.size() <= this->GetSize()); return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0}); } std::size_t TensorDescriptor::GetElementSpace() const { std::vector<std::size_t> maxIndices(lens.size()); std::transform(lens.begin(), lens.end(), std::vector<std::size_t>(lens.size(), 1).begin(), maxIndices.begin(), std::minus<size_t>()); return std::inner_product( maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) + 1; } std::size_t TensorDescriptor::GetNumBytes() const { return sizeof(this->type) * this->GetElementSpace(); } bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const { assert(this->lens.size() == rhs.strides.size()); return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides; } bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); } std::string TensorDescriptor::ToString() const { std::string result; for(auto i : this->lens) { result += std::to_string(i) + ", "; } return result.substr(0, result.length() - 2); } std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t) { return LogRange(stream, t.lens, ", "); } } // namespace miopen // TODO(paul): Remove MIOPEN_EXPORT int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices) { return miopen::deref(tensorDesc).GetIndex(indices); } <commit_msg>Fixed bug with miopen::TensorDescriptor->GetNumBytes() calculating sizeof enum not size of type.<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <algorithm> #include <cassert> #include <miopen/errors.hpp> #include <miopen/logger.hpp> #include <miopen/tensor.hpp> #include <numeric> #include <string> namespace miopen { TensorDescriptor::TensorDescriptor() {} TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens) : lens(plens), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } this->CalculateStrides(); } TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens, std::initializer_list<std::size_t> pstrides) : lens(plens), strides(pstrides), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } } TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size) : lens(plens, plens + size), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } this->CalculateStrides(); } TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, const int* pstrides, int size) : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t) { if(t != miopenFloat) { MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported"); } } void TensorDescriptor::CalculateStrides() { strides.clear(); strides.resize(lens.size(), 0); strides.back() = 1; std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>()); } const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; } const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; } int TensorDescriptor::GetSize() const { assert(lens.size() == strides.size()); return lens.size(); } std::size_t TensorDescriptor::GetElementSize() const { assert(lens.size() == strides.size()); return std::accumulate( lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>()); } miopenDataType_t TensorDescriptor::GetType() const { return this->type; } std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const { assert(l.size() <= this->GetSize()); return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0}); } std::size_t TensorDescriptor::GetElementSpace() const { std::vector<std::size_t> maxIndices(lens.size()); std::transform(lens.begin(), lens.end(), std::vector<std::size_t>(lens.size(), 1).begin(), maxIndices.begin(), std::minus<size_t>()); return std::inner_product( maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) + 1; } std::size_t TensorDescriptor::GetNumBytes() const { std::size_t typesize = 0; switch(this->type) { case miopenHalf: typesize = 2; break; case miopenFloat: typesize = 4; break; } return typesize * this->GetElementSpace(); } bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const { assert(this->lens.size() == rhs.strides.size()); return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides; } bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); } std::string TensorDescriptor::ToString() const { std::string result; for(auto i : this->lens) { result += std::to_string(i) + ", "; } return result.substr(0, result.length() - 2); } std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t) { return LogRange(stream, t.lens, ", "); } } // namespace miopen // TODO(paul): Remove MIOPEN_EXPORT int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices) { return miopen::deref(tensorDesc).GetIndex(indices); } <|endoftext|>
<commit_before>//===------------------------- thread.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" #ifndef _LIBCPP_HAS_NO_THREADS #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) # include <sys/param.h> # if defined(BSD) # include <sys/sysctl.h> # endif // defined(BSD) #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) # include <unistd.h> #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) #if defined(__NetBSD__) #pragma weak pthread_create // Do not create libpthread dependency #endif #if defined(_LIBCPP_WIN32API) #include <windows.h> #endif // defined(_LIBCPP_WIN32API) _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (!__libcpp_thread_isnull(&__t_)) terminate(); } void thread::join() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_join(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::join failed"); } void thread::detach() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_detach(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::detach failed"); } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. // if sysconf returns some other negative number, we have no idea // what is going on. Default to something safe. if (result < 0) return 0; return static_cast<unsigned>(result); #elif defined(_LIBCPP_WIN32API) SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. # if defined(_LIBCPP_MSVC) _LIBCPP_WARNING("hardware_concurrency not yet implemented") # else # warning hardware_concurrency not yet implemented # endif return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { if (ns > chrono::nanoseconds::zero()) { __libcpp_thread_sleep_for(ns); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD #endif // !_LIBCPP_HAS_NO_THREADS <commit_msg>[libcxx] Support threads on Fuchsia<commit_after>//===------------------------- thread.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" #ifndef _LIBCPP_HAS_NO_THREADS #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) # include <sys/param.h> # if defined(BSD) # include <sys/sysctl.h> # endif // defined(BSD) #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__) # include <unistd.h> #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__) #if defined(__NetBSD__) #pragma weak pthread_create // Do not create libpthread dependency #endif #if defined(_LIBCPP_WIN32API) #include <windows.h> #endif // defined(_LIBCPP_WIN32API) _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (!__libcpp_thread_isnull(&__t_)) terminate(); } void thread::join() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_join(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::join failed"); } void thread::detach() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_detach(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::detach failed"); } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. // if sysconf returns some other negative number, we have no idea // what is going on. Default to something safe. if (result < 0) return 0; return static_cast<unsigned>(result); #elif defined(_LIBCPP_WIN32API) SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. # if defined(_LIBCPP_MSVC) _LIBCPP_WARNING("hardware_concurrency not yet implemented") # else # warning hardware_concurrency not yet implemented # endif return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { if (ns > chrono::nanoseconds::zero()) { __libcpp_thread_sleep_for(ns); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD #endif // !_LIBCPP_HAS_NO_THREADS <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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 <limits.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <openssl/evp.h> #include <iomanip> #include "User.h" /* ************************************************************************** */ /* User :: Constructor/Destructor */ /* ************************************************************************** */ User::User( int id, string _username, string _password, bool _enabled): PoolObjectSQL(id), username (_username), password (_password), enabled (_enabled) {}; User::~User(){}; /* ************************************************************************** */ /* User :: Database Access Functions */ /* ************************************************************************** */ const char * User::table = "user_pool"; const char * User::db_names = "(oid,user_name,password,enabled)"; const char * User::db_bootstrap = "CREATE TABLE user_pool (" "oid INTEGER PRIMARY KEY, user_name TEXT, password TEXT," "enabled INTEGER, UNIQUE(user_name))"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::select_cb(void *nil, int num, char **values, char **names) { if ((!values[OID]) || (!values[USERNAME]) || (!values[PASSWORD]) || (!values[ENABLED]) || (num != LIMIT )) { return -1; } oid = atoi(values[OID]); username = values[USERNAME]; password = values[PASSWORD]; enabled = (atoi(values[ENABLED])==0)?false:true; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::select(SqlDB *db) { ostringstream oss; int rc; int boid; set_callback(static_cast<Callbackable::Callback>(&User::select_cb)); oss << "SELECT * FROM " << table << " WHERE oid = " << oid; boid = oid; oid = -1; rc = db->exec(oss, this); if ((rc != 0) || (oid != boid )) { return -1; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::insert(SqlDB *db) { int rc; rc = insert_replace(db, false); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::update(SqlDB *db) { int rc; rc = insert_replace(db, true); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::insert_replace(SqlDB *db, bool replace) { ostringstream oss; int rc; char * sql_username; char * sql_password; int str_enabled = enabled?1:0; // Update the User sql_username = db->escape_str(username.c_str()); if ( sql_username == 0 ) { goto error_username; } sql_password = db->escape_str(password.c_str()); if ( sql_password == 0 ) { goto error_password; } // Construct the SQL statement to Insert or Replace if(replace) { oss << "REPLACE"; } else { oss << "INSERT"; } oss << " INTO " << table << " "<< db_names <<" VALUES (" << oid << "," << "'" << sql_username << "'," << "'" << sql_password << "'," << str_enabled << ")"; rc = db->exec(oss); db->free_str(sql_username); db->free_str(sql_password); return rc; error_password: db->free_str(sql_username); error_username: return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::dump(ostringstream& oss, int num, char **values, char **names) { if ((!values[OID]) || (!values[USERNAME]) || (!values[PASSWORD]) || (!values[ENABLED]) || (num != LIMIT)) { return -1; } string str_enabled = (atoi(values[ENABLED])==0)?"Fase":"True"; oss << "<USER>" << "<ID>" << values[OID] <<"</ID>" << "<NAME>" << values[USERNAME]<<"</NAME>" << "<PASSWORD>"<< values[PASSWORD]<<"</PASSWORD>"<< "<ENABLED>" << str_enabled <<"</ENABLED>" << "</USER>"; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::drop(SqlDB * db) { ostringstream oss; int rc; oss << "DELETE FROM " << table << " WHERE oid=" << oid; rc = db->exec(oss); if ( rc == 0 ) { set_valid(false); } return rc; } /* ************************************************************************** */ /* User :: Misc */ /* ************************************************************************** */ ostream& operator<<(ostream& os, User& user) { string user_str; os << user.to_xml(user_str); return os; }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string& User::to_xml(string& xml) const { ostringstream oss; int enabled_int = enabled?1:0; oss << "<USER>" "<ID>" << oid <<"</ID>" << "<NAME>" << username <<"</NAME>" << "<PASSWORD>" << password <<"</PASSWORD>" << "<ENABLED>" << enabled_int <<"</ENABLED>" << "</USER>"; xml = oss.str(); return xml; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string& User::to_str(string& str) const { ostringstream os; string enabled_str = enabled?"True":"False"; os << "ID = " << oid << endl << "NAME = " << username << endl << "PASSWORD = " << password << endl << "ENABLED = " << enabled_str; str = os.str(); return str; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::authenticate(string _password) { if (enabled && _password==password) { return oid; } else { return -1; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::split_secret(const string secret, string& user, string& pass) { size_t pos; int rc = -1; pos=secret.find(":"); if (pos != string::npos) { user = secret.substr(0,pos); pass = secret.substr(pos+1); rc = 0; } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string User::sha1_digest(const string& pass) { EVP_MD_CTX mdctx; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; ostringstream oss; EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, EVP_sha1(), NULL); EVP_DigestUpdate(&mdctx, pass.c_str(), pass.length()); EVP_DigestFinal_ex(&mdctx,md_value,&md_len); EVP_MD_CTX_cleanup(&mdctx); for(unsigned int i = 0; i<md_len; i++) { oss << setfill('0') << setw(2) << hex << nouppercase << (unsigned short) md_value[i]; } return oss.str(); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <commit_msg>feature #206: User table definition is now MySQL compliant<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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 <limits.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <openssl/evp.h> #include <iomanip> #include "User.h" /* ************************************************************************** */ /* User :: Constructor/Destructor */ /* ************************************************************************** */ User::User( int id, string _username, string _password, bool _enabled): PoolObjectSQL(id), username (_username), password (_password), enabled (_enabled) {}; User::~User(){}; /* ************************************************************************** */ /* User :: Database Access Functions */ /* ************************************************************************** */ const char * User::table = "user_pool"; const char * User::db_names = "(oid,user_name,password,enabled)"; const char * User::db_bootstrap = "CREATE TABLE user_pool (" "oid INTEGER PRIMARY KEY, user_name VARCHAR(256), password TEXT," "enabled INTEGER, UNIQUE(user_name))"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::select_cb(void *nil, int num, char **values, char **names) { if ((!values[OID]) || (!values[USERNAME]) || (!values[PASSWORD]) || (!values[ENABLED]) || (num != LIMIT )) { return -1; } oid = atoi(values[OID]); username = values[USERNAME]; password = values[PASSWORD]; enabled = (atoi(values[ENABLED])==0)?false:true; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::select(SqlDB *db) { ostringstream oss; int rc; int boid; set_callback(static_cast<Callbackable::Callback>(&User::select_cb)); oss << "SELECT * FROM " << table << " WHERE oid = " << oid; boid = oid; oid = -1; rc = db->exec(oss, this); if ((rc != 0) || (oid != boid )) { return -1; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::insert(SqlDB *db) { int rc; rc = insert_replace(db, false); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::update(SqlDB *db) { int rc; rc = insert_replace(db, true); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::insert_replace(SqlDB *db, bool replace) { ostringstream oss; int rc; char * sql_username; char * sql_password; int str_enabled = enabled?1:0; // Update the User sql_username = db->escape_str(username.c_str()); if ( sql_username == 0 ) { goto error_username; } sql_password = db->escape_str(password.c_str()); if ( sql_password == 0 ) { goto error_password; } // Construct the SQL statement to Insert or Replace if(replace) { oss << "REPLACE"; } else { oss << "INSERT"; } oss << " INTO " << table << " "<< db_names <<" VALUES (" << oid << "," << "'" << sql_username << "'," << "'" << sql_password << "'," << str_enabled << ")"; rc = db->exec(oss); db->free_str(sql_username); db->free_str(sql_password); return rc; error_password: db->free_str(sql_username); error_username: return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::dump(ostringstream& oss, int num, char **values, char **names) { if ((!values[OID]) || (!values[USERNAME]) || (!values[PASSWORD]) || (!values[ENABLED]) || (num != LIMIT)) { return -1; } string str_enabled = (atoi(values[ENABLED])==0)?"Fase":"True"; oss << "<USER>" << "<ID>" << values[OID] <<"</ID>" << "<NAME>" << values[USERNAME]<<"</NAME>" << "<PASSWORD>"<< values[PASSWORD]<<"</PASSWORD>"<< "<ENABLED>" << str_enabled <<"</ENABLED>" << "</USER>"; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::drop(SqlDB * db) { ostringstream oss; int rc; oss << "DELETE FROM " << table << " WHERE oid=" << oid; rc = db->exec(oss); if ( rc == 0 ) { set_valid(false); } return rc; } /* ************************************************************************** */ /* User :: Misc */ /* ************************************************************************** */ ostream& operator<<(ostream& os, User& user) { string user_str; os << user.to_xml(user_str); return os; }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string& User::to_xml(string& xml) const { ostringstream oss; int enabled_int = enabled?1:0; oss << "<USER>" "<ID>" << oid <<"</ID>" << "<NAME>" << username <<"</NAME>" << "<PASSWORD>" << password <<"</PASSWORD>" << "<ENABLED>" << enabled_int <<"</ENABLED>" << "</USER>"; xml = oss.str(); return xml; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string& User::to_str(string& str) const { ostringstream os; string enabled_str = enabled?"True":"False"; os << "ID = " << oid << endl << "NAME = " << username << endl << "PASSWORD = " << password << endl << "ENABLED = " << enabled_str; str = os.str(); return str; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::authenticate(string _password) { if (enabled && _password==password) { return oid; } else { return -1; } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int User::split_secret(const string secret, string& user, string& pass) { size_t pos; int rc = -1; pos=secret.find(":"); if (pos != string::npos) { user = secret.substr(0,pos); pass = secret.substr(pos+1); rc = 0; } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ string User::sha1_digest(const string& pass) { EVP_MD_CTX mdctx; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; ostringstream oss; EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, EVP_sha1(), NULL); EVP_DigestUpdate(&mdctx, pass.c_str(), pass.length()); EVP_DigestFinal_ex(&mdctx,md_value,&md_len); EVP_MD_CTX_cleanup(&mdctx); for(unsigned int i = 0; i<md_len; i++) { oss << setfill('0') << setw(2) << hex << nouppercase << (unsigned short) md_value[i]; } return oss.str(); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <|endoftext|>
<commit_before>#include <ecto/ecto.hpp> #include <iostream> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <pcl/io/kinect_grabber.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <boost/shared_ptr.hpp> #include <pcl/visualization/cloud_viewer.h> #include <iostream> #include <boost/thread.hpp> typedef pcl::PointCloud<pcl::PointXYZRGB> cloud_t; class SimpleKinectGrabber { public: SimpleKinectGrabber() : thread_(boost::ref(*this)) { } ~SimpleKinectGrabber() { std::cout << "Attempting to stop" << std::endl; thread_.interrupt(); thread_.join(); } void operator ()() { boost::scoped_ptr<pcl::Grabber> interface(new pcl::OpenNIGrabber()); boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind(&SimpleKinectGrabber::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback(f); interface->start(); while (!thread_.interruption_requested()) { boost::thread::yield(); } c.disconnect(); std::cerr << "Stopping" << std::endl; interface->stop(); } /** * \brief don't hang on to this cloud!! or it won't get updated. */ cloud_t::ConstPtr getLatestCloud() { boost::mutex::scoped_lock lock(mutex_); return cloud_; } void cloud_cb_(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud) { boost::mutex::scoped_lock lock(mutex_); cloud_ = cloud; } boost::mutex mutex_; cloud_t::ConstPtr cloud_; boost::thread thread_; }; struct KinectGrabber : ecto::module { void Config() { setOut<cloud_t::ConstPtr> ("out", "An rgb xyz point cloud from the kinect"); } static void Params(tendrils_t& params) { } void Process() { getOut<cloud_t::ConstPtr> ("out") = grabber_.getLatestCloud(); } SimpleKinectGrabber grabber_; }; struct CloudViewer : ecto::module { void Config() { setIn<cloud_t::ConstPtr> ("input", "The cloud to view"); setOut<bool> ("stop", "True if stop requested", false); viewer_.reset(new pcl_visualization::CloudViewer(getParam<std::string> ("window_name"))); } static void Params(tendrils_t& params) { params.set<std::string> ("window_name", "The window name", "cloud viewer"); } void Process() { if (!viewer_) return; cloud_t::ConstPtr cloud = getIn<cloud_t::ConstPtr> ("input"); if (cloud) viewer_->showCloud(*cloud); if (viewer_->wasStopped(10)) getOut<bool> ("stop") = true; } boost::shared_ptr<pcl_visualization::CloudViewer> viewer_; }; ECTO_MODULE(pcl) { // ecto::wrap<VoxelGrid>("VoxelGrid"); ecto::wrap<KinectGrabber>("KinectGrabber", "This grabs frames from the kinect!!!"); ecto::wrap<CloudViewer>("CloudViewer"); } <commit_msg>adding voxel grid.<commit_after>#include <ecto/ecto.hpp> #include <iostream> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <pcl/io/kinect_grabber.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/voxel_grid.h> #include <boost/shared_ptr.hpp> #include <pcl/visualization/cloud_viewer.h> #include <iostream> #include <boost/thread.hpp> typedef pcl::PointCloud<pcl::PointXYZRGB> cloud_t; class SimpleKinectGrabber { public: SimpleKinectGrabber() : thread_(boost::ref(*this)) { } ~SimpleKinectGrabber() { std::cout << "Attempting to stop" << std::endl; thread_.interrupt(); thread_.join(); } void operator ()() { boost::scoped_ptr<pcl::Grabber> interface(new pcl::OpenNIGrabber()); boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind(&SimpleKinectGrabber::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback(f); interface->start(); while (!thread_.interruption_requested()) { boost::thread::yield(); } c.disconnect(); std::cerr << "Stopping" << std::endl; interface->stop(); } /** * \brief don't hang on to this cloud!! or it won't get updated. */ cloud_t::ConstPtr getLatestCloud() { boost::mutex::scoped_lock lock(mutex_); cloud_t::ConstPtr p = cloud_; cloud_.reset(); return p; } void cloud_cb_(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud) { boost::mutex::scoped_lock lock(mutex_); cloud_ = cloud; } boost::mutex mutex_; cloud_t::ConstPtr cloud_; boost::thread thread_; }; struct KinectGrabber : ecto::module { void Config() { setOut<cloud_t::ConstPtr> ("out", "An rgb xyz point cloud from the kinect"); } static void Params(tendrils_t& params) { } void Process() { cloud_t::ConstPtr p; while (!p) { p = grabber_.getLatestCloud(); boost::thread::yield(); } getOut<cloud_t::ConstPtr> ("out") = p; } SimpleKinectGrabber grabber_; }; struct VoxelGrid : ecto::module { static void Params(tendrils_t& params) { params.set<float> ("leaf_size", "The size of the leaf(meters), smaller means more points...", 0.05); } void Config() { setIn<cloud_t::ConstPtr> ("in", "The cloud to filter"); setOut<cloud_t::ConstPtr> ("out", "Filtered cloud."); float leaf_size = getParam<float>("leaf_size"); voxel_grid_.setLeafSize(leaf_size,leaf_size,leaf_size); cloud_out_.reset(new cloud_t); } void Process() { cloud_t::ConstPtr cloud = getIn<cloud_t::ConstPtr> ("in"); voxel_grid_.setInputCloud(cloud); voxel_grid_.filter(*cloud_out_); getOut<cloud_t::ConstPtr>("out") = cloud_out_; } pcl::VoxelGrid<cloud_t::PointType> voxel_grid_; cloud_t::Ptr cloud_out_; }; struct CloudViewer : ecto::module { void Config() { setIn<cloud_t::ConstPtr> ("input", "The cloud to view"); setOut<bool> ("stop", "True if stop requested", false); viewer_.reset(new pcl_visualization::CloudViewer(getParam<std::string> ("window_name"))); } static void Params(tendrils_t& params) { params.set<std::string> ("window_name", "The window name", "cloud viewer"); } void Process() { if (!viewer_) return; cloud_t::ConstPtr cloud = getIn<cloud_t::ConstPtr> ("input"); if (cloud) viewer_->showCloud(*cloud); if (viewer_->wasStopped(10)) getOut<bool> ("stop") = true; } boost::shared_ptr<pcl_visualization::CloudViewer> viewer_; }; ECTO_MODULE(pcl) { ecto::wrap<VoxelGrid>("VoxelGrid"); ecto::wrap<KinectGrabber>("KinectGrabber", "This grabs frames from the kinect!!!"); ecto::wrap<CloudViewer>("CloudViewer"); } <|endoftext|>
<commit_before>/* Copyright (c) 2006, MassaRoddel, 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. */ #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_pex.hpp" namespace libtorrent { namespace { const char extension_name[] = "ut_pex"; enum { extension_index = 1, max_peer_entries = 100 }; struct ut_pex_plugin: torrent_plugin { ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {} virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc); std::vector<char>& get_ut_pex_msg() { return m_ut_pex_msg; } // the second tick of the torrent // each minute the new lists of "added" + "added.f" and "dropped" // are calculated here and the pex message is created // each peer connection will use this message // max_peer_entries limits the packet size virtual void tick() { if (++m_1_minute < 60) return; m_1_minute = 0; std::list<tcp::endpoint> cs; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { // don't send out peers that we haven't connected to // (that have connected to us) if (!i->second->is_local()) continue; // don't send out peers that we haven't successfully connected to if (i->second->connecting()) continue; cs.push_back(i->first); } std::list<tcp::endpoint> added_peers, dropped_peers; std::set_difference(cs.begin(), cs.end(), m_old_peers.begin() , m_old_peers.end(), std::back_inserter(added_peers)); std::set_difference(m_old_peers.begin(), m_old_peers.end() , cs.begin(), cs.end(), std::back_inserter(dropped_peers)); m_old_peers = cs; unsigned int num_peers = max_peer_entries; std::string pla, pld, plf; std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> pld_out(pld); std::back_insert_iterator<std::string> plf_out(plf); // TODO: use random selection in case added_peers.size() > num_peers for (std::list<tcp::endpoint>::const_iterator i = added_peers.begin() , end(added_peers.end());i != end; ++i) { if (!i->address().is_v4()) continue; detail::write_endpoint(*i, pla_out); // no supported flags to set yet // 0x01 - peer supports encryption detail::write_uint8(0, plf_out); if (--num_peers == 0) break; } num_peers = max_peer_entries; // TODO: use random selection in case dropped_peers.size() > num_peers for (std::list<tcp::endpoint>::const_iterator i = dropped_peers.begin() , end(dropped_peers.end());i != end; ++i) { if (!i->address().is_v4()) continue; detail::write_endpoint(*i, pld_out); if (--num_peers == 0) break; } entry pex(entry::dictionary_t); pex["added"] = pla; pex["dropped"] = pld; pex["added.f"] = plf; m_ut_pex_msg.clear(); bencode(std::back_inserter(m_ut_pex_msg), pex); } private: torrent& m_torrent; std::list<tcp::endpoint> m_old_peers; int m_1_minute; std::vector<char> m_ut_pex_msg; }; struct ut_pex_peer_plugin : peer_plugin { ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp) : m_torrent(t) , m_pc(pc) , m_tp(tp) , m_1_minute(0) , m_message_index(0) {} virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages[extension_name] = extension_index; } virtual bool on_extension_handshake(entry const& h) { entry const& messages = h["m"]; if (entry const* index = messages.find_key(extension_name)) { m_message_index = index->integer(); return true; } else { m_message_index = 0; return false; } } virtual bool on_extended(int length, int msg, buffer::const_interval body) { if (msg != extension_index) return false; if (m_message_index == 0) return false; if (length > 500 * 1024) throw protocol_error("ut peer exchange message larger than 500 kB"); if (body.left() < length) return true; // in case we are a seed we do not use the peers // from the pex message to prevent us from // overloading ourself if (m_torrent.is_seed()) return true; entry Pex = bdecode(body.begin, body.end); entry* PeerList = Pex.find_key("added"); if (!PeerList) return true; std::string const& peers = PeerList->string(); int num_peers = peers.length() / 6; char const* in = peers.c_str(); peer_id pid; pid.clear(); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in); if (!m_torrent.connection_for(adr)) p.peer_from_tracker(adr, pid); } return true; } // the peers second tick // every minute we send a pex message virtual void tick() { if (!m_message_index) return; // no handshake yet if (++m_1_minute <= 60) return; send_ut_peer_list(); m_1_minute = 0; } private: void send_ut_peer_list() { std::vector<char>& pex_msg = m_tp.get_ut_pex_msg(); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); assert(i.begin == i.end); m_pc.setup_send(); } torrent& m_torrent; peer_connection& m_pc; ut_pex_plugin& m_tp; int m_1_minute; int m_message_index; }; boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc) { return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent , *pc, *this)); } }} namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t) { if (t->torrent_file().priv()) { return boost::shared_ptr<torrent_plugin>(); } return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t)); } } <commit_msg>fixed typo<commit_after>/* Copyright (c) 2006, MassaRoddel, 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. */ #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_pex.hpp" namespace libtorrent { namespace { const char extension_name[] = "ut_pex"; enum { extension_index = 1, max_peer_entries = 100 }; struct ut_pex_plugin: torrent_plugin { ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {} virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc); std::vector<char>& get_ut_pex_msg() { return m_ut_pex_msg; } // the second tick of the torrent // each minute the new lists of "added" + "added.f" and "dropped" // are calculated here and the pex message is created // each peer connection will use this message // max_peer_entries limits the packet size virtual void tick() { if (++m_1_minute < 60) return; m_1_minute = 0; std::list<tcp::endpoint> cs; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { // don't send out peers that we haven't connected to // (that have connected to us) if (!i->second->is_local()) continue; // don't send out peers that we haven't successfully connected to if (i->second->is_connecting()) continue; cs.push_back(i->first); } std::list<tcp::endpoint> added_peers, dropped_peers; std::set_difference(cs.begin(), cs.end(), m_old_peers.begin() , m_old_peers.end(), std::back_inserter(added_peers)); std::set_difference(m_old_peers.begin(), m_old_peers.end() , cs.begin(), cs.end(), std::back_inserter(dropped_peers)); m_old_peers = cs; unsigned int num_peers = max_peer_entries; std::string pla, pld, plf; std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> pld_out(pld); std::back_insert_iterator<std::string> plf_out(plf); // TODO: use random selection in case added_peers.size() > num_peers for (std::list<tcp::endpoint>::const_iterator i = added_peers.begin() , end(added_peers.end());i != end; ++i) { if (!i->address().is_v4()) continue; detail::write_endpoint(*i, pla_out); // no supported flags to set yet // 0x01 - peer supports encryption detail::write_uint8(0, plf_out); if (--num_peers == 0) break; } num_peers = max_peer_entries; // TODO: use random selection in case dropped_peers.size() > num_peers for (std::list<tcp::endpoint>::const_iterator i = dropped_peers.begin() , end(dropped_peers.end());i != end; ++i) { if (!i->address().is_v4()) continue; detail::write_endpoint(*i, pld_out); if (--num_peers == 0) break; } entry pex(entry::dictionary_t); pex["added"] = pla; pex["dropped"] = pld; pex["added.f"] = plf; m_ut_pex_msg.clear(); bencode(std::back_inserter(m_ut_pex_msg), pex); } private: torrent& m_torrent; std::list<tcp::endpoint> m_old_peers; int m_1_minute; std::vector<char> m_ut_pex_msg; }; struct ut_pex_peer_plugin : peer_plugin { ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp) : m_torrent(t) , m_pc(pc) , m_tp(tp) , m_1_minute(0) , m_message_index(0) {} virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages[extension_name] = extension_index; } virtual bool on_extension_handshake(entry const& h) { entry const& messages = h["m"]; if (entry const* index = messages.find_key(extension_name)) { m_message_index = index->integer(); return true; } else { m_message_index = 0; return false; } } virtual bool on_extended(int length, int msg, buffer::const_interval body) { if (msg != extension_index) return false; if (m_message_index == 0) return false; if (length > 500 * 1024) throw protocol_error("ut peer exchange message larger than 500 kB"); if (body.left() < length) return true; // in case we are a seed we do not use the peers // from the pex message to prevent us from // overloading ourself if (m_torrent.is_seed()) return true; entry Pex = bdecode(body.begin, body.end); entry* PeerList = Pex.find_key("added"); if (!PeerList) return true; std::string const& peers = PeerList->string(); int num_peers = peers.length() / 6; char const* in = peers.c_str(); peer_id pid; pid.clear(); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in); if (!m_torrent.connection_for(adr)) p.peer_from_tracker(adr, pid); } return true; } // the peers second tick // every minute we send a pex message virtual void tick() { if (!m_message_index) return; // no handshake yet if (++m_1_minute <= 60) return; send_ut_peer_list(); m_1_minute = 0; } private: void send_ut_peer_list() { std::vector<char>& pex_msg = m_tp.get_ut_pex_msg(); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); assert(i.begin == i.end); m_pc.setup_send(); } torrent& m_torrent; peer_connection& m_pc; ut_pex_plugin& m_tp; int m_1_minute; int m_message_index; }; boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc) { return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent , *pc, *this)); } }} namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t) { if (t->torrent_file().priv()) { return boost::shared_ptr<torrent_plugin>(); } return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t)); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xipage.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:33:27 $ * * 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 SC_XIPAGE_HXX #define SC_XIPAGE_HXX #ifndef SC_XLPAGE_HXX #include "xlpage.hxx" #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif // Page settings ============================================================== /** Contains all page (print) settings for a single sheet. @descr Supports reading all related records and creating a page style sheet. */ class XclImpPageSettings : protected XclImpRoot { public: explicit XclImpPageSettings( const XclImpRoot& rRoot ); /** Returns read-only access to the page data. */ inline const XclPageData& GetPageData() const { return maData; } /** Initializes the object to be used for a new sheet. */ void Initialize(); /** Reads a SETUP record and inserts contained data. */ void ReadSetup( XclImpStream& rStrm ); /** Reads a ***MARGIN record (reads all 4 margin records). */ void ReadMargin( XclImpStream& rStrm ); /** Reads a HCENTER or VCENTER record. */ void ReadCenter( XclImpStream& rStrm ); /** Reads a HEADER or FOOTER record. */ void ReadHeaderFooter( XclImpStream& rStrm ); /** Reads a HORIZONTALPAGEBREAKS or VERTICALPAGEBREAKS record. */ void ReadPageBreaks( XclImpStream& rStrm ); /** Reads a PRINTHEADERS record. */ void ReadPrintHeaders( XclImpStream& rStrm ); /** Reads a PRINTGRIDLINES record. */ void ReadPrintGridLines( XclImpStream& rStrm ); /** Reads a BITMAP record and creates the SvxBrushItem. */ void ReadBitmap( XclImpStream& rStrm ); /** Overrides paper size and orientation (used in sheet-charts). */ void SetPaperSize( sal_uInt16 nXclPaperSize, bool bPortrait ); /** Sets or clears the fit-to-pages setting (contained in WSBOOL record). */ inline void SetFitToPages( bool bFitToPages ) { maData.mbFitToPages = bFitToPages; } /** Creates a page stylesheet from current settings and sets it at current sheet. */ void Finalize(); private: XclPageData maData; /// Page settings data. bool mbValidPaper; /// true = Paper size and orientation valid. }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.700); FILE MERGED 2008/04/01 12:36:23 thb 1.6.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:47 rt 1.6.700.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xipage.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_XIPAGE_HXX #define SC_XIPAGE_HXX #include "xlpage.hxx" #include "xiroot.hxx" // Page settings ============================================================== /** Contains all page (print) settings for a single sheet. @descr Supports reading all related records and creating a page style sheet. */ class XclImpPageSettings : protected XclImpRoot { public: explicit XclImpPageSettings( const XclImpRoot& rRoot ); /** Returns read-only access to the page data. */ inline const XclPageData& GetPageData() const { return maData; } /** Initializes the object to be used for a new sheet. */ void Initialize(); /** Reads a SETUP record and inserts contained data. */ void ReadSetup( XclImpStream& rStrm ); /** Reads a ***MARGIN record (reads all 4 margin records). */ void ReadMargin( XclImpStream& rStrm ); /** Reads a HCENTER or VCENTER record. */ void ReadCenter( XclImpStream& rStrm ); /** Reads a HEADER or FOOTER record. */ void ReadHeaderFooter( XclImpStream& rStrm ); /** Reads a HORIZONTALPAGEBREAKS or VERTICALPAGEBREAKS record. */ void ReadPageBreaks( XclImpStream& rStrm ); /** Reads a PRINTHEADERS record. */ void ReadPrintHeaders( XclImpStream& rStrm ); /** Reads a PRINTGRIDLINES record. */ void ReadPrintGridLines( XclImpStream& rStrm ); /** Reads a BITMAP record and creates the SvxBrushItem. */ void ReadBitmap( XclImpStream& rStrm ); /** Overrides paper size and orientation (used in sheet-charts). */ void SetPaperSize( sal_uInt16 nXclPaperSize, bool bPortrait ); /** Sets or clears the fit-to-pages setting (contained in WSBOOL record). */ inline void SetFitToPages( bool bFitToPages ) { maData.mbFitToPages = bFitToPages; } /** Creates a page stylesheet from current settings and sets it at current sheet. */ void Finalize(); private: XclPageData maData; /// Page settings data. bool mbValidPaper; /// true = Paper size and orientation valid. }; // ============================================================================ #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dapidata.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:44:54 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include <vcl/waitobj.hxx> #include <unotools/processfactory.hxx> #include <vos/xception.hxx> #include <com/sun/star/data/XDatabaseFavorites.hpp> #include <com/sun/star/data/XDatabaseEngine.hpp> #include <com/sun/star/data/XDatabaseWorkspace.hpp> #include <com/sun/star/data/XDatabase.hpp> #include <com/sun/star/sheet/DataImportMode.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace com::sun::star; #include "dapidata.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" #include "dpsdbtab.hxx" // ScImportSourceDesc //------------------------------------------------------------------------- #define DP_SERVICE_DBENGINE "com.sun.star.data.DatabaseEngine" // entries in the "type" ListBox #define DP_TYPELIST_TABLE 0 #define DP_TYPELIST_QUERY 1 #define DP_TYPELIST_SQL 2 #define DP_TYPELIST_SQLNAT 3 //------------------------------------------------------------------------- ScDataPilotDatabaseDlg::ScDataPilotDatabaseDlg( Window* pParent ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPIDATA ) ), // aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtDatabase ( this, ScResId( FT_DATABASE ) ), aLbDatabase ( this, ScResId( LB_DATABASE ) ), aFtObject ( this, ScResId( FT_OBJECT ) ), aCbObject ( this, ScResId( CB_OBJECT ) ), aFtType ( this, ScResId( FT_OBJTYPE ) ), aLbType ( this, ScResId( LB_OBJTYPE ) ), aGbFrame ( this, ScResId( GB_FRAME ) ) { FreeResource(); WaitObject aWait( this ); // initializing the database service the first time takes a while TRY { // get database names uno::Reference<data::XDatabaseFavorites> xFavorites( utl::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if (xFavorites.is()) { uno::Sequence<beans::PropertyValue> aFavorites = xFavorites->getFavorites(); long nCount = aFavorites.getLength(); const beans::PropertyValue* pArray = aFavorites.getConstArray(); for (long nPos = 0; nPos < nCount; nPos++) { String aName = pArray[nPos].Name; aLbDatabase.InsertEntry( aName ); } } } CATCH_ALL() { DBG_ERROR("exception in database"); } END_CATCH aLbDatabase.SelectEntryPos( 0 ); aLbType.SelectEntryPos( 0 ); FillObjects(); aLbDatabase.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); aLbType.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); } ScDataPilotDatabaseDlg::~ScDataPilotDatabaseDlg() { } void ScDataPilotDatabaseDlg::GetValues( ScImportSourceDesc& rDesc ) { USHORT nSelect = aLbType.GetSelectEntryPos(); rDesc.aDBName = aLbDatabase.GetSelectEntry(); rDesc.aObject = aCbObject.GetText(); if ( !rDesc.aDBName.Len() || !rDesc.aObject.Len() ) rDesc.nType = sheet::DataImportMode_NONE; else if ( nSelect == DP_TYPELIST_TABLE ) rDesc.nType = sheet::DataImportMode_TABLE; else if ( nSelect == DP_TYPELIST_QUERY ) rDesc.nType = sheet::DataImportMode_QUERY; else rDesc.nType = sheet::DataImportMode_SQL; rDesc.bNative = ( nSelect == DP_TYPELIST_SQLNAT ); } IMPL_LINK( ScDataPilotDatabaseDlg, SelectHdl, ListBox*, pLb ) { FillObjects(); return 0; } void ScDataPilotDatabaseDlg::FillObjects() { aCbObject.Clear(); String aDatabaseName = aLbDatabase.GetSelectEntry(); if (!aDatabaseName.Len()) return; USHORT nSelect = aLbType.GetSelectEntryPos(); if ( nSelect > DP_TYPELIST_QUERY ) return; // only tables and queries TRY { uno::Reference<data::XDatabaseEngine> xEngine( utl::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if ( !xEngine.is() ) return; // read default workspace (like in FmFormView::CreateFieldControl) uno::Reference<container::XIndexAccess> xWsps( xEngine->getWorkspaces(), uno::UNO_QUERY ); if ( !xWsps.is() ) return; uno::Any aElement( xWsps->getByIndex(0) ); uno::Reference<data::XDatabaseWorkspace> xWorkspace; aElement >>= xWorkspace; uno::Reference<data::XDatabase> xDatabase = xWorkspace->open( aDatabaseName ); uno::Reference<container::XNameAccess> xAccess; if ( nSelect == DP_TYPELIST_TABLE ) { // get all tables uno::Reference<data::XDatabaseConnection> xConnection( xDatabase, uno::UNO_QUERY ); if ( !xConnection.is() ) return; xAccess = uno::Reference<container::XNameAccess>( xConnection->getTables(), uno::UNO_QUERY ); } else { // get all queries xAccess = uno::Reference<container::XNameAccess>( xDatabase->getQueries(), uno::UNO_QUERY ); } if( !xAccess.is() ) return; // fill list uno::Sequence<rtl::OUString> aSeq = xAccess->getElementNames(); long nCount = aSeq.getLength(); const rtl::OUString* pArray = aSeq.getConstArray(); for( long nPos=0; nPos<nCount; nPos++ ) { String aName = pArray[nPos]; aCbObject.InsertEntry( aName ); } } CATCH_ALL() { // #71604# this may happen if an invalid database is selected -> no DBG_ERROR DBG_WARNING("exception in database"); } END_CATCH } <commit_msg>at uno calls, catch only uno exceptions<commit_after>/************************************************************************* * * $RCSfile: dapidata.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nn $ $Date: 2000-10-09 17:39:56 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include <vcl/waitobj.hxx> #include <unotools/processfactory.hxx> #include <com/sun/star/data/XDatabaseFavorites.hpp> #include <com/sun/star/data/XDatabaseEngine.hpp> #include <com/sun/star/data/XDatabaseWorkspace.hpp> #include <com/sun/star/data/XDatabase.hpp> #include <com/sun/star/sheet/DataImportMode.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> using namespace com::sun::star; #include "dapidata.hxx" #include "scresid.hxx" #include "sc.hrc" #include "dapitype.hrc" #include "dpsdbtab.hxx" // ScImportSourceDesc //------------------------------------------------------------------------- #define DP_SERVICE_DBENGINE "com.sun.star.data.DatabaseEngine" // entries in the "type" ListBox #define DP_TYPELIST_TABLE 0 #define DP_TYPELIST_QUERY 1 #define DP_TYPELIST_SQL 2 #define DP_TYPELIST_SQLNAT 3 //------------------------------------------------------------------------- ScDataPilotDatabaseDlg::ScDataPilotDatabaseDlg( Window* pParent ) : ModalDialog ( pParent, ScResId( RID_SCDLG_DAPIDATA ) ), // aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), aFtDatabase ( this, ScResId( FT_DATABASE ) ), aLbDatabase ( this, ScResId( LB_DATABASE ) ), aFtObject ( this, ScResId( FT_OBJECT ) ), aCbObject ( this, ScResId( CB_OBJECT ) ), aFtType ( this, ScResId( FT_OBJTYPE ) ), aLbType ( this, ScResId( LB_OBJTYPE ) ), aGbFrame ( this, ScResId( GB_FRAME ) ) { FreeResource(); WaitObject aWait( this ); // initializing the database service the first time takes a while try { // get database names uno::Reference<data::XDatabaseFavorites> xFavorites( utl::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if (xFavorites.is()) { uno::Sequence<beans::PropertyValue> aFavorites = xFavorites->getFavorites(); long nCount = aFavorites.getLength(); const beans::PropertyValue* pArray = aFavorites.getConstArray(); for (long nPos = 0; nPos < nCount; nPos++) { String aName = pArray[nPos].Name; aLbDatabase.InsertEntry( aName ); } } } catch(uno::Exception&) { DBG_ERROR("exception in database"); } aLbDatabase.SelectEntryPos( 0 ); aLbType.SelectEntryPos( 0 ); FillObjects(); aLbDatabase.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); aLbType.SetSelectHdl( LINK( this, ScDataPilotDatabaseDlg, SelectHdl ) ); } ScDataPilotDatabaseDlg::~ScDataPilotDatabaseDlg() { } void ScDataPilotDatabaseDlg::GetValues( ScImportSourceDesc& rDesc ) { USHORT nSelect = aLbType.GetSelectEntryPos(); rDesc.aDBName = aLbDatabase.GetSelectEntry(); rDesc.aObject = aCbObject.GetText(); if ( !rDesc.aDBName.Len() || !rDesc.aObject.Len() ) rDesc.nType = sheet::DataImportMode_NONE; else if ( nSelect == DP_TYPELIST_TABLE ) rDesc.nType = sheet::DataImportMode_TABLE; else if ( nSelect == DP_TYPELIST_QUERY ) rDesc.nType = sheet::DataImportMode_QUERY; else rDesc.nType = sheet::DataImportMode_SQL; rDesc.bNative = ( nSelect == DP_TYPELIST_SQLNAT ); } IMPL_LINK( ScDataPilotDatabaseDlg, SelectHdl, ListBox*, pLb ) { FillObjects(); return 0; } void ScDataPilotDatabaseDlg::FillObjects() { aCbObject.Clear(); String aDatabaseName = aLbDatabase.GetSelectEntry(); if (!aDatabaseName.Len()) return; USHORT nSelect = aLbType.GetSelectEntryPos(); if ( nSelect > DP_TYPELIST_QUERY ) return; // only tables and queries try { uno::Reference<data::XDatabaseEngine> xEngine( utl::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii( DP_SERVICE_DBENGINE ) ), uno::UNO_QUERY); if ( !xEngine.is() ) return; // read default workspace (like in FmFormView::CreateFieldControl) uno::Reference<container::XIndexAccess> xWsps( xEngine->getWorkspaces(), uno::UNO_QUERY ); if ( !xWsps.is() ) return; uno::Any aElement( xWsps->getByIndex(0) ); uno::Reference<data::XDatabaseWorkspace> xWorkspace; aElement >>= xWorkspace; uno::Reference<data::XDatabase> xDatabase = xWorkspace->open( aDatabaseName ); uno::Reference<container::XNameAccess> xAccess; if ( nSelect == DP_TYPELIST_TABLE ) { // get all tables uno::Reference<data::XDatabaseConnection> xConnection( xDatabase, uno::UNO_QUERY ); if ( !xConnection.is() ) return; xAccess = uno::Reference<container::XNameAccess>( xConnection->getTables(), uno::UNO_QUERY ); } else { // get all queries xAccess = uno::Reference<container::XNameAccess>( xDatabase->getQueries(), uno::UNO_QUERY ); } if( !xAccess.is() ) return; // fill list uno::Sequence<rtl::OUString> aSeq = xAccess->getElementNames(); long nCount = aSeq.getLength(); const rtl::OUString* pArray = aSeq.getConstArray(); for( long nPos=0; nPos<nCount; nPos++ ) { String aName = pArray[nPos]; aCbObject.InsertEntry( aName ); } } catch(uno::Exception&) { // #71604# this may happen if an invalid database is selected -> no DBG_ERROR DBG_WARNING("exception in database"); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: imoptdlg.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2006-07-21 13:24:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "imoptdlg.hxx" #include "scresid.hxx" #include "imoptdlg.hrc" #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif static const sal_Char pStrFix[] = "FIX"; //------------------------------------------------------------------------ // Der Options-String darf kein Semikolon mehr enthalten (wegen Pickliste) // darum ab Version 336 Komma stattdessen ScImportOptions::ScImportOptions( const String& rStr ) { bFixedWidth = FALSE; nFieldSepCode = 0; if ( rStr.GetTokenCount(',') >= 3 ) { String aToken( rStr.GetToken( 0, ',' ) ); if( aToken.EqualsIgnoreCaseAscii( pStrFix ) ) bFixedWidth = TRUE; else nFieldSepCode = (sal_Unicode) aToken.ToInt32(); nTextSepCode = (sal_Unicode) rStr.GetToken(1,',').ToInt32(); aStrFont = rStr.GetToken(2,','); eCharSet = ScGlobal::GetCharsetValue(aStrFont); bSaveAsShown = (rStr.GetToken( 3, ',' ).ToInt32() ? TRUE : FALSE); } } //------------------------------------------------------------------------ String ScImportOptions::BuildString() const { String aResult; if( bFixedWidth ) aResult.AppendAscii( pStrFix ); else aResult += String::CreateFromInt32(nFieldSepCode); aResult += ','; aResult += String::CreateFromInt32(nTextSepCode); aResult += ','; aResult += aStrFont; aResult += ','; aResult += String::CreateFromInt32( bSaveAsShown ? 1 : 0 ); return aResult; } //------------------------------------------------------------------------ void ScImportOptions::SetTextEncoding( rtl_TextEncoding nEnc ) { eCharSet = (nEnc == RTL_TEXTENCODING_DONTKNOW ? gsl_getSystemTextEncoding() : nEnc); aStrFont = ScGlobal::GetCharsetString( nEnc ); } <commit_msg>INTEGRATION: CWS changefileheader (1.13.492); FILE MERGED 2008/04/01 15:30:40 thb 1.13.492.2: #i85898# Stripping all external header guards 2008/03/31 17:15:14 rt 1.13.492.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: imoptdlg.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "imoptdlg.hxx" #include "scresid.hxx" #include "imoptdlg.hrc" #include <rtl/tencinfo.h> static const sal_Char pStrFix[] = "FIX"; //------------------------------------------------------------------------ // Der Options-String darf kein Semikolon mehr enthalten (wegen Pickliste) // darum ab Version 336 Komma stattdessen ScImportOptions::ScImportOptions( const String& rStr ) { bFixedWidth = FALSE; nFieldSepCode = 0; if ( rStr.GetTokenCount(',') >= 3 ) { String aToken( rStr.GetToken( 0, ',' ) ); if( aToken.EqualsIgnoreCaseAscii( pStrFix ) ) bFixedWidth = TRUE; else nFieldSepCode = (sal_Unicode) aToken.ToInt32(); nTextSepCode = (sal_Unicode) rStr.GetToken(1,',').ToInt32(); aStrFont = rStr.GetToken(2,','); eCharSet = ScGlobal::GetCharsetValue(aStrFont); bSaveAsShown = (rStr.GetToken( 3, ',' ).ToInt32() ? TRUE : FALSE); } } //------------------------------------------------------------------------ String ScImportOptions::BuildString() const { String aResult; if( bFixedWidth ) aResult.AppendAscii( pStrFix ); else aResult += String::CreateFromInt32(nFieldSepCode); aResult += ','; aResult += String::CreateFromInt32(nTextSepCode); aResult += ','; aResult += aStrFont; aResult += ','; aResult += String::CreateFromInt32( bSaveAsShown ? 1 : 0 ); return aResult; } //------------------------------------------------------------------------ void ScImportOptions::SetTextEncoding( rtl_TextEncoding nEnc ) { eCharSet = (nEnc == RTL_TEXTENCODING_DONTKNOW ? gsl_getSystemTextEncoding() : nEnc); aStrFont = ScGlobal::GetCharsetString( nEnc ); } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef NET_STREAM_HPP #define NET_STREAM_HPP #include <cstdint> #include <cstddef> #include <delegate> #include <memory> #include <vector> #include <net/socket.hpp> namespace net { class Stream; using Stream_ptr = std::unique_ptr<Stream>; /** * @brief An abstract network Stream interface based on TCP. */ class Stream { public: using buffer_t = std::shared_ptr<std::vector<uint8_t>>; using ptr = Stream_ptr; /** Construct a shared vector used by streams **/ template <typename... Args> static buffer_t construct_buffer(Args&&... args) { return std::make_shared<std::vector<uint8_t>> (std::forward<Args> (args)...); } /** Called when the stream is ready to be used. */ using ConnectCallback = delegate<void(Stream& self)>; /** * @brief Event when the stream is connected/established/ready to be used. * * @param[in] cb The connect callback */ virtual void on_connect(ConnectCallback cb) = 0; /** Called with a shared buffer and the length of the data when received. */ using ReadCallback = delegate<void(buffer_t)>; /** * @brief Event when data is received. * * @param[in] n The size of the receive buffer * @param[in] cb The read callback */ virtual void on_read(size_t n, ReadCallback cb) = 0; /** Called with nothing ¯\_(ツ)_/¯ */ using CloseCallback = delegate<void()>; /** * @brief Event for when the Stream is being closed. * * @param[in] cb The close callback */ virtual void on_close(CloseCallback cb) = 0; /** Called with the number of bytes written. */ using WriteCallback = delegate<void(size_t)>; /** * @brief Event for when data has been written. * * @param[in] cb The write callback */ virtual void on_write(WriteCallback cb) = 0; /** * @brief Async write of a data with a length. * * @param[in] buf data * @param[in] n length */ virtual void write(const void* buf, size_t n) = 0; /** * @brief Async write of a shared buffer with a length. * * @param[in] buffer shared buffer * @param[in] n length */ virtual void write(buffer_t buf) = 0; /** * @brief Async write of a string. * * @param[in] str The string */ virtual void write(const std::string& str) = 0; /** * @brief Closes the stream. */ virtual void close() = 0; /** * @brief Resets all callbacks. */ virtual void reset_callbacks() = 0; /** * @brief Returns the streams local socket. * * @return A TCP Socket */ virtual Socket local() const = 0; /** * @brief Returns the streams remote socket. * * @return A TCP Socket */ virtual Socket remote() const = 0; /** * @brief Returns a string representation of the stream. * * @return String representation of the stream. */ virtual std::string to_string() const = 0; /** * @brief Determines if connected (established). * * @return True if connected, False otherwise. */ virtual bool is_connected() const noexcept = 0; /** * @brief Determines if writable. (write is allowed) * * @return True if writable, False otherwise. */ virtual bool is_writable() const noexcept = 0; /** * @brief Determines if readable. (data can be received) * * @return True if readable, False otherwise. */ virtual bool is_readable() const noexcept = 0; /** * @brief Determines if closing. * * @return True if closing, False otherwise. */ virtual bool is_closing() const noexcept = 0; /** * @brief Determines if closed. * * @return True if closed, False otherwise. */ virtual bool is_closed() const noexcept = 0; /** * Returns the CPU id the Stream originates from **/ virtual int get_cpuid() const noexcept = 0; /** * Returns the underlying transport, or nullptr if bottom. * If no transport present, most likely its a TCP stream, in which * case you can dynamic_cast and call tcp() to get the connection **/ virtual Stream* transport() noexcept = 0; virtual size_t serialize_to(void*) const = 0; virtual ~Stream() = default; }; // < class Stream } // < namespace net #endif // < NET_STREAM_HPP <commit_msg>stream: Add transport_bottom() to get the outermost stream<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef NET_STREAM_HPP #define NET_STREAM_HPP #include <cstdint> #include <cstddef> #include <delegate> #include <memory> #include <vector> #include <net/socket.hpp> namespace net { class Stream; using Stream_ptr = std::unique_ptr<Stream>; /** * @brief An abstract network Stream interface based on TCP. */ class Stream { public: using buffer_t = std::shared_ptr<std::vector<uint8_t>>; using ptr = Stream_ptr; /** Construct a shared vector used by streams **/ template <typename... Args> static buffer_t construct_buffer(Args&&... args) { return std::make_shared<std::vector<uint8_t>> (std::forward<Args> (args)...); } /** Called when the stream is ready to be used. */ using ConnectCallback = delegate<void(Stream& self)>; /** * @brief Event when the stream is connected/established/ready to be used. * * @param[in] cb The connect callback */ virtual void on_connect(ConnectCallback cb) = 0; /** Called with a shared buffer and the length of the data when received. */ using ReadCallback = delegate<void(buffer_t)>; /** * @brief Event when data is received. * * @param[in] n The size of the receive buffer * @param[in] cb The read callback */ virtual void on_read(size_t n, ReadCallback cb) = 0; /** Called with nothing ¯\_(ツ)_/¯ */ using CloseCallback = delegate<void()>; /** * @brief Event for when the Stream is being closed. * * @param[in] cb The close callback */ virtual void on_close(CloseCallback cb) = 0; /** Called with the number of bytes written. */ using WriteCallback = delegate<void(size_t)>; /** * @brief Event for when data has been written. * * @param[in] cb The write callback */ virtual void on_write(WriteCallback cb) = 0; /** * @brief Async write of a data with a length. * * @param[in] buf data * @param[in] n length */ virtual void write(const void* buf, size_t n) = 0; /** * @brief Async write of a shared buffer with a length. * * @param[in] buffer shared buffer * @param[in] n length */ virtual void write(buffer_t buf) = 0; /** * @brief Async write of a string. * * @param[in] str The string */ virtual void write(const std::string& str) = 0; /** * @brief Closes the stream. */ virtual void close() = 0; /** * @brief Resets all callbacks. */ virtual void reset_callbacks() = 0; /** * @brief Returns the streams local socket. * * @return A TCP Socket */ virtual Socket local() const = 0; /** * @brief Returns the streams remote socket. * * @return A TCP Socket */ virtual Socket remote() const = 0; /** * @brief Returns a string representation of the stream. * * @return String representation of the stream. */ virtual std::string to_string() const = 0; /** * @brief Determines if connected (established). * * @return True if connected, False otherwise. */ virtual bool is_connected() const noexcept = 0; /** * @brief Determines if writable. (write is allowed) * * @return True if writable, False otherwise. */ virtual bool is_writable() const noexcept = 0; /** * @brief Determines if readable. (data can be received) * * @return True if readable, False otherwise. */ virtual bool is_readable() const noexcept = 0; /** * @brief Determines if closing. * * @return True if closing, False otherwise. */ virtual bool is_closing() const noexcept = 0; /** * @brief Determines if closed. * * @return True if closed, False otherwise. */ virtual bool is_closed() const noexcept = 0; /** * Returns the CPU id the Stream originates from **/ virtual int get_cpuid() const noexcept = 0; /** * Returns the underlying transport, or nullptr if bottom. * If no transport present, most likely its a TCP stream, in which * case you can dynamic_cast and call tcp() to get the connection **/ virtual Stream* transport() noexcept = 0; /** Recursively navigate to the transport stream at the bottom **/ inline Stream* bottom_transport() noexcept; virtual size_t serialize_to(void*) const = 0; virtual ~Stream() = default; }; // < class Stream inline Stream* Stream::bottom_transport() noexcept { Stream* stream = this; while (stream->transport() != nullptr) { stream = stream->transport(); } return stream; } } // < namespace net #endif // < NET_STREAM_HPP <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk. #include <hemingway/vector.hpp> namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& cs, unsigned int s) { this->size_ = s; unsigned int n = cs.size(); this->components_.resize(n, 0); for (unsigned int i = 0; i < n; i++) { this->components_[i] = cs[i]; } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& cs) { this->size_ = cs.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned int k = 0; unsigned int n = (s + c - 1) / c; this->components_.resize(n, 0); while (i < s) { // Compute the number of bits in the current chunk. unsigned int b = i + c > s ? s - i : c; for (unsigned int j = 0; j < b; j++) { this->components_[k] |= cs[i + j] << (b - j - 1); } i += b; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int i) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (i >= s) { throw std::out_of_range("Invalid index"); } // Compute the index of the target chunk. unsigned int d = i / s; // Compute the index of the first bit of the target chunk. unsigned int j = d * s; // Compute the number of bits in the target chunk. unsigned int b = j + c > s ? s - j : c; return (this->components_[d] >> (b - (i % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } return vector::distance(*this, v) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & v.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int it) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the index of the first bit of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (it >> (s - j - m)) & (((unsigned long) 1 << m) - 1); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int n = this->components_.size(); std::vector<unsigned int> c(n); for (unsigned int i = 0; i < n; i++) { c[i] = this->components_[i] & v.components_[i]; } return vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ unsigned long vector::hash() const { unsigned int n = this->components_.size(); unsigned long h = 7; for (unsigned int i = 0; i < n; i++) { h = 31 * h + this->components_[i]; } return h; } /** * Compute the distance between two vectors. * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ unsigned int vector::distance(const vector& u, const vector& v) { if (u.size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(u.components_[i] ^ v.components_[i]); } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int d) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<> components(0, 1); std::vector<bool> c(d); for (unsigned int i = 0; i < d; i++) { c[i] = components(generator); } return vector(c); } } <commit_msg>Never throw in `operator==`<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk. #include <hemingway/vector.hpp> namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& cs, unsigned int s) { this->size_ = s; unsigned int n = cs.size(); this->components_.resize(n, 0); for (unsigned int i = 0; i < n; i++) { this->components_[i] = cs[i]; } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& cs) { this->size_ = cs.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned int k = 0; unsigned int n = (s + c - 1) / c; this->components_.resize(n, 0); while (i < s) { // Compute the number of bits in the current chunk. unsigned int b = i + c > s ? s - i : c; for (unsigned int j = 0; j < b; j++) { this->components_[k] |= cs[i + j] << (b - j - 1); } i += b; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int i) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (i >= s) { throw std::out_of_range("Invalid index"); } // Compute the index of the target chunk. unsigned int d = i / s; // Compute the index of the first bit of the target chunk. unsigned int j = d * s; // Compute the number of bits in the target chunk. unsigned int b = j + c > s ? s - j : c; return (this->components_[d] >> (b - (i % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& v) const { if (this->size() != v.size()) { return false; } return vector::distance(*this, v) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & v.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int it) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the index of the first bit of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (it >> (s - j - m)) & (((unsigned long) 1 << m) - 1); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int n = this->components_.size(); std::vector<unsigned int> c(n); for (unsigned int i = 0; i < n; i++) { c[i] = this->components_[i] & v.components_[i]; } return vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ unsigned long vector::hash() const { unsigned int n = this->components_.size(); unsigned long h = 7; for (unsigned int i = 0; i < n; i++) { h = 31 * h + this->components_[i]; } return h; } /** * Compute the distance between two vectors. * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ unsigned int vector::distance(const vector& u, const vector& v) { if (u.size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(u.components_[i] ^ v.components_[i]); } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int d) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<> components(0, 1); std::vector<bool> c(d); for (unsigned int i = 0; i < d; i++) { c[i] = components(generator); } return vector(c); } } <|endoftext|>
<commit_before>// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "version.h" #include <stdlib.h> #include "util.h" using namespace std; const char* kNinjaVersion = "1.11.0.git"; void ParseVersion(const string& version, int* major, int* minor) { size_t end = version.find('.'); *major = atoi(version.substr(0, end).c_str()); *minor = 0; if (end != string::npos) { size_t start = end + 1; end = version.find('.', start); *minor = atoi(version.substr(start, end).c_str()); } } void CheckNinjaVersion(const string& version) { int bin_major, bin_minor; ParseVersion(kNinjaVersion, &bin_major, &bin_minor); int file_major, file_minor; ParseVersion(version, &file_major, &file_minor); if (bin_major > file_major) { Warning("ninja executable version (%s) greater than build file " "ninja_required_version (%s); versions may be incompatible.", kNinjaVersion, version.c_str()); return; } if ((bin_major == file_major && bin_minor < file_minor) || bin_major < file_major) { Fatal("ninja version (%s) incompatible with build file " "ninja_required_version version (%s).", kNinjaVersion, version.c_str()); } } <commit_msg>mark this 1.12.0.git<commit_after>// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "version.h" #include <stdlib.h> #include "util.h" using namespace std; const char* kNinjaVersion = "1.12.0.git"; void ParseVersion(const string& version, int* major, int* minor) { size_t end = version.find('.'); *major = atoi(version.substr(0, end).c_str()); *minor = 0; if (end != string::npos) { size_t start = end + 1; end = version.find('.', start); *minor = atoi(version.substr(start, end).c_str()); } } void CheckNinjaVersion(const string& version) { int bin_major, bin_minor; ParseVersion(kNinjaVersion, &bin_major, &bin_minor); int file_major, file_minor; ParseVersion(version, &file_major, &file_minor); if (bin_major > file_major) { Warning("ninja executable version (%s) greater than build file " "ninja_required_version (%s); versions may be incompatible.", kNinjaVersion, version.c_str()); return; } if ((bin_major == file_major && bin_minor < file_minor) || bin_major < file_major) { Fatal("ninja version (%s) incompatible with build file " "ninja_required_version version (%s).", kNinjaVersion, version.c_str()); } } <|endoftext|>
<commit_before>#include "visual.h" #include <array> #include <ctime> #include <iostream> #include <list> #include <random> #include <stdlib.h> #include <stdio.h> #include <vector> #include <AntTweakBar.h> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/polar_coordinates.hpp> #include <glm/gtx/rotate_vector.hpp> #include "camera/camera.h" #include "data/cube.h" #include "data/point.h" #include "data/triangle.h" #include "shaders/program.h" #include "shaders/shader.h" #include "textures/texture.h" #include "util/checked_call.h" static float const sPI = 3.1415926535f; static glm::ivec2 sWinSizeI(400, 400); static glm::vec2 sWinSize(static_cast<float>(sWinSizeI.x), static_cast<float>(sWinSizeI.y)); static float sScreenRatio = sWinSize.x / sWinSize.y; static bool sMouseVisible{ false }; glm::vec3 const sCubePos(0.0f, 0.0f, 0.0f); glm::vec3 sRotAngles; static size_t const sNumPoints{ 32 }; static camera sCamera(sWinSize.x, sWinSize.y); static std::vector<bool> sKeys(GLFW_KEY_LAST, false); static float sStep = 1.0f; static TwBar* sATB{ nullptr }; static void glfwErrorReporting(int errCode, char const* msg); static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers); static void mouseCallback(GLFWwindow* window, double x, double y); static void scrollCallback(GLFWwindow* window, double xDiff, double yDiff); static void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers); static void charCallback(GLFWwindow* window, unsigned int symb); static void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY); static void moveCamera(float dt); int runVisual() { CHECK(GL_FALSE != glfwInit(), "GLFW init failed", return -1;); // Provide some hints for the GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwSetErrorCallback(glfwErrorReporting); // Create a window GLFWwindow* window = glfwCreateWindow(sWinSizeI.x, sWinSizeI.y, "Renderize", nullptr, nullptr); CHECK(window, "Error creating window", { glfwTerminate(); return -1; }); glfwMakeContextCurrent(window); if (TwInit(TW_OPENGL_CORE, NULL)) { TwWindowSize(sWinSizeI.x, sWinSizeI.y); sATB = TwNewBar("Tweak"); TwAddVarRW(sATB, "step", TW_TYPE_FLOAT, &sStep, " label='Step' step=0.1 "); } else std::cerr << TwGetLastError() << std::endl; // Initialize Glew glewExperimental = GL_TRUE; GLenum glewCode = glewInit(); CHECK(GLEW_OK == glewCode, "Failed to initialize GLEW: ", std::cerr << glewGetErrorString(glewCode) << std::endl; return -1;); glViewport(0, 0, sWinSizeI.x, sWinSizeI.y); glEnable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); //glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_SRC_COLOR); // Initialize some GLFW callbacks glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, keyCallback); glfwSetCursorPosCallback(window, mouseCallback); glfwSetScrollCallback(window, scrollCallback); glfwSetMouseButtonCallback(window, mouseButtonCallback); glfwSetCharCallback(window, charCallback); glfwSetWindowSizeCallback(window, windowSizeCallback); std::mt19937 randGen(static_cast<std::mt19937::result_type>(std::time(nullptr))); std::uniform_real_distribution<float> uniDist(-1.0f, 1.0f); std::exponential_distribution<float> expDist; glm::vec3 quad[] = { glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(-1.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(1.0f, -1.0f, 0.0f) }; //auto verts = getCube(0.6f, 7); //std::vector<pointCos> pnts; //for (auto& vrt : verts) //{ // float const phi = uniDist(randGen) * 2.0f * sPI; // float const theta = (uniDist(randGen) - 0.5f) * sPI; // float const rad = 2.0f; // //glm::vec3 onSphere(rad * std::cos(phi) * std::cos(theta), rad * std::sin(phi) * std::cos(theta), rad * std::sin(theta)); // auto onSphere = glm::normalize(vrt) * 2.0f; // pnts.push_back(pointCos(vrt, vrt, onSphere)); // pnts.back().mFreq = 3.0f; // //pnts.back().mPhase = 3.14f * uniDist(randGen); //} //std::vector<glm::vec3> verts; //glm::vec3 triangle[] = { glm::vec3(-1.0f, -1.0f, 0.0f), // glm::vec3(-1.0f, 1.0f, 0.0f), // glm::vec3(1.0f, 1.0f, 0.0f) }; //verts = fill(triangle, 0.2f); std::vector<glm::vec3> verts; std::generate_n(std::back_inserter(verts), sNumPoints, [&uniDist, &randGen]() { glm::vec2 const polar(0.0f, uniDist(randGen) * glm::pi<float>()); auto const decVec = glm::euclidean(polar) * (uniDist(randGen) + 1.0f) * 0.5f; return glm::vec3(decVec.z, decVec.x, 2.1f); }); std::vector<pointFromTo> motors; for (size_t i = 0; i < verts.size(); ++i) { motors.push_back(pointFromTo(verts[i], verts[i])); } motors[0].mFinish = verts[1]; int movingI = 0; GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * verts.size(), verts.data(), GL_DYNAMIC_DRAW); GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); { glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), static_cast<GLvoid*>(0)); glEnableVertexAttribArray(0); } program prog; CHECK(prog.create(), prog.lastError(), return -1;); // Shaders shader vertexShader, fragShader; CHECK(vertexShader.compile(readAllText("shaders/cube.vert"), GL_VERTEX_SHADER), vertexShader.lastError(), return -1;); CHECK(fragShader.compile(readAllText("shaders/form.frag"), GL_FRAGMENT_SHADER), fragShader.lastError(), return -1;); prog.attach(vertexShader); prog.attach(fragShader); CHECK(prog.link(), prog.lastError(), return -1;); float lastTime = static_cast<float>(glfwGetTime()); float dt{ 0.0f }; float const dT{ 0.0125f }; // Game Loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); float const curTime = static_cast<float>(glfwGetTime()); dt = curTime - lastTime; if (dt < dT) continue; lastTime = curTime; for (size_t i = 0; i < sNumPoints; ++i) { motors[i].update(dt); } if (motors[movingI].dist() < 0.05f) { int nextI = (movingI + 1) % sNumPoints; motors[nextI].mFinish = verts[(nextI + 1) % sNumPoints]; motors[nextI].mSpeed = motors[movingI].mSpeed; movingI = (movingI + 1) % sNumPoints; } glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(verts[0]), verts.data(), GL_STATIC_DRAW); moveCamera(dt); glm::mat4 view; view = sCamera.view(); glm::mat4 projection; projection = sCamera.projection(); glm::mat4 model; model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::translate(model, sCubePos); model = glm::rotate(model, glm::radians(sRotAngles.x), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(sRotAngles.y), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(sRotAngles.z), glm::vec3(0.0f, 0.0f, 1.0f)); prog.use(); prog["zNear"] = sCamera.near(); prog["zFar"] = sCamera.far(); prog["model"] = model; prog["view"] = view; prog["projection"] = projection; prog["iResolution"] = sWinSize; prog["iGlobalTime"] = curTime; // Rendering glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glPointSize(5); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, verts.size()); glBindVertexArray(0); glDisableVertexAttribArray(0); //TwDraw(); glfwSwapBuffers(window); } TwDeleteBar(sATB); sATB = nullptr; glfwTerminate(); return 0; } void glfwErrorReporting(int errCode, char const* msg) { std::cerr << "ERROR " << errCode << ": " << msg << std::endl; } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers) { if (TwEventKeyGLFW(key, action)) return; if (action == GLFW_PRESS) sKeys[key] = true; if (action == GLFW_RELEASE) sKeys[key] = false; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); else if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_RIGHT_ALT) && action == GLFW_PRESS) { sMouseVisible = !sMouseVisible; glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); } } void mouseCallback(GLFWwindow* window, double x, double y) { float const xFloat = static_cast<GLfloat>(x); float const yFloat = static_cast<GLfloat>(y); static GLfloat lastX = xFloat, lastY = yFloat; if (sMouseVisible) { lastX = xFloat; lastY = yFloat; TwEventMousePosGLFW(static_cast<int>(x), static_cast<int>(y)); return; } GLfloat xDiff = xFloat - lastX; GLfloat yDiff = yFloat - lastY; lastX = xFloat; lastY = yFloat; GLfloat const sensitivity = 0.08f; xDiff *= sensitivity; yDiff *= sensitivity; } void scrollCallback(GLFWwindow* window, double xDiff, double yDiff) { if (TwEventMouseWheelGLFW(static_cast<int>(yDiff))) return; sCamera.fov(sCamera.fov() - static_cast<float>(yDiff)); } void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers) { TwEventMouseButtonGLFW(button, action); } void charCallback(GLFWwindow* window, unsigned int symb) { TwEventCharGLFW(symb, GLFW_PRESS); } void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY) { sWinSizeI = glm::ivec2(sizeX, sizeY); sWinSize = glm::vec2(static_cast<float>(sizeX), static_cast<float>(sizeY)); glViewport(0, 0, sWinSizeI.x, sWinSizeI.y); TwWindowSize(sWinSizeI.x, sWinSizeI.y); } void moveCamera(float dt) { if (sMouseVisible) return; float const rotAngle = 90.0f * dt; if (sKeys[GLFW_KEY_W]) sRotAngles.x -= rotAngle; if (sKeys[GLFW_KEY_S]) sRotAngles.x += rotAngle; if (sKeys[GLFW_KEY_A]) sRotAngles.y -= rotAngle; if (sKeys[GLFW_KEY_D]) sRotAngles.y += rotAngle; if (sKeys[GLFW_KEY_SPACE]) sRotAngles.z += rotAngle; if (sKeys[GLFW_KEY_LEFT_SHIFT] || sKeys[GLFW_KEY_RIGHT_SHIFT]) sRotAngles.z -= rotAngle; } <commit_msg>arranged dots in circle<commit_after>#include "visual.h" #include <array> #include <ctime> #include <iostream> #include <list> #include <random> #include <stdlib.h> #include <stdio.h> #include <vector> #include <AntTweakBar.h> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/polar_coordinates.hpp> #include <glm/gtx/rotate_vector.hpp> #include "camera/camera.h" #include "data/cube.h" #include "data/point.h" #include "data/triangle.h" #include "shaders/program.h" #include "shaders/shader.h" #include "textures/texture.h" #include "util/checked_call.h" static float const sPI = 3.1415926535f; static glm::ivec2 sWinSizeI(400, 400); static glm::vec2 sWinSize(static_cast<float>(sWinSizeI.x), static_cast<float>(sWinSizeI.y)); static float sScreenRatio = sWinSize.x / sWinSize.y; static bool sMouseVisible{ false }; glm::vec3 const sCubePos(0.0f, 0.0f, 0.0f); glm::vec3 sRotAngles; static size_t const sNumPoints{ 32 }; static camera sCamera(sWinSize.x, sWinSize.y); static std::vector<bool> sKeys(GLFW_KEY_LAST, false); static float sStep = 1.0f; static TwBar* sATB{ nullptr }; static void glfwErrorReporting(int errCode, char const* msg); static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers); static void mouseCallback(GLFWwindow* window, double x, double y); static void scrollCallback(GLFWwindow* window, double xDiff, double yDiff); static void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers); static void charCallback(GLFWwindow* window, unsigned int symb); static void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY); static void moveCamera(float dt); int runVisual() { CHECK(GL_FALSE != glfwInit(), "GLFW init failed", return -1;); // Provide some hints for the GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwSetErrorCallback(glfwErrorReporting); // Create a window GLFWwindow* window = glfwCreateWindow(sWinSizeI.x, sWinSizeI.y, "Renderize", nullptr, nullptr); CHECK(window, "Error creating window", { glfwTerminate(); return -1; }); glfwMakeContextCurrent(window); if (TwInit(TW_OPENGL_CORE, NULL)) { TwWindowSize(sWinSizeI.x, sWinSizeI.y); sATB = TwNewBar("Tweak"); TwAddVarRW(sATB, "step", TW_TYPE_FLOAT, &sStep, " label='Step' step=0.1 "); } else std::cerr << TwGetLastError() << std::endl; // Initialize Glew glewExperimental = GL_TRUE; GLenum glewCode = glewInit(); CHECK(GLEW_OK == glewCode, "Failed to initialize GLEW: ", std::cerr << glewGetErrorString(glewCode) << std::endl; return -1;); glViewport(0, 0, sWinSizeI.x, sWinSizeI.y); glEnable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); //glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_SRC_COLOR); // Initialize some GLFW callbacks glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, keyCallback); glfwSetCursorPosCallback(window, mouseCallback); glfwSetScrollCallback(window, scrollCallback); glfwSetMouseButtonCallback(window, mouseButtonCallback); glfwSetCharCallback(window, charCallback); glfwSetWindowSizeCallback(window, windowSizeCallback); std::mt19937 randGen(static_cast<std::mt19937::result_type>(std::time(nullptr))); std::uniform_real_distribution<float> uniDist(-1.0f, 1.0f); std::exponential_distribution<float> expDist; glm::vec3 quad[] = { glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(-1.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(1.0f, -1.0f, 0.0f) }; //auto verts = getCube(0.6f, 7); //std::vector<pointCos> pnts; //for (auto& vrt : verts) //{ // float const phi = uniDist(randGen) * 2.0f * sPI; // float const theta = (uniDist(randGen) - 0.5f) * sPI; // float const rad = 2.0f; // //glm::vec3 onSphere(rad * std::cos(phi) * std::cos(theta), rad * std::sin(phi) * std::cos(theta), rad * std::sin(theta)); // auto onSphere = glm::normalize(vrt) * 2.0f; // pnts.push_back(pointCos(vrt, vrt, onSphere)); // pnts.back().mFreq = 3.0f; // //pnts.back().mPhase = 3.14f * uniDist(randGen); //} //std::vector<glm::vec3> verts; //glm::vec3 triangle[] = { glm::vec3(-1.0f, -1.0f, 0.0f), // glm::vec3(-1.0f, 1.0f, 0.0f), // glm::vec3(1.0f, 1.0f, 0.0f) }; //verts = fill(triangle, 0.2f); std::vector<glm::vec3> verts; std::generate_n(std::back_inserter(verts), sNumPoints, [&uniDist, &randGen]() { glm::vec2 const polar(0.0f, uniDist(randGen) * glm::pi<float>()); auto const decVec = glm::euclidean(polar) * 0.5f;// *(uniDist(randGen) + 1.0f) * 0.5f; return glm::vec3(decVec.z, decVec.x, 2.1f); }); std::vector<pointFromTo> motors; for (size_t i = 0; i < verts.size(); ++i) { motors.push_back(pointFromTo(verts[i], verts[i])); } motors[0].mFinish = verts[1]; int movingI = 0; GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * verts.size(), verts.data(), GL_DYNAMIC_DRAW); GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); { glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), static_cast<GLvoid*>(0)); glEnableVertexAttribArray(0); } program prog; CHECK(prog.create(), prog.lastError(), return -1;); // Shaders shader vertexShader, fragShader; CHECK(vertexShader.compile(readAllText("shaders/cube.vert"), GL_VERTEX_SHADER), vertexShader.lastError(), return -1;); CHECK(fragShader.compile(readAllText("shaders/form.frag"), GL_FRAGMENT_SHADER), fragShader.lastError(), return -1;); prog.attach(vertexShader); prog.attach(fragShader); CHECK(prog.link(), prog.lastError(), return -1;); float lastTime = static_cast<float>(glfwGetTime()); float dt{ 0.0f }; float const dT{ 0.0125f }; // Game Loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); float const curTime = static_cast<float>(glfwGetTime()); dt = curTime - lastTime; if (dt < dT) continue; lastTime = curTime; for (size_t i = 0; i < sNumPoints; ++i) { motors[i].update(dt); } if (motors[movingI].dist() < 0.05f) { int nextI = (movingI + 1) % sNumPoints; motors[nextI].mFinish = verts[(nextI + 1) % sNumPoints]; motors[nextI].mSpeed = motors[movingI].mSpeed; movingI = (movingI + 1) % sNumPoints; } glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(verts[0]), verts.data(), GL_STATIC_DRAW); moveCamera(dt); glm::mat4 view; view = sCamera.view(); glm::mat4 projection; projection = sCamera.projection(); glm::mat4 model; model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::translate(model, sCubePos); model = glm::rotate(model, glm::radians(sRotAngles.x), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(sRotAngles.y), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(sRotAngles.z), glm::vec3(0.0f, 0.0f, 1.0f)); prog.use(); prog["zNear"] = sCamera.near(); prog["zFar"] = sCamera.far(); prog["model"] = model; prog["view"] = view; prog["projection"] = projection; prog["iResolution"] = sWinSize; prog["iGlobalTime"] = curTime; // Rendering glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glPointSize(5); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, verts.size()); glBindVertexArray(0); glDisableVertexAttribArray(0); //TwDraw(); glfwSwapBuffers(window); } TwDeleteBar(sATB); sATB = nullptr; glfwTerminate(); return 0; } void glfwErrorReporting(int errCode, char const* msg) { std::cerr << "ERROR " << errCode << ": " << msg << std::endl; } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers) { if (TwEventKeyGLFW(key, action)) return; if (action == GLFW_PRESS) sKeys[key] = true; if (action == GLFW_RELEASE) sKeys[key] = false; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); else if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_RIGHT_ALT) && action == GLFW_PRESS) { sMouseVisible = !sMouseVisible; glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); } } void mouseCallback(GLFWwindow* window, double x, double y) { float const xFloat = static_cast<GLfloat>(x); float const yFloat = static_cast<GLfloat>(y); static GLfloat lastX = xFloat, lastY = yFloat; if (sMouseVisible) { lastX = xFloat; lastY = yFloat; TwEventMousePosGLFW(static_cast<int>(x), static_cast<int>(y)); return; } GLfloat xDiff = xFloat - lastX; GLfloat yDiff = yFloat - lastY; lastX = xFloat; lastY = yFloat; GLfloat const sensitivity = 0.08f; xDiff *= sensitivity; yDiff *= sensitivity; } void scrollCallback(GLFWwindow* window, double xDiff, double yDiff) { if (TwEventMouseWheelGLFW(static_cast<int>(yDiff))) return; sCamera.fov(sCamera.fov() - static_cast<float>(yDiff)); } void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers) { TwEventMouseButtonGLFW(button, action); } void charCallback(GLFWwindow* window, unsigned int symb) { TwEventCharGLFW(symb, GLFW_PRESS); } void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY) { sWinSizeI = glm::ivec2(sizeX, sizeY); sWinSize = glm::vec2(static_cast<float>(sizeX), static_cast<float>(sizeY)); glViewport(0, 0, sWinSizeI.x, sWinSizeI.y); TwWindowSize(sWinSizeI.x, sWinSizeI.y); } void moveCamera(float dt) { if (sMouseVisible) return; float const rotAngle = 90.0f * dt; if (sKeys[GLFW_KEY_W]) sRotAngles.x -= rotAngle; if (sKeys[GLFW_KEY_S]) sRotAngles.x += rotAngle; if (sKeys[GLFW_KEY_A]) sRotAngles.y -= rotAngle; if (sKeys[GLFW_KEY_D]) sRotAngles.y += rotAngle; if (sKeys[GLFW_KEY_SPACE]) sRotAngles.z += rotAngle; if (sKeys[GLFW_KEY_LEFT_SHIFT] || sKeys[GLFW_KEY_RIGHT_SHIFT]) sRotAngles.z -= rotAngle; } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <sstream> #include "error_handling.h" #include "game.h" #include "coordinate.h" #include "fight.h" #include "io.h" #include "item.h" #include "level.h" #include "misc.h" #include "monster.h" #include "options.h" #include "os.h" #include "pack.h" #include "player.h" #include "rogue.h" #include "weapons.h" using namespace std; static Weapon::Type random_weapon_type() { int value = os_rand_range(100); int end = static_cast<int>(Weapon::Type::NWEAPONS); for (int i = 0; i < end; ++i) { Weapon::Type type = static_cast<Weapon::Type>(i); int probability = Weapon::probability(type); if (value < probability) { return type; } else { value -= probability; } } error("Error! Sum of probabilities is not 100%"); } Weapon* Weapon::clone() const { return new Weapon(*this); } bool Weapon::is_magic() const { return get_hit_plus() != 0 || get_damage_plus() != 0; } Weapon::~Weapon() {} Weapon::Weapon(bool random_stats) : Weapon(random_weapon_type(), random_stats) {} Weapon::Weapon(Weapon::Type subtype_, bool random_stats) : Item(), subtype(subtype_), identified(false) { o_type = WEAPON; o_which = subtype; o_count = 1; switch (subtype) { case MACE: { set_attack_damage({2,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case SWORD: { set_attack_damage({3,4}); set_throw_damage({1,2}); o_launch = NO_WEAPON; } break; case BOW: { set_attack_damage({1,1}); set_throw_damage({2,3}); o_launch = NO_WEAPON; } break; case ARROW: { set_attack_damage({0,0}); set_throw_damage({1,1}); o_launch = BOW; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case DAGGER: { set_attack_damage({1,6}); set_throw_damage({1,4}); o_launch = NO_WEAPON; o_count = os_rand_range(4) + 2; o_flags = ISMISL; } break; case TWOSWORD: { set_attack_damage({4,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case DART: { set_attack_damage({0,0}); set_throw_damage({1,3}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case SHIRAKEN: { set_attack_damage({0,0}); set_throw_damage({2,4}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case SPEAR: { set_attack_damage({2,3}); set_throw_damage({1,6}); set_armor(2); o_launch = NO_WEAPON; o_flags = ISMISL; } break; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } if (random_stats) { int rand = os_rand_range(100); if (rand < 10) { set_cursed(); modify_hit_plus(-os_rand_range(3) + 1); } else if (rand < 15) { modify_hit_plus(os_rand_range(3) + 1); } } } void Weapon::set_identified() { identified = true; } void Weapon::set_not_identified() { identified = false; } bool Weapon::is_identified() const { return identified; } string Weapon::name(Weapon::Type type) { switch (type) { case MACE: return "mace"; case SWORD: return "long sword"; case BOW: return "short bow"; case ARROW: return "arrow"; case DAGGER: return "dagger"; case TWOSWORD: return "two handed sword"; case DART: return "dart"; case SHIRAKEN: return "shuriken"; case SPEAR: return "spear"; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::probability(Weapon::Type type) { switch (type) { case MACE: return 11; case SWORD: return 11; case BOW: return 12; case ARROW: return 12; case DAGGER: return 8; case TWOSWORD: return 10; case DART: return 12; case SHIRAKEN: return 12; case SPEAR: return 12; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::worth(Weapon::Type type) { switch (type) { case MACE: return 8; case SWORD: return 15; case BOW: return 15; case ARROW: return 1; case DAGGER: return 3; case TWOSWORD: return 75; case DART: return 2; case SHIRAKEN: return 5; case SPEAR: return 5; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } string Weapon::get_description() const { stringstream buffer; string const& obj_name = Weapon::name(static_cast<Weapon::Type>(o_which)); if (o_count == 1) { buffer << "a" << vowelstr(obj_name) << " " << obj_name; } else { buffer << o_count << " " << obj_name << "s"; } int dices; int sides; if (o_type == AMMO || o_which == Weapon::BOW) { dices = get_throw_damage().dices; sides = get_throw_damage().sides; } else if (o_type == WEAPON) { dices = get_attack_damage().dices; sides = get_attack_damage().sides; } else { error("Bad item type"); } buffer << " (" << sides << "d" << dices << ")"; if (identified) { buffer << " ("; int p_hit = get_hit_plus(); if (p_hit >= 0) { buffer << "+"; } buffer << p_hit << ","; int p_dmg = get_damage_plus(); if (p_dmg >= 0) { buffer << "+"; } buffer << p_dmg << ")"; } if (get_armor() != 0) { buffer << " ["; int p_armor = get_armor(); if (p_armor >= 0) { buffer << "+"; } buffer << p_armor << "]"; } if (!get_nickname().empty()) { buffer << " called " << get_nickname(); } return buffer.str(); } void weapon_missile_fall(Item* obj, bool pr) { Coordinate fpos; if (fallpos(&obj->get_position(), &fpos)) { obj->set_position(fpos); Game::level->items.push_back(obj); return; } if (pr) { stringstream os; os << "the " << Weapon::name(static_cast<Weapon::Type>(obj->o_which)) << " vanishes as it hits the ground"; Game::io->message(os.str()); } delete obj; } <commit_msg>Stack arrows that fall on the same tile if possible<commit_after>#include <vector> #include <string> #include <sstream> #include "error_handling.h" #include "game.h" #include "coordinate.h" #include "fight.h" #include "io.h" #include "item.h" #include "level.h" #include "misc.h" #include "monster.h" #include "options.h" #include "os.h" #include "pack.h" #include "player.h" #include "rogue.h" #include "weapons.h" using namespace std; static Weapon::Type random_weapon_type() { int value = os_rand_range(100); int end = static_cast<int>(Weapon::Type::NWEAPONS); for (int i = 0; i < end; ++i) { Weapon::Type type = static_cast<Weapon::Type>(i); int probability = Weapon::probability(type); if (value < probability) { return type; } else { value -= probability; } } error("Error! Sum of probabilities is not 100%"); } Weapon* Weapon::clone() const { return new Weapon(*this); } bool Weapon::is_magic() const { return get_hit_plus() != 0 || get_damage_plus() != 0; } Weapon::~Weapon() {} Weapon::Weapon(bool random_stats) : Weapon(random_weapon_type(), random_stats) {} Weapon::Weapon(Weapon::Type subtype_, bool random_stats) : Item(), subtype(subtype_), identified(false) { o_type = WEAPON; o_which = subtype; o_count = 1; switch (subtype) { case MACE: { set_attack_damage({2,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case SWORD: { set_attack_damage({3,4}); set_throw_damage({1,2}); o_launch = NO_WEAPON; } break; case BOW: { set_attack_damage({1,1}); set_throw_damage({2,3}); o_launch = NO_WEAPON; } break; case ARROW: { set_attack_damage({0,0}); set_throw_damage({1,1}); o_launch = BOW; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case DAGGER: { set_attack_damage({1,6}); set_throw_damage({1,4}); o_launch = NO_WEAPON; o_count = os_rand_range(4) + 2; o_flags = ISMISL; } break; case TWOSWORD: { set_attack_damage({4,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case DART: { set_attack_damage({0,0}); set_throw_damage({1,3}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case SHIRAKEN: { set_attack_damage({0,0}); set_throw_damage({2,4}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = AMMO; } break; case SPEAR: { set_attack_damage({2,3}); set_throw_damage({1,6}); set_armor(2); o_launch = NO_WEAPON; o_flags = ISMISL; } break; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } if (random_stats) { int rand = os_rand_range(100); if (rand < 10) { set_cursed(); modify_hit_plus(-os_rand_range(3) + 1); } else if (rand < 15) { modify_hit_plus(os_rand_range(3) + 1); } } } void Weapon::set_identified() { identified = true; } void Weapon::set_not_identified() { identified = false; } bool Weapon::is_identified() const { return identified; } string Weapon::name(Weapon::Type type) { switch (type) { case MACE: return "mace"; case SWORD: return "long sword"; case BOW: return "short bow"; case ARROW: return "arrow"; case DAGGER: return "dagger"; case TWOSWORD: return "two handed sword"; case DART: return "dart"; case SHIRAKEN: return "shuriken"; case SPEAR: return "spear"; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::probability(Weapon::Type type) { switch (type) { case MACE: return 11; case SWORD: return 11; case BOW: return 12; case ARROW: return 12; case DAGGER: return 8; case TWOSWORD: return 10; case DART: return 12; case SHIRAKEN: return 12; case SPEAR: return 12; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::worth(Weapon::Type type) { switch (type) { case MACE: return 8; case SWORD: return 15; case BOW: return 15; case ARROW: return 1; case DAGGER: return 3; case TWOSWORD: return 75; case DART: return 2; case SHIRAKEN: return 5; case SPEAR: return 5; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } string Weapon::get_description() const { stringstream buffer; string const& obj_name = Weapon::name(static_cast<Weapon::Type>(o_which)); if (o_count == 1) { buffer << "a" << vowelstr(obj_name) << " " << obj_name; } else { buffer << o_count << " " << obj_name << "s"; } int dices; int sides; if (o_type == AMMO || o_which == Weapon::BOW) { dices = get_throw_damage().dices; sides = get_throw_damage().sides; } else if (o_type == WEAPON) { dices = get_attack_damage().dices; sides = get_attack_damage().sides; } else { error("Bad item type"); } buffer << " (" << sides << "d" << dices << ")"; if (identified) { buffer << " ("; int p_hit = get_hit_plus(); if (p_hit >= 0) { buffer << "+"; } buffer << p_hit << ","; int p_dmg = get_damage_plus(); if (p_dmg >= 0) { buffer << "+"; } buffer << p_dmg << ")"; } if (get_armor() != 0) { buffer << " ["; int p_armor = get_armor(); if (p_armor >= 0) { buffer << "+"; } buffer << p_armor << "]"; } if (!get_nickname().empty()) { buffer << " called " << get_nickname(); } return buffer.str(); } void weapon_missile_fall(Item* obj, bool pr) { Coordinate fpos; if (fallpos(&obj->get_position(), &fpos)) { obj->set_position(fpos); // See if we can stack it with something on the ground for (Item* ground_item : Game::level->items) { if (ground_item->get_position() == obj->get_position() && ground_item->o_type == obj->o_type && ground_item->o_which == obj->o_which && ground_item->get_hit_plus() == obj->get_hit_plus() && ground_item->get_damage_plus() == obj->get_damage_plus()) { ground_item->o_count++; delete obj; obj = nullptr; break; } } if (obj != nullptr) { Game::level->items.push_back(obj); } return; } if (pr) { stringstream os; os << "the " << Weapon::name(static_cast<Weapon::Type>(obj->o_which)) << " vanishes as it hits the ground"; Game::io->message(os.str()); } delete obj; } <|endoftext|>
<commit_before><commit_msg>Perception: Remove unused variables<commit_after><|endoftext|>
<commit_before>/* * (C) Copyright 2016 Mirantis 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. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <cstddef> #include <type_traits> template <class TypeT, size_t MaxSize> class static_ptr { public: typedef TypeT* pointer; private: struct Cloneable; typedef Cloneable* pointer_lcm; /* Virtual constructors for C++... */ struct Cloneable { virtual pointer clone_obj(void *, TypeT&&) = 0; virtual pointer_lcm clone_lcm(void *) = 0; }; unsigned char storage[MaxSize]; unsigned char lcm_storage[sizeof(Cloneable)]; bool is_empty = true; pointer_lcm get_lcm() noexcept { return reinterpret_cast<pointer_lcm>(lcm_storage); } public: static_ptr() { } static_ptr(static_ptr&& rhs) { if (false == rhs.is_empty) { rhs.get_lcm()->clone_obj(storage, std::move(*rhs.get())); rhs.get_lcm()->clone_lcm(lcm_storage); is_empty = false; } } static_ptr& operator=(static_ptr&& rhs) { if (false == rhs.is_empty) { rhs.lcm->clone_obj(storage, std::move(*rhs.get())); rhs.lcm->clone_lcm(lcm_storage); is_empty = false; } } /* Let's mimic the std::unique_ptr's behaviour. It's very useful to say to * the world who controls the lifetime of the contained object. */ static_ptr(const static_ptr&) = delete; static_ptr& operator=(const static_ptr&) = delete; template <class T, typename std::enable_if<std::is_base_of<TypeT, T>::value>::type* = nullptr > static_ptr(T&& t) { struct ClonableT : public Cloneable { virtual TypeT* clone_obj(void* p, TypeT&& u) override { return new (p) T(static_cast<T&&>(u)); } virtual pointer_lcm clone_lcm(void* p) override { return new (p) ClonableT; } }; new (lcm_storage) ClonableT(); get_lcm()->clone_obj(&storage, std::move(t)); is_empty = false; } ~static_ptr() { auto obj = get(); if (obj) { obj->~TypeT(); } } TypeT* operator->() { return get(); } pointer get() noexcept { return is_empty ? nullptr : reinterpret_cast<pointer>(storage); } }; <commit_msg>Add static_ptr<T, Size>::element_type.<commit_after>/* * (C) Copyright 2016 Mirantis 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. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <cstddef> #include <type_traits> template <class TypeT, size_t MaxSize> class static_ptr { public: typedef TypeT* pointer; typedef TypeT element_type; private: struct Cloneable; typedef Cloneable* pointer_lcm; /* Virtual constructors for C++... */ struct Cloneable { virtual pointer clone_obj(void *, TypeT&&) = 0; virtual pointer_lcm clone_lcm(void *) = 0; }; unsigned char storage[MaxSize]; unsigned char lcm_storage[sizeof(Cloneable)]; bool is_empty = true; pointer_lcm get_lcm() noexcept { return reinterpret_cast<pointer_lcm>(lcm_storage); } public: static_ptr() { } static_ptr(static_ptr&& rhs) { if (false == rhs.is_empty) { rhs.get_lcm()->clone_obj(storage, std::move(*rhs.get())); rhs.get_lcm()->clone_lcm(lcm_storage); is_empty = false; } } static_ptr& operator=(static_ptr&& rhs) { if (false == rhs.is_empty) { rhs.lcm->clone_obj(storage, std::move(*rhs.get())); rhs.lcm->clone_lcm(lcm_storage); is_empty = false; } } /* Let's mimic the std::unique_ptr's behaviour. It's very useful to say to * the world who controls the lifetime of the contained object. */ static_ptr(const static_ptr&) = delete; static_ptr& operator=(const static_ptr&) = delete; template <class T, typename std::enable_if<std::is_base_of<TypeT, T>::value>::type* = nullptr > static_ptr(T&& t) { struct ClonableT : public Cloneable { virtual TypeT* clone_obj(void* p, TypeT&& u) override { return new (p) T(static_cast<T&&>(u)); } virtual pointer_lcm clone_lcm(void* p) override { return new (p) ClonableT; } }; new (lcm_storage) ClonableT(); get_lcm()->clone_obj(&storage, std::move(t)); is_empty = false; } ~static_ptr() { auto obj = get(); if (obj) { obj->~TypeT(); } } TypeT* operator->() { return get(); } pointer get() noexcept { return is_empty ? nullptr : reinterpret_cast<pointer>(storage); } }; <|endoftext|>
<commit_before>/*++ Module Name: snap.cpp Abstract: Main entry point for the snap binary. Calls into the indexer, single-end aligner or paired-end aligner functions defined in other source files in this directory. Authors: Matei Zaharia & Bill Bolosky, February, 2012 Environment: User mode service. Revision History: Adapted from cSNAP, which was in turn adapted from the scala prototype --*/ #include "stdafx.h" #include "options.h" #include "FASTA.h" #include "GenomeIndex.h" #include "SingleAligner.h" #include "PairedAligner.h" #include "exit.h" #include "SeedSequencer.h" using namespace std; const char *SNAP_VERSION = "1.0beta.4"; static void usage() { fprintf(stderr, "Usage: snap <command> [<options>]\n" "Commands:\n" " index build a genome index\n" " single align single-end reads\n" " paired align paired-end reads\n" "Type a command without arguments to see its help.\n"); soft_exit(1); } int main(int argc, const char **argv) { printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION); InitializeSeedSequencers(); if (argc < 2) { usage(); } else if (strcmp(argv[1], "index") == 0) { GenomeIndex::runIndexer(argc - 2, argv + 2); } else if (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "paired") == 0) { for (int i = 1; i < argc; /* i is increased below */) { unsigned nArgsConsumed; if (strcmp(argv[i], "single") == 0) { SingleAlignerContext single; single.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed); } else if (strcmp(argv[i], "paired") == 0) { PairedAlignerContext paired; paired.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed); } else { fprintf(stderr, "Invalid command: %s\n\n", argv[i]); usage(); } _ASSERT(nArgsConsumed > 0); i += nArgsConsumed + 1; // +1 for single or paired } } else { fprintf(stderr, "Invalid command: %s\n\n", argv[1]); usage(); } } <commit_msg>1.0beta.4 merge from dev<commit_after>/*++ Module Name: snap.cpp Abstract: Main entry point for the snap binary. Calls into the indexer, single-end aligner or paired-end aligner functions defined in other source files in this directory. Authors: Matei Zaharia & Bill Bolosky, February, 2012 Environment: User mode service. Revision History: Adapted from cSNAP, which was in turn adapted from the scala prototype --*/ #include "stdafx.h" #include "options.h" #include "FASTA.h" #include "GenomeIndex.h" #include "SingleAligner.h" #include "PairedAligner.h" #include "exit.h" #include "SeedSequencer.h" using namespace std; const char *SNAP_VERSION = "1.0beta.4"; static void usage() { fprintf(stderr, "Usage: snap <command> [<options>]\n" "Commands:\n" " index build a genome index\n" " single align single-end reads\n" " paired align paired-end reads\n" "Type a command without arguments to see its help.\n"); soft_exit(1); } int main(int argc, const char **argv) { printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION); InitializeSeedSequencers(); if (argc < 2) { usage(); } else if (strcmp(argv[1], "index") == 0) { GenomeIndex::runIndexer(argc - 2, argv + 2); } else if (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "paired") == 0) { for (int i = 1; i < argc; /* i is increased below */) { unsigned nArgsConsumed; if (strcmp(argv[i], "single") == 0) { SingleAlignerContext single; single.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed); } else if (strcmp(argv[i], "paired") == 0) { PairedAlignerContext paired; paired.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed); } else { fprintf(stderr, "Invalid command: %s\n\n", argv[i]); usage(); } _ASSERT(nArgsConsumed > 0); i += nArgsConsumed + 1; // +1 for single or paired } } else { fprintf(stderr, "Invalid command: %s\n\n", argv[1]); usage(); } } <|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 "UpgradeFeature.h" #include "ApplicationFeatures/HttpEndpointProvider.h" #include "Basics/application-exit.h" #include "Cluster/ClusterFeature.h" #include "FeaturePhases/AqlFeaturePhase.h" #include "GeneralServer/AuthenticationFeature.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include "Replication/ReplicationFeature.h" #include "RestServer/BootstrapFeature.h" #include "RestServer/DatabaseFeature.h" #include "RestServer/InitDatabaseFeature.h" #include "VocBase/Methods/Upgrade.h" #include "VocBase/vocbase.h" using namespace arangodb::application_features; using namespace arangodb::basics; using namespace arangodb::options; namespace arangodb { UpgradeFeature::UpgradeFeature(application_features::ApplicationServer& server, int* result, std::vector<std::type_index> const& nonServerFeatures) : ApplicationFeature(server, "Upgrade"), _upgrade(false), _upgradeCheck(true), _result(result), _nonServerFeatures(nonServerFeatures) { setOptional(false); startsAfter<AqlFeaturePhase>(); } void UpgradeFeature::addTask(methods::Upgrade::Task&& task) { _tasks.push_back(std::move(task)); } void UpgradeFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addSection("database", "Configure the database"); options->addOldOption("upgrade", "database.auto-upgrade"); options->addOption("--database.auto-upgrade", "perform a database upgrade if necessary", new BooleanParameter(&_upgrade)); options->addOption("--database.upgrade-check", "skip a database upgrade", new BooleanParameter(&_upgradeCheck), arangodb::options::makeFlags(arangodb::options::Flags::Hidden)); } void UpgradeFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { if (_upgrade && !_upgradeCheck) { LOG_TOPIC("47698", FATAL, arangodb::Logger::FIXME) << "cannot specify both '--database.auto-upgrade true' and " "'--database.upgrade-check false'"; FATAL_ERROR_EXIT(); } if (!_upgrade) { LOG_TOPIC("ed226", TRACE, arangodb::Logger::FIXME) << "executing upgrade check: not disabling server features"; return; } LOG_TOPIC("23525", INFO, arangodb::Logger::FIXME) << "executing upgrade procedure: disabling server features"; server().forceDisableFeatures(_nonServerFeatures); std::vector<std::type_index> otherFeaturesToDisable = { std::type_index(typeid(BootstrapFeature)), std::type_index(typeid(HttpEndpointProvider)), }; server().forceDisableFeatures(otherFeaturesToDisable); ReplicationFeature& replicationFeature = server().getFeature<ReplicationFeature>(); replicationFeature.disableReplicationApplier(); DatabaseFeature& database = server().getFeature<DatabaseFeature>(); database.enableUpgrade(); ClusterFeature& cluster = server().getFeature<ClusterFeature>(); cluster.forceDisable(); ServerState::instance()->setRole(ServerState::ROLE_SINGLE); } void UpgradeFeature::prepare() { // need to register tasks before creating any database methods::Upgrade::registerTasks(*this); } void UpgradeFeature::start() { auto& init = server().getFeature<InitDatabaseFeature>(); auth::UserManager* um = server().getFeature<AuthenticationFeature>().userManager(); // upgrade the database if (_upgradeCheck) { upgradeDatabase(); if (!init.restoreAdmin() && !init.defaultPassword().empty() && um != nullptr) { um->updateUser("root", [&](auth::User& user) { user.updatePassword(init.defaultPassword()); return TRI_ERROR_NO_ERROR; }); } } // change admin user if (init.restoreAdmin() && ServerState::instance()->isSingleServerOrCoordinator()) { Result res = um->removeAllUsers(); if (res.fail()) { LOG_TOPIC("70922", ERR, arangodb::Logger::FIXME) << "failed to clear users: " << res.errorMessage(); *_result = EXIT_FAILURE; return; } VPackSlice extras = VPackSlice::noneSlice(); res = um->storeUser(true, "root", init.defaultPassword(), true, extras); if (res.fail() && res.errorNumber() == TRI_ERROR_USER_NOT_FOUND) { res = um->storeUser(false, "root", init.defaultPassword(), true, extras); } if (res.fail()) { LOG_TOPIC("e9637", ERR, arangodb::Logger::FIXME) << "failed to create root user: " << res.errorMessage(); *_result = EXIT_FAILURE; return; } auto oldLevel = arangodb::Logger::FIXME.level(); arangodb::Logger::FIXME.setLogLevel(arangodb::LogLevel::INFO); LOG_TOPIC("95cab", INFO, arangodb::Logger::FIXME) << "Password changed."; arangodb::Logger::FIXME.setLogLevel(oldLevel); *_result = EXIT_SUCCESS; } // and force shutdown if (_upgrade || init.isInitDatabase() || init.restoreAdmin()) { if (init.isInitDatabase()) { *_result = EXIT_SUCCESS; } LOG_TOPIC("7da27", INFO, arangodb::Logger::STARTUP) << "server will now shut down due to upgrade, database initialization " "or admin restoration."; server().beginShutdown(); } } void UpgradeFeature::upgradeDatabase() { LOG_TOPIC("05dff", TRACE, arangodb::Logger::FIXME) << "starting database init/upgrade"; DatabaseFeature& databaseFeature = server().getFeature<DatabaseFeature>(); bool ignoreDatafileErrors = false; { VPackBuilder options = server().options([](std::string const& name) { return (name.find("database.ignore-datafile-errors") != std::string::npos); }); VPackSlice s = options.slice(); if (s.get("database.ignore-datafile-errors").isBoolean()) { ignoreDatafileErrors = s.get("database.ignore-datafile-errors").getBool(); } } for (auto& name : databaseFeature.getDatabaseNames()) { TRI_vocbase_t* vocbase = databaseFeature.lookupDatabase(name); TRI_ASSERT(vocbase != nullptr); auto res = methods::Upgrade::startup(*vocbase, _upgrade, ignoreDatafileErrors); if (res.fail()) { char const* typeName = "initialization"; if (res.type == methods::VersionResult::UPGRADE_NEEDED) { typeName = "upgrade"; // an upgrade failed or is required if (!_upgrade) { LOG_TOPIC("1c156", ERR, arangodb::Logger::FIXME) << "Database '" << vocbase->name() << "' needs upgrade. " << "Please start the server with --database.auto-upgrade"; } } LOG_TOPIC("2eb08", FATAL, arangodb::Logger::FIXME) << "Database '" << vocbase->name() << "' " << typeName << " failed (" << res.errorMessage() << "). " << "Please inspect the logs from the " << typeName << " procedure" << " and try starting the server again."; FATAL_ERROR_EXIT(); } } if (_upgrade) { *_result = EXIT_SUCCESS; LOG_TOPIC("0de5e", INFO, arangodb::Logger::FIXME) << "database upgrade passed"; } // and return from the context LOG_TOPIC("01a03", TRACE, arangodb::Logger::FIXME) << "finished database init/upgrade"; } } // namespace arangodb <commit_msg>ARANGODB_UPGRADE_DURING_RESTORE env variable. (#10385)<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 "UpgradeFeature.h" #include "ApplicationFeatures/HttpEndpointProvider.h" #include "Basics/application-exit.h" #include "Cluster/ClusterFeature.h" #include "FeaturePhases/AqlFeaturePhase.h" #include "GeneralServer/AuthenticationFeature.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include "Replication/ReplicationFeature.h" #include "RestServer/BootstrapFeature.h" #include "RestServer/DatabaseFeature.h" #include "RestServer/InitDatabaseFeature.h" #include "VocBase/Methods/Upgrade.h" #include "VocBase/vocbase.h" using namespace arangodb::application_features; using namespace arangodb::basics; using namespace arangodb::options; namespace arangodb { UpgradeFeature::UpgradeFeature(application_features::ApplicationServer& server, int* result, std::vector<std::type_index> const& nonServerFeatures) : ApplicationFeature(server, "Upgrade"), _upgrade(false), _upgradeCheck(true), _result(result), _nonServerFeatures(nonServerFeatures) { setOptional(false); startsAfter<AqlFeaturePhase>(); } void UpgradeFeature::addTask(methods::Upgrade::Task&& task) { _tasks.push_back(std::move(task)); } void UpgradeFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addSection("database", "Configure the database"); options->addOldOption("upgrade", "database.auto-upgrade"); options->addOption("--database.auto-upgrade", "perform a database upgrade if necessary", new BooleanParameter(&_upgrade)); options->addOption("--database.upgrade-check", "skip a database upgrade", new BooleanParameter(&_upgradeCheck), arangodb::options::makeFlags(arangodb::options::Flags::Hidden)); } /// @brief This external is buried in RestServer/arangod.cpp. /// Used to perform one last action upon shutdown. extern std::function<int()> * restartAction; #ifndef _WIN32 static std::string const UPGRADE_ENV = "ARANGODB_UPGRADE_DURING_RESTORE"; static int upgradeRestart() { unsetenv(UPGRADE_ENV.c_str()); return 0; } #endif void UpgradeFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { #ifndef _WIN32 // The following environment variable is another way to run a database // upgrade. If the environment variable is set, the system does a database // upgrade and then restarts itself without the environment variable. // This is used in hotbackup if a restore to a backup happens which is from // an older database version. The restore process sets the environment // variable at runtime and then does a restore. After the restart (with // the old data) the database upgrade is run and another restart is // happening afterwards with the environment variable being cleared. char* upgrade = getenv(UPGRADE_ENV.c_str()); if (upgrade != nullptr) { _upgrade = true; restartAction = new std::function<int()>(); *restartAction = upgradeRestart; } #endif if (_upgrade && !_upgradeCheck) { LOG_TOPIC("47698", FATAL, arangodb::Logger::FIXME) << "cannot specify both '--database.auto-upgrade true' and " "'--database.upgrade-check false'"; FATAL_ERROR_EXIT(); } if (!_upgrade) { LOG_TOPIC("ed226", TRACE, arangodb::Logger::FIXME) << "executing upgrade check: not disabling server features"; return; } LOG_TOPIC("23525", INFO, arangodb::Logger::FIXME) << "executing upgrade procedure: disabling server features"; server().forceDisableFeatures(_nonServerFeatures); std::vector<std::type_index> otherFeaturesToDisable = { std::type_index(typeid(BootstrapFeature)), std::type_index(typeid(HttpEndpointProvider)), }; server().forceDisableFeatures(otherFeaturesToDisable); ReplicationFeature& replicationFeature = server().getFeature<ReplicationFeature>(); replicationFeature.disableReplicationApplier(); DatabaseFeature& database = server().getFeature<DatabaseFeature>(); database.enableUpgrade(); ClusterFeature& cluster = server().getFeature<ClusterFeature>(); cluster.forceDisable(); ServerState::instance()->setRole(ServerState::ROLE_SINGLE); } void UpgradeFeature::prepare() { // need to register tasks before creating any database methods::Upgrade::registerTasks(*this); } void UpgradeFeature::start() { auto& init = server().getFeature<InitDatabaseFeature>(); auth::UserManager* um = server().getFeature<AuthenticationFeature>().userManager(); // upgrade the database if (_upgradeCheck) { upgradeDatabase(); if (!init.restoreAdmin() && !init.defaultPassword().empty() && um != nullptr) { um->updateUser("root", [&](auth::User& user) { user.updatePassword(init.defaultPassword()); return TRI_ERROR_NO_ERROR; }); } } // change admin user if (init.restoreAdmin() && ServerState::instance()->isSingleServerOrCoordinator()) { Result res = um->removeAllUsers(); if (res.fail()) { LOG_TOPIC("70922", ERR, arangodb::Logger::FIXME) << "failed to clear users: " << res.errorMessage(); *_result = EXIT_FAILURE; return; } VPackSlice extras = VPackSlice::noneSlice(); res = um->storeUser(true, "root", init.defaultPassword(), true, extras); if (res.fail() && res.errorNumber() == TRI_ERROR_USER_NOT_FOUND) { res = um->storeUser(false, "root", init.defaultPassword(), true, extras); } if (res.fail()) { LOG_TOPIC("e9637", ERR, arangodb::Logger::FIXME) << "failed to create root user: " << res.errorMessage(); *_result = EXIT_FAILURE; return; } auto oldLevel = arangodb::Logger::FIXME.level(); arangodb::Logger::FIXME.setLogLevel(arangodb::LogLevel::INFO); LOG_TOPIC("95cab", INFO, arangodb::Logger::FIXME) << "Password changed."; arangodb::Logger::FIXME.setLogLevel(oldLevel); *_result = EXIT_SUCCESS; } // and force shutdown if (_upgrade || init.isInitDatabase() || init.restoreAdmin()) { if (init.isInitDatabase()) { *_result = EXIT_SUCCESS; } LOG_TOPIC("7da27", INFO, arangodb::Logger::STARTUP) << "server will now shut down due to upgrade, database initialization " "or admin restoration."; server().beginShutdown(); } } void UpgradeFeature::upgradeDatabase() { LOG_TOPIC("05dff", TRACE, arangodb::Logger::FIXME) << "starting database init/upgrade"; DatabaseFeature& databaseFeature = server().getFeature<DatabaseFeature>(); bool ignoreDatafileErrors = false; { VPackBuilder options = server().options([](std::string const& name) { return (name.find("database.ignore-datafile-errors") != std::string::npos); }); VPackSlice s = options.slice(); if (s.get("database.ignore-datafile-errors").isBoolean()) { ignoreDatafileErrors = s.get("database.ignore-datafile-errors").getBool(); } } for (auto& name : databaseFeature.getDatabaseNames()) { TRI_vocbase_t* vocbase = databaseFeature.lookupDatabase(name); TRI_ASSERT(vocbase != nullptr); auto res = methods::Upgrade::startup(*vocbase, _upgrade, ignoreDatafileErrors); if (res.fail()) { char const* typeName = "initialization"; if (res.type == methods::VersionResult::UPGRADE_NEEDED) { typeName = "upgrade"; // an upgrade failed or is required if (!_upgrade) { LOG_TOPIC("1c156", ERR, arangodb::Logger::FIXME) << "Database '" << vocbase->name() << "' needs upgrade. " << "Please start the server with --database.auto-upgrade"; } } LOG_TOPIC("2eb08", FATAL, arangodb::Logger::FIXME) << "Database '" << vocbase->name() << "' " << typeName << " failed (" << res.errorMessage() << "). " << "Please inspect the logs from the " << typeName << " procedure" << " and try starting the server again."; FATAL_ERROR_EXIT(); } } if (_upgrade) { *_result = EXIT_SUCCESS; LOG_TOPIC("0de5e", INFO, arangodb::Logger::FIXME) << "database upgrade passed"; } // and return from the context LOG_TOPIC("01a03", TRACE, arangodb::Logger::FIXME) << "finished database init/upgrade"; } } // namespace arangodb <|endoftext|>
<commit_before>#pragma once namespace Principia { namespace Quantities { template<int LengthExponent, int MassExponent, int TimeExponent, int CurrentExponent, int TemperatureExponent, int AmountExponent, int LuminousIntensityExponent, int WindingExponent, int AngleExponent, int SolidAngleExponent> struct Dimensions { enum { Length = LengthExponent, Mass = MassExponent, Time = TimeExponent, Current = CurrentExponent, Temperature = TemperatureExponent, Amount = AmountExponent, LuminousIntensity = LuminousIntensityExponent, Winding = WindingExponent, Angle = AngleExponent, SolidAngle = SolidAngleExponent }; }; namespace TypeGenerators { template<typename Q> struct Collapse { typedef Q ResultType; }; template<> struct Collapse<Quantity<NoDimensions>> { typedef Dimensionless ResultType; }; template<typename Left, typename Right> struct ProductGenerator { enum { Length = Left::Dimensions::Length + Right::Dimensions::Length, Mass = Left::Dimensions::Mass + Right::Dimensions::Mass, Time = Left::Dimensions::Time + Right::Dimensions::Time, Current = Left::Dimensions::Current + Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature + Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount + Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity + Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding + Right::Dimensions::Winding, Angle = Left::Dimensions::Angle + Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle + Right::Dimensions::SolidAngle }; typedef typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType ResultType; }; template<typename Left> struct ProductGenerator<Left, Dimensionless> { typedef Left ResultType; }; template<typename Right> struct ProductGenerator<Dimensionless, Right> { typedef Right ResultType; }; template<> struct ProductGenerator<Dimensionless, Dimensionless> { typedef Dimensionless ResultType; }; template<typename Left, typename Right> struct QuotientGenerator { enum { Length = Left::Dimensions::Length - Right::Dimensions::Length, Mass = Left::Dimensions::Mass - Right::Dimensions::Mass, Time = Left::Dimensions::Time - Right::Dimensions::Time, Current = Left::Dimensions::Current - Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature - Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount - Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity - Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding - Right::Dimensions::Winding, Angle = Left::Dimensions::Angle - Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle - Right::Dimensions::SolidAngle }; typedef typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType ResultType; }; template<typename Left> struct QuotientGenerator<Left, Dimensionless> { typedef Left ResultType; }; template<> struct QuotientGenerator<Dimensionless, Dimensionless> { typedef Dimensionless ResultType; }; template<typename Right> struct QuotientGenerator<Dimensionless, Right> { enum { Length = -Right::Dimensions::Length, Mass = -Right::Dimensions::Mass, Time = -Right::Dimensions::Time, Current = -Right::Dimensions::Current, Temperature = -Right::Dimensions::Temperature, Amount = -Right::Dimensions::Amount, LuminousIntensity = -Right::Dimensions::LuminousIntensity, Winding = -Right::Dimensions::Winding, Angle = -Right::Dimensions::Angle, SolidAngle = -Right::Dimensions::SolidAngle }; typedef Quantity< Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>> ResultType; }; template<typename Q, int Exponent, typename> struct PowerGenerator {}; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent > 1)>> { typedef Product< typename PowerGenerator<Q, Exponent - 1>::ResultType, Q> ResultType; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent < 1)>>{ typedef Quotient< typename PowerGenerator<Q, Exponent + 1>::ResultType, Q> ResultType; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent == 1)>>{ typedef Q ResultType; }; } namespace Factories { inline Length Metres(Dimensionless const& number) { return Length(number); } inline Mass Kilograms(Dimensionless const& number) { return Mass(number); } inline Time Seconds(Dimensionless const& number) { return Time(number); } inline Current Amperes(Dimensionless const& number) { return Current(number); } inline Temperature Kelvins(Dimensionless const& number) { return Temperature(number); } inline Amount Moles(Dimensionless const& number) { return Amount(number); } inline LuminousIntensity Candelas(Dimensionless const& number) { return LuminousIntensity(number); } inline Winding Cycles(Dimensionless const& number) { return Winding(number); } inline Angle Radians(Dimensionless const& number) { return Angle(number); } inline SolidAngle Steradians(Dimensionless const& number) { return SolidAngle(number); } } template<typename D> template<int Exponent> Exponentiation<Quantity<D>, Exponent> Quantity<D>::Pow() const { return Exponentiation<Quantity<D>, Exponent>(magnitude_.Pow(Exponent)); } template<typename D> inline Quantity<D>::Quantity(Dimensionless const& magnitude) : magnitude_(magnitude) {} #pragma region Additive group template<typename D> inline Quantity<D> operator+(Quantity<D> const& right) { return Quantity<D>(+right.magnitude_); } template<typename D> inline Quantity<D> operator-(Quantity<D> const& right) { return Quantity<D>(-right.magnitude_); } template<typename D> inline Quantity<D> operator+(Quantity<D> const& left, Quantity<D> const& right) { return Quantity<D>(left.magnitude_ + right.magnitude_); } template<typename D> inline Quantity<D> operator-(Quantity<D> const& left, Quantity<D> const& right) { return Quantity<D>(left.magnitude_ - right.magnitude_); } #pragma endregion #pragma region Multiplicative group template<typename DLeft, typename DRight> inline Product <typename Quantity<DLeft>, typename Quantity <DRight>> operator*(Quantity<DLeft> const& left, Quantity<DRight> const& right) { return Product<typename Quantity<DLeft>, typename Quantity<DRight>>(left.magnitude_ * right.magnitude_); } template<typename DLeft, typename DRight> inline Quotient<typename Quantity<DLeft>, typename Quantity <DRight>> operator/(Quantity<DLeft> const& left, Quantity<DRight> const& right) { return Quotient<typename Quantity<DLeft>, typename Quantity<DRight>>(left.magnitude_ / right.magnitude_); } template<typename D> inline Quantity<D> operator*(Quantity<D> const& left, Dimensionless const& right) { return Quantity<D>(left.magnitude_ * right); } template<typename D> inline Quantity<D> operator*(Dimensionless const& left, Quantity<D> const& right) { return Quantity<D>(left * right.magnitude_); } template<typename D> inline Quantity<D> operator/(Quantity<D> const& left, Dimensionless const& right) { return Quantity<D>(left.magnitude_ / right); } template<typename D> inline Inverse<Quantity<D>> operator/(Dimensionless const& left, Quantity<D> const& right) { return Inverse<Quantity<D>>(left / right.magnitude_); } #pragma endregion #pragma region Assigment operators template<typename D> inline void operator+=(Quantity<D>& left, Quantity<D> const& right) { left = left + right; } template<typename D> inline void operator-=(Quantity<D>& left, Quantity<D> const& right) { left = left - right; } template<typename D> inline void operator*=(Quantity<D>& left, Dimensionless const& right) { left = left * right; } template<typename D> inline void operator/=(Quantity<D>& left, Dimensionless const& right) { left = left / right; } #pragma endregion #pragma region Comparison operators template<typename D> inline bool operator>(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ > right.magnitude_; } template<typename D> inline bool operator<(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ < right.magnitude_; } template<typename D> inline bool operator>=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ >= right.magnitude_; } template<typename D> inline bool operator<=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ <= right.magnitude_; } template<typename D> inline bool operator==(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ == right.magnitude_; } template<typename D> inline bool operator!=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ != right.magnitude_; } #pragma endregion template<typename D> inline Quantity<D> Abs(Quantity<D> const& quantity) { return Quantity<D>(Abs(quantity.magnitude_)); } template<typename D> inline std::wstring ToString(Quantity<D> const& quantity, unsigned char const precision) { return ToString(quantity.magnitude_, precision) + (D::Length != 0 ? L" m^" + std::to_wstring(D::Length) : L"") + (D::Mass != 0 ? L" kg^" + std::to_wstring(D::Mass) : L"") + (D::Time != 0 ? L" s^" + std::to_wstring(D::Time) : L"") + (D::Current != 0 ? L" A^" + std::to_wstring(D::Current) : L"") + (D::Temperature != 0 ? L" K^" + std::to_wstring(D::Temperature) : L"") + (D::Amount != 0 ? L" mol^" + std::to_wstring(D::Amount) : L"") + (D::LuminousIntensity != 0 ? L" cd^" + std::to_wstring(D::LuminousIntensity) : L"") + (D::Winding != 0 ? L" cycle^" + std::to_wstring(D::Winding) : L"") + (D::Angle != 0 ? L" rad^" + std::to_wstring(D::Angle) : L"") + (D::SolidAngle != 0 ? L" sr^" + std::to_wstring(D::SolidAngle) : L""); } } } <commit_msg>No whitespace at end of line.<commit_after>#pragma once namespace Principia { namespace Quantities { template<int LengthExponent, int MassExponent, int TimeExponent, int CurrentExponent, int TemperatureExponent, int AmountExponent, int LuminousIntensityExponent, int WindingExponent, int AngleExponent, int SolidAngleExponent> struct Dimensions { enum { Length = LengthExponent, Mass = MassExponent, Time = TimeExponent, Current = CurrentExponent, Temperature = TemperatureExponent, Amount = AmountExponent, LuminousIntensity = LuminousIntensityExponent, Winding = WindingExponent, Angle = AngleExponent, SolidAngle = SolidAngleExponent }; }; namespace TypeGenerators { template<typename Q> struct Collapse { typedef Q ResultType; }; template<> struct Collapse<Quantity<NoDimensions>> { typedef Dimensionless ResultType; }; template<typename Left, typename Right> struct ProductGenerator { enum { Length = Left::Dimensions::Length + Right::Dimensions::Length, Mass = Left::Dimensions::Mass + Right::Dimensions::Mass, Time = Left::Dimensions::Time + Right::Dimensions::Time, Current = Left::Dimensions::Current + Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature + Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount + Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity + Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding + Right::Dimensions::Winding, Angle = Left::Dimensions::Angle + Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle + Right::Dimensions::SolidAngle }; typedef typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType ResultType; }; template<typename Left> struct ProductGenerator<Left, Dimensionless> { typedef Left ResultType; }; template<typename Right> struct ProductGenerator<Dimensionless, Right> { typedef Right ResultType; }; template<> struct ProductGenerator<Dimensionless, Dimensionless> { typedef Dimensionless ResultType; }; template<typename Left, typename Right> struct QuotientGenerator { enum { Length = Left::Dimensions::Length - Right::Dimensions::Length, Mass = Left::Dimensions::Mass - Right::Dimensions::Mass, Time = Left::Dimensions::Time - Right::Dimensions::Time, Current = Left::Dimensions::Current - Right::Dimensions::Current, Temperature = Left::Dimensions::Temperature - Right::Dimensions::Temperature, Amount = Left::Dimensions::Amount - Right::Dimensions::Amount, LuminousIntensity = Left::Dimensions::LuminousIntensity - Right:: Dimensions::LuminousIntensity, Winding = Left::Dimensions::Winding - Right::Dimensions::Winding, Angle = Left::Dimensions::Angle - Right::Dimensions::Angle, SolidAngle = Left::Dimensions::SolidAngle - Right::Dimensions::SolidAngle }; typedef typename Collapse< Quantity<Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>>>::ResultType ResultType; }; template<typename Left> struct QuotientGenerator<Left, Dimensionless> { typedef Left ResultType; }; template<> struct QuotientGenerator<Dimensionless, Dimensionless> { typedef Dimensionless ResultType; }; template<typename Right> struct QuotientGenerator<Dimensionless, Right> { enum { Length = -Right::Dimensions::Length, Mass = -Right::Dimensions::Mass, Time = -Right::Dimensions::Time, Current = -Right::Dimensions::Current, Temperature = -Right::Dimensions::Temperature, Amount = -Right::Dimensions::Amount, LuminousIntensity = -Right::Dimensions::LuminousIntensity, Winding = -Right::Dimensions::Winding, Angle = -Right::Dimensions::Angle, SolidAngle = -Right::Dimensions::SolidAngle }; typedef Quantity< Dimensions<Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity, Winding, Angle, SolidAngle>> ResultType; }; template<typename Q, int Exponent, typename> struct PowerGenerator {}; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent > 1)>> { typedef Product< typename PowerGenerator<Q, Exponent - 1>::ResultType, Q> ResultType; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent < 1)>>{ typedef Quotient< typename PowerGenerator<Q, Exponent + 1>::ResultType, Q> ResultType; }; template<typename Q, int Exponent> struct PowerGenerator<Q, Exponent, Range<(Exponent == 1)>>{ typedef Q ResultType; }; } namespace Factories { inline Length Metres(Dimensionless const& number) { return Length(number); } inline Mass Kilograms(Dimensionless const& number) { return Mass(number); } inline Time Seconds(Dimensionless const& number) { return Time(number); } inline Current Amperes(Dimensionless const& number) { return Current(number); } inline Temperature Kelvins(Dimensionless const& number) { return Temperature(number); } inline Amount Moles(Dimensionless const& number) { return Amount(number); } inline LuminousIntensity Candelas(Dimensionless const& number) { return LuminousIntensity(number); } inline Winding Cycles(Dimensionless const& number) { return Winding(number); } inline Angle Radians(Dimensionless const& number) { return Angle(number); } inline SolidAngle Steradians(Dimensionless const& number) { return SolidAngle(number); } } template<typename D> template<int Exponent> Exponentiation<Quantity<D>, Exponent> Quantity<D>::Pow() const { return Exponentiation<Quantity<D>, Exponent>(magnitude_.Pow(Exponent)); } template<typename D> inline Quantity<D>::Quantity(Dimensionless const& magnitude) : magnitude_(magnitude) {} #pragma region Additive group template<typename D> inline Quantity<D> operator+(Quantity<D> const& right) { return Quantity<D>(+right.magnitude_); } template<typename D> inline Quantity<D> operator-(Quantity<D> const& right) { return Quantity<D>(-right.magnitude_); } template<typename D> inline Quantity<D> operator+(Quantity<D> const& left, Quantity<D> const& right) { return Quantity<D>(left.magnitude_ + right.magnitude_); } template<typename D> inline Quantity<D> operator-(Quantity<D> const& left, Quantity<D> const& right) { return Quantity<D>(left.magnitude_ - right.magnitude_); } #pragma endregion #pragma region Multiplicative group template<typename DLeft, typename DRight> inline Product <typename Quantity<DLeft>, typename Quantity <DRight>> operator*(Quantity<DLeft> const& left, Quantity<DRight> const& right) { return Product<typename Quantity<DLeft>, typename Quantity<DRight>>(left.magnitude_ * right.magnitude_); } template<typename DLeft, typename DRight> inline Quotient<typename Quantity<DLeft>, typename Quantity <DRight>> operator/(Quantity<DLeft> const& left, Quantity<DRight> const& right) { return Quotient<typename Quantity<DLeft>, typename Quantity<DRight>>(left.magnitude_ / right.magnitude_); } template<typename D> inline Quantity<D> operator*(Quantity<D> const& left, Dimensionless const& right) { return Quantity<D>(left.magnitude_ * right); } template<typename D> inline Quantity<D> operator*(Dimensionless const& left, Quantity<D> const& right) { return Quantity<D>(left * right.magnitude_); } template<typename D> inline Quantity<D> operator/(Quantity<D> const& left, Dimensionless const& right) { return Quantity<D>(left.magnitude_ / right); } template<typename D> inline Inverse<Quantity<D>> operator/(Dimensionless const& left, Quantity<D> const& right) { return Inverse<Quantity<D>>(left / right.magnitude_); } #pragma endregion #pragma region Assigment operators template<typename D> inline void operator+=(Quantity<D>& left, Quantity<D> const& right) { left = left + right; } template<typename D> inline void operator-=(Quantity<D>& left, Quantity<D> const& right) { left = left - right; } template<typename D> inline void operator*=(Quantity<D>& left, Dimensionless const& right) { left = left * right; } template<typename D> inline void operator/=(Quantity<D>& left, Dimensionless const& right) { left = left / right; } #pragma endregion #pragma region Comparison operators template<typename D> inline bool operator>(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ > right.magnitude_; } template<typename D> inline bool operator<(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ < right.magnitude_; } template<typename D> inline bool operator>=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ >= right.magnitude_; } template<typename D> inline bool operator<=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ <= right.magnitude_; } template<typename D> inline bool operator==(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ == right.magnitude_; } template<typename D> inline bool operator!=(Quantity<D> const& left, Quantity<D> const& right) { return left.magnitude_ != right.magnitude_; } #pragma endregion template<typename D> inline Quantity<D> Abs(Quantity<D> const& quantity) { return Quantity<D>(Abs(quantity.magnitude_)); } template<typename D> inline std::wstring ToString(Quantity<D> const& quantity, unsigned char const precision) { return ToString(quantity.magnitude_, precision) + (D::Length != 0 ? L" m^" + std::to_wstring(D::Length) : L"") + (D::Mass != 0 ? L" kg^" + std::to_wstring(D::Mass) : L"") + (D::Time != 0 ? L" s^" + std::to_wstring(D::Time) : L"") + (D::Current != 0 ? L" A^" + std::to_wstring(D::Current) : L"") + (D::Temperature != 0 ? L" K^" + std::to_wstring(D::Temperature) : L"") + (D::Amount != 0 ? L" mol^" + std::to_wstring(D::Amount) : L"") + (D::LuminousIntensity != 0 ? L" cd^" + std::to_wstring(D::LuminousIntensity) : L"") + (D::Winding != 0 ? L" cycle^" + std::to_wstring(D::Winding) : L"") + (D::Angle != 0 ? L" rad^" + std::to_wstring(D::Angle) : L"") + (D::SolidAngle != 0 ? L" sr^" + std::to_wstring(D::SolidAngle) : L""); } } } <|endoftext|>
<commit_before>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/extensions/tab_helper.h" #include <map> #include <utility> #include "atom/browser/extensions/atom_extension_api_frame_id_map_helper.h" #include "atom/browser/extensions/atom_extension_web_contents_observer.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/component_extension_resource_manager.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/file_reader.h" #include "extensions/common/extension_messages.h" #include "native_mate/arguments.h" #include "native_mate/dictionary.h" #include "net/base/filename_util.h" #include "ui/base/resource/resource_bundle.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(extensions::TabHelper); namespace keys { const char kIdKey[] = "id"; const char kActiveKey[] = "active"; const char kIncognitoKey[] = "incognito"; const char kWindowIdKey[] = "windowId"; const char kTitleKey[] = "title"; const char kUrlKey[] = "url"; const char kStatusKey[] = "status"; const char kAudibleKey[] = "audible"; const char kDiscardedKey[] = "discarded"; const char kAutoDiscardableKey[] = "autoDiscardable"; const char kHighlightedKey[] = "highlighted"; const char kIndexKey[] = "index"; const char kPinnedKey[] = "pinned"; const char kSelectedKey[] = "selected"; } // namespace keys static std::map<int, std::pair<int, int>> render_view_map_; static std::map<int, int> active_tab_map_; static int32_t next_id = 1; namespace extensions { TabHelper::TabHelper(content::WebContents* contents) : content::WebContentsObserver(contents), values_(new base::DictionaryValue), script_executor_( new ScriptExecutor(contents, &script_execution_observers_)) { session_id_ = next_id++; RenderViewCreated(contents->GetRenderViewHost()); contents->ForEachFrame( base::Bind(&TabHelper::SetTabId, base::Unretained(this))); AtomExtensionWebContentsObserver::CreateForWebContents(contents); } TabHelper::~TabHelper() { } void TabHelper::SetWindowId(const int32_t& id) { window_id_ = id; // Extension code in the renderer holds the ID of the window that hosts it. // Notify it that the window ID changed. web_contents()->SendToAllFrames( new ExtensionMsg_UpdateBrowserWindowId(MSG_ROUTING_NONE, window_id_)); } void TabHelper::SetActive(bool active) { if (active) active_tab_map_[window_id_] = session_id_; else if (active_tab_map_[window_id_] == session_id_) active_tab_map_[window_id_] = -1; } void TabHelper::SetTabIndex(int index) { index_ = index; } void TabHelper::SetTabValues(const base::DictionaryValue& values) { values_->MergeDictionary(&values); } void TabHelper::RenderViewCreated(content::RenderViewHost* render_view_host) { render_view_map_[session_id_] = std::make_pair( render_view_host->GetProcess()->GetID(), render_view_host->GetRoutingID()); } void TabHelper::RenderFrameCreated(content::RenderFrameHost* host) { SetTabId(host); } void TabHelper::WebContentsDestroyed() { render_view_map_.erase(session_id_); } void TabHelper::SetTabId(content::RenderFrameHost* render_frame_host) { render_frame_host->Send( new ExtensionMsg_SetTabId(render_frame_host->GetRoutingID(), session_id_)); } void TabHelper::DidCloneToNewWebContents( content::WebContents* old_web_contents, content::WebContents* new_web_contents) { // When the WebContents that this is attached to is cloned, // give the new clone a TabHelper and copy state over. CreateForWebContents(new_web_contents); } bool TabHelper::ExecuteScriptInTab(mate::Arguments* args) { std::string extension_id; if (!args->GetNext(&extension_id)) { args->ThrowError("extensionId is a required field"); return false; } std::string code_string; if (!args->GetNext(&code_string)) { args->ThrowError("codeString is a required field"); return false; } base::DictionaryValue options; if (!args->GetNext(&options)) { args->ThrowError("options is a required field"); return false; } extensions::ScriptExecutor::ResultType result; extensions::ScriptExecutor::ExecuteScriptCallback callback; if (!args->GetNext(&callback)) { callback = extensions::ScriptExecutor::ExecuteScriptCallback(); result = extensions::ScriptExecutor::NO_RESULT; } else { result = extensions::ScriptExecutor::JSON_SERIALIZED_RESULT; } extensions::ScriptExecutor* executor = script_executor(); if (!executor) return false; std::string file; GURL file_url; options.GetString("file", &file); std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy(); if (!file.empty()) { ExtensionRegistry* registry = ExtensionRegistry::Get(web_contents()->GetBrowserContext()); if (!registry) return false; const Extension* extension = registry->enabled_extensions().GetByID(extension_id); if (!extension) return false; ExtensionResource resource = extension->GetResource(file); if (resource.extension_root().empty() || resource.relative_path().empty()) { return false; } file_url = net::FilePathToFileURL(resource.GetFilePath()); int resource_id; const ComponentExtensionResourceManager* component_extension_resource_manager = ExtensionsBrowserClient::Get() ->GetComponentExtensionResourceManager(); if (component_extension_resource_manager && component_extension_resource_manager->IsComponentExtensionResource( resource.extension_root(), resource.relative_path(), &resource_id)) { const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); file = rb.GetRawDataResource(resource_id).as_string(); } else { scoped_refptr<FileReader> file_reader(new FileReader( resource, base::Bind(&TabHelper::ExecuteScript, base::Unretained(this), extension_id, base::Passed(&copy), result, callback, file_url))); file_reader->Start(); return true; } } ExecuteScript(extension_id, std::move(copy), result, callback, file_url, true, base::MakeUnique<std::string>(file.empty() ? code_string : file)); return true; } void TabHelper::ExecuteScript( const std::string extension_id, std::unique_ptr<base::DictionaryValue> options, extensions::ScriptExecutor::ResultType result, extensions::ScriptExecutor::ExecuteScriptCallback callback, const GURL& file_url, bool success, std::unique_ptr<std::string> code_string) { extensions::ScriptExecutor* executor = script_executor(); bool all_frames = false; options->GetBoolean("allFrames", &all_frames); extensions::ScriptExecutor::FrameScope frame_scope = all_frames ? extensions::ScriptExecutor::INCLUDE_SUB_FRAMES : extensions::ScriptExecutor::SINGLE_FRAME; int frame_id = extensions::ExtensionApiFrameIdMap::kTopFrameId; options->GetInteger("frameId", &frame_id); bool match_about_blank = false; options->GetBoolean("matchAboutBlank", &match_about_blank); bool main_world = false; options->GetBoolean("mainWorld", &main_world); extensions::UserScript::RunLocation run_at = extensions::UserScript::UNDEFINED; std::string run_at_string = "undefined"; options->GetString("runAt", &run_at_string); if (run_at_string == "document_start") { run_at = extensions::UserScript::DOCUMENT_START; } else if (run_at_string == "document_end") { run_at = extensions::UserScript::DOCUMENT_END; } else if (run_at_string == "document_idle") { run_at = extensions::UserScript::DOCUMENT_IDLE; } executor->ExecuteScript( HostID(HostID::EXTENSIONS, extension_id), extensions::ScriptExecutor::JAVASCRIPT, *code_string, frame_scope, frame_id, match_about_blank ? extensions::ScriptExecutor::MATCH_ABOUT_BLANK : extensions::ScriptExecutor::DONT_MATCH_ABOUT_BLANK, run_at, main_world ? extensions::ScriptExecutor::MAIN_WORLD : extensions::ScriptExecutor::ISOLATED_WORLD, extensions::ScriptExecutor::DEFAULT_PROCESS, GURL(), // No webview src. file_url, // No file url. false, // user gesture result, callback); } // static content::WebContents* TabHelper::GetTabById(int32_t tab_id) { content::RenderViewHost* rvh = content::RenderViewHost::FromID(render_view_map_[tab_id].first, render_view_map_[tab_id].second); if (rvh) { return content::WebContents::FromRenderViewHost(rvh); } else { return NULL; } } // static content::WebContents* TabHelper::GetTabById(int32_t tab_id, content::BrowserContext* browser_context) { auto contents = GetTabById(tab_id); if (contents) { if (extensions::ExtensionsBrowserClient::Get()->IsSameContext( browser_context, contents->GetBrowserContext())) { if (tab_id == extensions::TabHelper::IdForTab(contents)) return contents; } } return NULL; } // static base::DictionaryValue* TabHelper::CreateTabValue( content::WebContents* contents) { auto tab_id = IdForTab(contents); auto window_id = IdForWindowContainingTab(contents); auto tab_helper = TabHelper::FromWebContents(contents); bool active = (active_tab_map_[window_id] == tab_id); std::unique_ptr<base::DictionaryValue> result( tab_helper->getTabValues()->CreateDeepCopy()); result->SetInteger(keys::kIdKey, tab_id); result->SetInteger(keys::kWindowIdKey, window_id); result->SetBoolean(keys::kIncognitoKey, contents->GetBrowserContext()->IsOffTheRecord()); result->SetBoolean(keys::kActiveKey, active); result->SetString(keys::kUrlKey, contents->GetURL().spec()); result->SetString(keys::kTitleKey, contents->GetTitle()); result->SetString(keys::kStatusKey, contents->IsLoading() ? "loading" : "complete"); result->SetBoolean(keys::kAudibleKey, contents->WasRecentlyAudible()); result->SetBoolean(keys::kDiscardedKey, false); result->SetBoolean(keys::kAutoDiscardableKey, false); result->SetBoolean(keys::kHighlightedKey, active); if (tab_helper->index_ != -1) result->SetInteger(keys::kIndexKey, tab_helper->index_); // TODO(bridiver) - set pinned value result->SetBoolean(keys::kPinnedKey, false); result->SetBoolean(keys::kSelectedKey, active); return result.release(); } // static int32_t TabHelper::IdForTab(const content::WebContents* tab) { const TabHelper* session_tab_helper = tab ? TabHelper::FromWebContents(tab) : NULL; return session_tab_helper ? session_tab_helper->session_id_ : -1; } // static int32_t TabHelper::IdForWindowContainingTab( const content::WebContents* tab) { const TabHelper* session_tab_helper = tab ? TabHelper::FromWebContents(tab) : NULL; return session_tab_helper ? session_tab_helper->window_id_ : -1; } } // namespace extensions <commit_msg>Always emit a tabIndex even for -1<commit_after>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/extensions/tab_helper.h" #include <map> #include <utility> #include "atom/browser/extensions/atom_extension_api_frame_id_map_helper.h" #include "atom/browser/extensions/atom_extension_web_contents_observer.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/component_extension_resource_manager.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/file_reader.h" #include "extensions/common/extension_messages.h" #include "native_mate/arguments.h" #include "native_mate/dictionary.h" #include "net/base/filename_util.h" #include "ui/base/resource/resource_bundle.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(extensions::TabHelper); namespace keys { const char kIdKey[] = "id"; const char kActiveKey[] = "active"; const char kIncognitoKey[] = "incognito"; const char kWindowIdKey[] = "windowId"; const char kTitleKey[] = "title"; const char kUrlKey[] = "url"; const char kStatusKey[] = "status"; const char kAudibleKey[] = "audible"; const char kDiscardedKey[] = "discarded"; const char kAutoDiscardableKey[] = "autoDiscardable"; const char kHighlightedKey[] = "highlighted"; const char kIndexKey[] = "index"; const char kPinnedKey[] = "pinned"; const char kSelectedKey[] = "selected"; } // namespace keys static std::map<int, std::pair<int, int>> render_view_map_; static std::map<int, int> active_tab_map_; static int32_t next_id = 1; namespace extensions { TabHelper::TabHelper(content::WebContents* contents) : content::WebContentsObserver(contents), values_(new base::DictionaryValue), script_executor_( new ScriptExecutor(contents, &script_execution_observers_)) { session_id_ = next_id++; RenderViewCreated(contents->GetRenderViewHost()); contents->ForEachFrame( base::Bind(&TabHelper::SetTabId, base::Unretained(this))); AtomExtensionWebContentsObserver::CreateForWebContents(contents); } TabHelper::~TabHelper() { } void TabHelper::SetWindowId(const int32_t& id) { window_id_ = id; // Extension code in the renderer holds the ID of the window that hosts it. // Notify it that the window ID changed. web_contents()->SendToAllFrames( new ExtensionMsg_UpdateBrowserWindowId(MSG_ROUTING_NONE, window_id_)); } void TabHelper::SetActive(bool active) { if (active) active_tab_map_[window_id_] = session_id_; else if (active_tab_map_[window_id_] == session_id_) active_tab_map_[window_id_] = -1; } void TabHelper::SetTabIndex(int index) { index_ = index; } void TabHelper::SetTabValues(const base::DictionaryValue& values) { values_->MergeDictionary(&values); } void TabHelper::RenderViewCreated(content::RenderViewHost* render_view_host) { render_view_map_[session_id_] = std::make_pair( render_view_host->GetProcess()->GetID(), render_view_host->GetRoutingID()); } void TabHelper::RenderFrameCreated(content::RenderFrameHost* host) { SetTabId(host); } void TabHelper::WebContentsDestroyed() { render_view_map_.erase(session_id_); } void TabHelper::SetTabId(content::RenderFrameHost* render_frame_host) { render_frame_host->Send( new ExtensionMsg_SetTabId(render_frame_host->GetRoutingID(), session_id_)); } void TabHelper::DidCloneToNewWebContents( content::WebContents* old_web_contents, content::WebContents* new_web_contents) { // When the WebContents that this is attached to is cloned, // give the new clone a TabHelper and copy state over. CreateForWebContents(new_web_contents); } bool TabHelper::ExecuteScriptInTab(mate::Arguments* args) { std::string extension_id; if (!args->GetNext(&extension_id)) { args->ThrowError("extensionId is a required field"); return false; } std::string code_string; if (!args->GetNext(&code_string)) { args->ThrowError("codeString is a required field"); return false; } base::DictionaryValue options; if (!args->GetNext(&options)) { args->ThrowError("options is a required field"); return false; } extensions::ScriptExecutor::ResultType result; extensions::ScriptExecutor::ExecuteScriptCallback callback; if (!args->GetNext(&callback)) { callback = extensions::ScriptExecutor::ExecuteScriptCallback(); result = extensions::ScriptExecutor::NO_RESULT; } else { result = extensions::ScriptExecutor::JSON_SERIALIZED_RESULT; } extensions::ScriptExecutor* executor = script_executor(); if (!executor) return false; std::string file; GURL file_url; options.GetString("file", &file); std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy(); if (!file.empty()) { ExtensionRegistry* registry = ExtensionRegistry::Get(web_contents()->GetBrowserContext()); if (!registry) return false; const Extension* extension = registry->enabled_extensions().GetByID(extension_id); if (!extension) return false; ExtensionResource resource = extension->GetResource(file); if (resource.extension_root().empty() || resource.relative_path().empty()) { return false; } file_url = net::FilePathToFileURL(resource.GetFilePath()); int resource_id; const ComponentExtensionResourceManager* component_extension_resource_manager = ExtensionsBrowserClient::Get() ->GetComponentExtensionResourceManager(); if (component_extension_resource_manager && component_extension_resource_manager->IsComponentExtensionResource( resource.extension_root(), resource.relative_path(), &resource_id)) { const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); file = rb.GetRawDataResource(resource_id).as_string(); } else { scoped_refptr<FileReader> file_reader(new FileReader( resource, base::Bind(&TabHelper::ExecuteScript, base::Unretained(this), extension_id, base::Passed(&copy), result, callback, file_url))); file_reader->Start(); return true; } } ExecuteScript(extension_id, std::move(copy), result, callback, file_url, true, base::MakeUnique<std::string>(file.empty() ? code_string : file)); return true; } void TabHelper::ExecuteScript( const std::string extension_id, std::unique_ptr<base::DictionaryValue> options, extensions::ScriptExecutor::ResultType result, extensions::ScriptExecutor::ExecuteScriptCallback callback, const GURL& file_url, bool success, std::unique_ptr<std::string> code_string) { extensions::ScriptExecutor* executor = script_executor(); bool all_frames = false; options->GetBoolean("allFrames", &all_frames); extensions::ScriptExecutor::FrameScope frame_scope = all_frames ? extensions::ScriptExecutor::INCLUDE_SUB_FRAMES : extensions::ScriptExecutor::SINGLE_FRAME; int frame_id = extensions::ExtensionApiFrameIdMap::kTopFrameId; options->GetInteger("frameId", &frame_id); bool match_about_blank = false; options->GetBoolean("matchAboutBlank", &match_about_blank); bool main_world = false; options->GetBoolean("mainWorld", &main_world); extensions::UserScript::RunLocation run_at = extensions::UserScript::UNDEFINED; std::string run_at_string = "undefined"; options->GetString("runAt", &run_at_string); if (run_at_string == "document_start") { run_at = extensions::UserScript::DOCUMENT_START; } else if (run_at_string == "document_end") { run_at = extensions::UserScript::DOCUMENT_END; } else if (run_at_string == "document_idle") { run_at = extensions::UserScript::DOCUMENT_IDLE; } executor->ExecuteScript( HostID(HostID::EXTENSIONS, extension_id), extensions::ScriptExecutor::JAVASCRIPT, *code_string, frame_scope, frame_id, match_about_blank ? extensions::ScriptExecutor::MATCH_ABOUT_BLANK : extensions::ScriptExecutor::DONT_MATCH_ABOUT_BLANK, run_at, main_world ? extensions::ScriptExecutor::MAIN_WORLD : extensions::ScriptExecutor::ISOLATED_WORLD, extensions::ScriptExecutor::DEFAULT_PROCESS, GURL(), // No webview src. file_url, // No file url. false, // user gesture result, callback); } // static content::WebContents* TabHelper::GetTabById(int32_t tab_id) { content::RenderViewHost* rvh = content::RenderViewHost::FromID(render_view_map_[tab_id].first, render_view_map_[tab_id].second); if (rvh) { return content::WebContents::FromRenderViewHost(rvh); } else { return NULL; } } // static content::WebContents* TabHelper::GetTabById(int32_t tab_id, content::BrowserContext* browser_context) { auto contents = GetTabById(tab_id); if (contents) { if (extensions::ExtensionsBrowserClient::Get()->IsSameContext( browser_context, contents->GetBrowserContext())) { if (tab_id == extensions::TabHelper::IdForTab(contents)) return contents; } } return NULL; } // static base::DictionaryValue* TabHelper::CreateTabValue( content::WebContents* contents) { auto tab_id = IdForTab(contents); auto window_id = IdForWindowContainingTab(contents); auto tab_helper = TabHelper::FromWebContents(contents); bool active = (active_tab_map_[window_id] == tab_id); std::unique_ptr<base::DictionaryValue> result( tab_helper->getTabValues()->CreateDeepCopy()); result->SetInteger(keys::kIdKey, tab_id); result->SetInteger(keys::kWindowIdKey, window_id); result->SetBoolean(keys::kIncognitoKey, contents->GetBrowserContext()->IsOffTheRecord()); result->SetBoolean(keys::kActiveKey, active); result->SetString(keys::kUrlKey, contents->GetURL().spec()); result->SetString(keys::kTitleKey, contents->GetTitle()); result->SetString(keys::kStatusKey, contents->IsLoading() ? "loading" : "complete"); result->SetBoolean(keys::kAudibleKey, contents->WasRecentlyAudible()); result->SetBoolean(keys::kDiscardedKey, false); result->SetBoolean(keys::kAutoDiscardableKey, false); result->SetBoolean(keys::kHighlightedKey, active); result->SetInteger(keys::kIndexKey, tab_helper->index_); // TODO(bridiver) - set pinned value result->SetBoolean(keys::kPinnedKey, false); result->SetBoolean(keys::kSelectedKey, active); return result.release(); } // static int32_t TabHelper::IdForTab(const content::WebContents* tab) { const TabHelper* session_tab_helper = tab ? TabHelper::FromWebContents(tab) : NULL; return session_tab_helper ? session_tab_helper->session_id_ : -1; } // static int32_t TabHelper::IdForWindowContainingTab( const content::WebContents* tab) { const TabHelper* session_tab_helper = tab ? TabHelper::FromWebContents(tab) : NULL; return session_tab_helper ? session_tab_helper->window_id_ : -1; } } // namespace extensions <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/atom_renderer_client.h" #include <string> #include <vector> #include "atom/common/api/api_messages.h" #include "atom/common/api/atom_bindings.h" #include "atom/common/api/event_emitter_caller.h" #include "atom/common/color_util.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/node_bindings.h" #include "atom/common/options_switches.h" #include "atom/renderer/atom_render_view_observer.h" #include "atom/renderer/content_settings_observer.h" #include "atom/renderer/guest_view_container.h" #include "atom/renderer/node_array_buffer_bridge.h" #include "atom/renderer/preferences_manager.h" #include "base/command_line.h" #include "chrome/renderer/media/chrome_key_systems.h" #include "chrome/renderer/pepper/pepper_helper.h" #include "chrome/renderer/printing/print_web_view_helper.h" #include "chrome/renderer/tts_dispatcher.h" #include "content/public/common/content_constants.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "ipc/ipc_message_macros.h" #include "native_mate/dictionary.h" #include "third_party/WebKit/public/web/WebCustomElement.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginParams.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebSecurityPolicy.h" #include "third_party/WebKit/public/web/WebView.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #endif #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/common/node_includes.h" namespace atom { namespace { // Helper class to forward the messages to the client. class AtomRenderFrameObserver : public content::RenderFrameObserver { public: AtomRenderFrameObserver(content::RenderFrame* frame, AtomRendererClient* renderer_client, bool isolated_world) : content::RenderFrameObserver(frame), render_frame_(frame), isolated_world_(isolated_world), renderer_client_(renderer_client) {} // content::RenderFrameObserver: void DidClearWindowObject() override { renderer_client_->DidClearWindowObject(render_frame_); } void CreateIsolatedWorldContext() { blink::WebScriptSource source("void 0"); render_frame_->GetWebFrame()->executeScriptInIsolatedWorld( kIsolatedWorldId, &source, 1, 1); } bool IsMainWorld(int world_id) { return world_id == kMainWorldId; } bool IsIsolatedWorld(int world_id) { return world_id == kIsolatedWorldId; } void DidCreateScriptContext(v8::Handle<v8::Context> context, int extension_group, int world_id) override { bool notify_client = isolated_world_ ? IsIsolatedWorld(world_id) : IsMainWorld(world_id); if (notify_client) renderer_client_->DidCreateScriptContext(context, render_frame_); if (isolated_world_ && IsMainWorld(world_id)) CreateIsolatedWorldContext(); } void WillReleaseScriptContext(v8::Local<v8::Context> context, int world_id) override { bool notify_client = isolated_world_ ? IsIsolatedWorld(world_id) : IsMainWorld(world_id); if (notify_client) renderer_client_->WillReleaseScriptContext(context, render_frame_); } void OnDestruct() override { delete this; } private: content::RenderFrame* render_frame_; bool isolated_world_; AtomRendererClient* renderer_client_; const int kMainWorldId = 0; const int kIsolatedWorldId = 999; DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver); }; v8::Local<v8::Value> GetRenderProcessPreferences( const PreferencesManager* preferences_manager, v8::Isolate* isolate) { if (preferences_manager->preferences()) return mate::ConvertToV8(isolate, *preferences_manager->preferences()); else return v8::Null(isolate); } void AddRenderBindings(v8::Isolate* isolate, v8::Local<v8::Object> process, const PreferencesManager* preferences_manager) { mate::Dictionary dict(isolate, process); dict.SetMethod( "getRenderProcessPreferences", base::Bind(GetRenderProcessPreferences, preferences_manager)); } bool IsDevToolsExtension(content::RenderFrame* render_frame) { return static_cast<GURL>(render_frame->GetWebFrame()->document().url()) .SchemeIs("chrome-extension"); } std::vector<std::string> ParseSchemesCLISwitch(const char* switch_name) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name); return base::SplitString( custom_schemes, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); } } // namespace AtomRendererClient::AtomRendererClient() : node_bindings_(NodeBindings::Create(false)), atom_bindings_(new AtomBindings) { // Parse --standard-schemes=scheme1,scheme2 std::vector<std::string> standard_schemes_list = ParseSchemesCLISwitch(switches::kStandardSchemes); for (const std::string& scheme : standard_schemes_list) url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT); } AtomRendererClient::~AtomRendererClient() { } void AtomRendererClient::RenderThreadStarted() { blink::WebCustomElement::addEmbedderCustomElementName("webview"); blink::WebCustomElement::addEmbedderCustomElementName("browserplugin"); OverrideNodeArrayBuffer(); preferences_manager_.reset(new PreferencesManager); #if defined(OS_WIN) // Set ApplicationUserModelID in renderer process. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::string16 app_id = command_line->GetSwitchValueNative(switches::kAppUserModelId); if (!app_id.empty()) { SetCurrentProcessExplicitAppUserModelID(app_id.c_str()); } #endif #if defined(OS_MACOSX) // Disable rubber banding by default. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switches::kScrollBounce)) { base::ScopedCFTypeRef<CFStringRef> key( base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding")); base::ScopedCFTypeRef<CFStringRef> value( base::SysUTF8ToCFStringRef("false")); CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication); CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); } #endif } void AtomRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new PepperHelper(render_frame); bool isolated_world = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kIsolatedWorld); new AtomRenderFrameObserver(render_frame, this, isolated_world); new ContentSettingsObserver(render_frame); // Allow file scheme to handle service worker by default. // FIXME(zcbenz): Can this be moved elsewhere? blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers("file"); // Parse --secure-schemes=scheme1,scheme2 std::vector<std::string> secure_schemes_list = ParseSchemesCLISwitch(switches::kSecureSchemes); for (const std::string& secure_scheme : secure_schemes_list) blink::WebSecurityPolicy::registerURLSchemeAsSecure( blink::WebString::fromUTF8(secure_scheme)); } void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) { new printing::PrintWebViewHelper(render_view); new AtomRenderViewObserver(render_view, this); blink::WebFrameWidget* web_frame_widget = render_view->GetWebFrameWidget(); if (!web_frame_widget) return; base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview. web_frame_widget->setBaseBackgroundColor(SK_ColorTRANSPARENT); } else { // normal window. // If backgroundColor is specified then use it. std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor); // Otherwise use white background. SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name); web_frame_widget->setBaseBackgroundColor(color); } } void AtomRendererClient::DidClearWindowObject( content::RenderFrame* render_frame) { // Make sure every page will get a script context created. render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0")); } void AtomRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { // Inform the document start pharse. node::Environment* env = node_bindings_->uv_env(); if (env) { v8::HandleScope handle_scope(env->isolate()); mate::EmitEvent(env->isolate(), env->process_object(), "document-start"); } } void AtomRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { // Inform the document end pharse. node::Environment* env = node_bindings_->uv_env(); if (env) { v8::HandleScope handle_scope(env->isolate()); mate::EmitEvent(env->isolate(), env->process_object(), "document-end"); } } blink::WebSpeechSynthesizer* AtomRendererClient::OverrideSpeechSynthesizer( blink::WebSpeechSynthesizerClient* client) { return new TtsDispatcher(client); } bool AtomRendererClient::OverrideCreatePlugin( content::RenderFrame* render_frame, blink::WebLocalFrame* frame, const blink::WebPluginParams& params, blink::WebPlugin** plugin) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (params.mimeType.utf8() == content::kBrowserPluginMimeType || command_line->HasSwitch(switches::kEnablePlugins)) return false; *plugin = nullptr; return true; } void AtomRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { // Only allow node integration for the main frame, unless it is a devtools // extension page. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame)) return; api_context_.Reset(context->GetIsolate(), context); api_context_.SetWeak(); // Whether the node binding has been initialized. bool first_time = node_bindings_->uv_env() == nullptr; // Prepare the node bindings. if (first_time) { node_bindings_->Initialize(); node_bindings_->PrepareMessageLoop(); } // Setup node environment for each window. node::Environment* env = node_bindings_->CreateEnvironment(context); // Add Electron extended APIs. atom_bindings_->BindTo(env->isolate(), env->process_object()); AddRenderBindings(env->isolate(), env->process_object(), preferences_manager_.get()); // Load everything. node_bindings_->LoadEnvironment(env); if (first_time) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } } void AtomRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { // Only allow node integration for the main frame, unless it is a devtools // extension page. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame)) return; node::Environment* env = node::Environment::GetCurrent(context); if (env) mate::EmitEvent(env->isolate(), env->process_object(), "exit"); } bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame, const GURL& url, const std::string& http_method, bool is_initial_navigation, bool is_server_redirect, bool* send_referrer) { // Handle all the navigations and reloads in browser. // FIXME We only support GET here because http method will be ignored when // the OpenURLFromTab is triggered, which means form posting would not work, // we should solve this by patching Chromium in future. *send_referrer = true; return http_method == "GET"; } content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate( content::RenderFrame* render_frame, const std::string& mime_type, const GURL& original_url) { if (mime_type == content::kBrowserPluginMimeType) { return new GuestViewContainer(render_frame); } else { return nullptr; } } void AtomRendererClient::AddSupportedKeySystems( std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) { AddChromeKeySystems(key_systems); } v8::Local<v8::Context> AtomRendererClient::GetAPIContext(v8::Isolate* isolate) { return api_context_.Get(isolate); } } // namespace atom <commit_msg>:art: Use enum for world ids<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/atom_renderer_client.h" #include <string> #include <vector> #include "atom/common/api/api_messages.h" #include "atom/common/api/atom_bindings.h" #include "atom/common/api/event_emitter_caller.h" #include "atom/common/color_util.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/node_bindings.h" #include "atom/common/options_switches.h" #include "atom/renderer/atom_render_view_observer.h" #include "atom/renderer/content_settings_observer.h" #include "atom/renderer/guest_view_container.h" #include "atom/renderer/node_array_buffer_bridge.h" #include "atom/renderer/preferences_manager.h" #include "base/command_line.h" #include "chrome/renderer/media/chrome_key_systems.h" #include "chrome/renderer/pepper/pepper_helper.h" #include "chrome/renderer/printing/print_web_view_helper.h" #include "chrome/renderer/tts_dispatcher.h" #include "content/public/common/content_constants.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "ipc/ipc_message_macros.h" #include "native_mate/dictionary.h" #include "third_party/WebKit/public/web/WebCustomElement.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPluginParams.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebSecurityPolicy.h" #include "third_party/WebKit/public/web/WebView.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #endif #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/common/node_includes.h" namespace atom { namespace { // Helper class to forward the messages to the client. class AtomRenderFrameObserver : public content::RenderFrameObserver { public: AtomRenderFrameObserver(content::RenderFrame* frame, AtomRendererClient* renderer_client, bool isolated_world) : content::RenderFrameObserver(frame), render_frame_(frame), isolated_world_(isolated_world), renderer_client_(renderer_client) {} // content::RenderFrameObserver: void DidClearWindowObject() override { renderer_client_->DidClearWindowObject(render_frame_); } void CreateIsolatedWorldContext() { blink::WebScriptSource source("void 0"); render_frame_->GetWebFrame()->executeScriptInIsolatedWorld( World::ISOLATED, &source, 1, 1); } bool IsMainWorld(int world_id) { return world_id == World::MAIN; } bool IsIsolatedWorld(int world_id) { return world_id == World::ISOLATED; } void DidCreateScriptContext(v8::Handle<v8::Context> context, int extension_group, int world_id) override { bool notify_client = isolated_world_ ? IsIsolatedWorld(world_id) : IsMainWorld(world_id); if (notify_client) renderer_client_->DidCreateScriptContext(context, render_frame_); if (isolated_world_ && IsMainWorld(world_id)) CreateIsolatedWorldContext(); } void WillReleaseScriptContext(v8::Local<v8::Context> context, int world_id) override { bool notify_client = isolated_world_ ? IsIsolatedWorld(world_id) : IsMainWorld(world_id); if (notify_client) renderer_client_->WillReleaseScriptContext(context, render_frame_); } void OnDestruct() override { delete this; } private: content::RenderFrame* render_frame_; bool isolated_world_; AtomRendererClient* renderer_client_; enum World { MAIN = 0, ISOLATED = 999 }; DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver); }; v8::Local<v8::Value> GetRenderProcessPreferences( const PreferencesManager* preferences_manager, v8::Isolate* isolate) { if (preferences_manager->preferences()) return mate::ConvertToV8(isolate, *preferences_manager->preferences()); else return v8::Null(isolate); } void AddRenderBindings(v8::Isolate* isolate, v8::Local<v8::Object> process, const PreferencesManager* preferences_manager) { mate::Dictionary dict(isolate, process); dict.SetMethod( "getRenderProcessPreferences", base::Bind(GetRenderProcessPreferences, preferences_manager)); } bool IsDevToolsExtension(content::RenderFrame* render_frame) { return static_cast<GURL>(render_frame->GetWebFrame()->document().url()) .SchemeIs("chrome-extension"); } std::vector<std::string> ParseSchemesCLISwitch(const char* switch_name) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name); return base::SplitString( custom_schemes, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); } } // namespace AtomRendererClient::AtomRendererClient() : node_bindings_(NodeBindings::Create(false)), atom_bindings_(new AtomBindings) { // Parse --standard-schemes=scheme1,scheme2 std::vector<std::string> standard_schemes_list = ParseSchemesCLISwitch(switches::kStandardSchemes); for (const std::string& scheme : standard_schemes_list) url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT); } AtomRendererClient::~AtomRendererClient() { } void AtomRendererClient::RenderThreadStarted() { blink::WebCustomElement::addEmbedderCustomElementName("webview"); blink::WebCustomElement::addEmbedderCustomElementName("browserplugin"); OverrideNodeArrayBuffer(); preferences_manager_.reset(new PreferencesManager); #if defined(OS_WIN) // Set ApplicationUserModelID in renderer process. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); base::string16 app_id = command_line->GetSwitchValueNative(switches::kAppUserModelId); if (!app_id.empty()) { SetCurrentProcessExplicitAppUserModelID(app_id.c_str()); } #endif #if defined(OS_MACOSX) // Disable rubber banding by default. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switches::kScrollBounce)) { base::ScopedCFTypeRef<CFStringRef> key( base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding")); base::ScopedCFTypeRef<CFStringRef> value( base::SysUTF8ToCFStringRef("false")); CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication); CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); } #endif } void AtomRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new PepperHelper(render_frame); bool isolated_world = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kIsolatedWorld); new AtomRenderFrameObserver(render_frame, this, isolated_world); new ContentSettingsObserver(render_frame); // Allow file scheme to handle service worker by default. // FIXME(zcbenz): Can this be moved elsewhere? blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers("file"); // Parse --secure-schemes=scheme1,scheme2 std::vector<std::string> secure_schemes_list = ParseSchemesCLISwitch(switches::kSecureSchemes); for (const std::string& secure_scheme : secure_schemes_list) blink::WebSecurityPolicy::registerURLSchemeAsSecure( blink::WebString::fromUTF8(secure_scheme)); } void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) { new printing::PrintWebViewHelper(render_view); new AtomRenderViewObserver(render_view, this); blink::WebFrameWidget* web_frame_widget = render_view->GetWebFrameWidget(); if (!web_frame_widget) return; base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview. web_frame_widget->setBaseBackgroundColor(SK_ColorTRANSPARENT); } else { // normal window. // If backgroundColor is specified then use it. std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor); // Otherwise use white background. SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name); web_frame_widget->setBaseBackgroundColor(color); } } void AtomRendererClient::DidClearWindowObject( content::RenderFrame* render_frame) { // Make sure every page will get a script context created. render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0")); } void AtomRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { // Inform the document start pharse. node::Environment* env = node_bindings_->uv_env(); if (env) { v8::HandleScope handle_scope(env->isolate()); mate::EmitEvent(env->isolate(), env->process_object(), "document-start"); } } void AtomRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { // Inform the document end pharse. node::Environment* env = node_bindings_->uv_env(); if (env) { v8::HandleScope handle_scope(env->isolate()); mate::EmitEvent(env->isolate(), env->process_object(), "document-end"); } } blink::WebSpeechSynthesizer* AtomRendererClient::OverrideSpeechSynthesizer( blink::WebSpeechSynthesizerClient* client) { return new TtsDispatcher(client); } bool AtomRendererClient::OverrideCreatePlugin( content::RenderFrame* render_frame, blink::WebLocalFrame* frame, const blink::WebPluginParams& params, blink::WebPlugin** plugin) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (params.mimeType.utf8() == content::kBrowserPluginMimeType || command_line->HasSwitch(switches::kEnablePlugins)) return false; *plugin = nullptr; return true; } void AtomRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { // Only allow node integration for the main frame, unless it is a devtools // extension page. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame)) return; api_context_.Reset(context->GetIsolate(), context); api_context_.SetWeak(); // Whether the node binding has been initialized. bool first_time = node_bindings_->uv_env() == nullptr; // Prepare the node bindings. if (first_time) { node_bindings_->Initialize(); node_bindings_->PrepareMessageLoop(); } // Setup node environment for each window. node::Environment* env = node_bindings_->CreateEnvironment(context); // Add Electron extended APIs. atom_bindings_->BindTo(env->isolate(), env->process_object()); AddRenderBindings(env->isolate(), env->process_object(), preferences_manager_.get()); // Load everything. node_bindings_->LoadEnvironment(env); if (first_time) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } } void AtomRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { // Only allow node integration for the main frame, unless it is a devtools // extension page. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame)) return; node::Environment* env = node::Environment::GetCurrent(context); if (env) mate::EmitEvent(env->isolate(), env->process_object(), "exit"); } bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame, const GURL& url, const std::string& http_method, bool is_initial_navigation, bool is_server_redirect, bool* send_referrer) { // Handle all the navigations and reloads in browser. // FIXME We only support GET here because http method will be ignored when // the OpenURLFromTab is triggered, which means form posting would not work, // we should solve this by patching Chromium in future. *send_referrer = true; return http_method == "GET"; } content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate( content::RenderFrame* render_frame, const std::string& mime_type, const GURL& original_url) { if (mime_type == content::kBrowserPluginMimeType) { return new GuestViewContainer(render_frame); } else { return nullptr; } } void AtomRendererClient::AddSupportedKeySystems( std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) { AddChromeKeySystems(key_systems); } v8::Local<v8::Context> AtomRendererClient::GetAPIContext(v8::Isolate* isolate) { return api_context_.Get(isolate); } } // namespace atom <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: servres.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:20:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <string.h> #include "servres.hrc" #include "servuid.hxx" #include "servres.hxx" ModalDialogGROSSER_TEST_DLG::ModalDialogGROSSER_TEST_DLG( Window * pParent, const ResId & rResId, BOOL bFreeRes ) : ModalDialog( pParent, rResId ), aCheckBox1( this, ResId( 1 ) ), aTriStateBox1( this, ResId( 1 ) ), aOKButton1( this, ResId( 1 ) ), aTimeField1( this, ResId( 1 ) ), aMultiLineEdit1( this, ResId( 1 ) ), aGroupBox1( this, ResId( 1 ) ), aRadioButton1( this, ResId( 1 ) ), aRadioButton2( this, ResId( 2 ) ), aMultiListBox1( this, ResId( 1 ) ), aComboBox1( this, ResId( 1 ) ), aDateBox1( this, ResId( 1 ) ), aFixedText1( this, ResId( 1 ) ) { if( bFreeRes ) FreeResource(); } MenuMENU_CLIENT::MenuMENU_CLIENT( const ResId & rResId, BOOL ) : MenuBar( rResId ) { // No subresources, automatic free resource } <commit_msg>INTEGRATION: CWS pchfix02 (1.2.56); FILE MERGED 2006/09/01 17:16:04 kaib 1.2.56.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: servres.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 00:34:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_automation.hxx" #include <string.h> #include "servres.hrc" #include "servuid.hxx" #include "servres.hxx" ModalDialogGROSSER_TEST_DLG::ModalDialogGROSSER_TEST_DLG( Window * pParent, const ResId & rResId, BOOL bFreeRes ) : ModalDialog( pParent, rResId ), aCheckBox1( this, ResId( 1 ) ), aTriStateBox1( this, ResId( 1 ) ), aOKButton1( this, ResId( 1 ) ), aTimeField1( this, ResId( 1 ) ), aMultiLineEdit1( this, ResId( 1 ) ), aGroupBox1( this, ResId( 1 ) ), aRadioButton1( this, ResId( 1 ) ), aRadioButton2( this, ResId( 2 ) ), aMultiListBox1( this, ResId( 1 ) ), aComboBox1( this, ResId( 1 ) ), aDateBox1( this, ResId( 1 ) ), aFixedText1( this, ResId( 1 ) ) { if( bFreeRes ) FreeResource(); } MenuMENU_CLIENT::MenuMENU_CLIENT( const ResId & rResId, BOOL ) : MenuBar( rResId ) { // No subresources, automatic free resource } <|endoftext|>
<commit_before>// Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "TemplateProxy.h" #include "Utility.h" namespace PyROOT { namespace { //= PyROOT template proxy construction/destruction =========================== TemplateProxy* tpp_new( PyTypeObject*, PyObject*, PyObject* ) { TemplateProxy* pytmpl = PyObject_GC_New( TemplateProxy, &TemplateProxy_Type ); pytmpl->fPyName = NULL; pytmpl->fPyClass = NULL; pytmpl->fSelf = NULL; PyObject_GC_Track( pytmpl ); return pytmpl; } //____________________________________________________________________________ void tpp_dealloc( TemplateProxy* pytmpl ) { PyObject_GC_UnTrack( pytmpl ); PyObject_GC_Del( pytmpl ); } //____________________________________________________________________________ int tpp_traverse( TemplateProxy* pytmpl, visitproc visit, void* args ) { if ( pytmpl->fPyName ) { int err = visit( (PyObject*)pytmpl->fPyName, args ); if ( err ) return err; } if ( pytmpl->fPyClass ) { int err = visit( (PyObject*)pytmpl->fPyClass, args ); if ( err ) return err; } if ( pytmpl->fSelf ) { int err = visit( (PyObject*)pytmpl->fSelf, args ); if ( err ) return err; } return 0; } //____________________________________________________________________________ int tpp_clear( TemplateProxy* pytmpl ) { Py_XDECREF( (PyObject*)pytmpl->fPyName ); pytmpl->fPyName = NULL; Py_XDECREF( (PyObject*)pytmpl->fPyClass ); pytmpl->fPyClass = NULL; Py_XDECREF( (PyObject*)pytmpl->fSelf ); pytmpl->fSelf = NULL; return 0; } //= PyROOT template proxy callable behavior ================================== PyObject* tpp_call( TemplateProxy* pytmpl, PyObject* args, PyObject* kwds ) { // dispatcher to the actual member method, args is self object + template arguments // (as in a function call); build full instantiation PyObject* pymeth = 0; Py_ssize_t nArgs = PyTuple_GET_SIZE( args ); if ( 1 <= nArgs ) { // build "< type, type, ... >" part of method name Py_INCREF( pytmpl->fPyName ); PyObject* pyname = pytmpl->fPyName; if ( Utility::BuildTemplateName( pyname, args, 0 ) ) { // lookup method on self (to make sure it propagates), which is readily callable pymeth = PyObject_GetAttr( pytmpl->fSelf, pyname ); } Py_XDECREF( pyname ); } if ( pymeth ) return pymeth; // templated, now called by the user // if the method lookup fails, try to locate the "generic" version of the template PyErr_Clear(); pymeth = PyObject_GetAttrString( pytmpl->fSelf, (std::string( "__generic_" ) + PyString_AS_STRING( pytmpl->fPyName )).c_str() ); if ( pymeth ) return PyObject_Call( pymeth, args, kwds ); // non-templated, executed as-is return pymeth; } //____________________________________________________________________________ TemplateProxy* tpp_descrget( TemplateProxy* pytmpl, PyObject* pyobj, PyObject* ) { // create and use a new template proxy (language requirement) TemplateProxy* newPyTmpl = (TemplateProxy*)TemplateProxy_Type.tp_alloc( &TemplateProxy_Type, 0 ); // copy name and class Py_INCREF( pytmpl->fPyName ); newPyTmpl->fPyName = pytmpl->fPyName; Py_XINCREF( pytmpl->fPyClass ); newPyTmpl->fPyClass = pytmpl->fPyClass; // new method is to be bound to current object (may be NULL) Py_XINCREF( pyobj ); newPyTmpl->fSelf = pyobj; return newPyTmpl; } } // unnamed namespace //= PyROOT template proxy type =============================================== PyTypeObject TemplateProxy_Type = { PyObject_HEAD_INIT( &PyType_Type ) 0, // ob_size (char*)"ROOT.TemplateProxy", // tp_name sizeof(TemplateProxy), // tp_basicsize 0, // tp_itemsize (destructor)tpp_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash (ternaryfunc)tpp_call, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags (char*)"PyROOT template proxy (internal)", // tp_doc (traverseproc)tpp_traverse,// tp_traverse (inquiry)tpp_clear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict (descrgetfunc)tpp_descrget,// tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)tpp_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0, // tp_weaklist #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3 0 // tp_del #endif }; } // namespace PyROOT <commit_msg>fix const cast compilation problem<commit_after>// Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "TemplateProxy.h" #include "Utility.h" namespace PyROOT { namespace { //= PyROOT template proxy construction/destruction =========================== TemplateProxy* tpp_new( PyTypeObject*, PyObject*, PyObject* ) { TemplateProxy* pytmpl = PyObject_GC_New( TemplateProxy, &TemplateProxy_Type ); pytmpl->fPyName = NULL; pytmpl->fPyClass = NULL; pytmpl->fSelf = NULL; PyObject_GC_Track( pytmpl ); return pytmpl; } //____________________________________________________________________________ void tpp_dealloc( TemplateProxy* pytmpl ) { PyObject_GC_UnTrack( pytmpl ); PyObject_GC_Del( pytmpl ); } //____________________________________________________________________________ int tpp_traverse( TemplateProxy* pytmpl, visitproc visit, void* args ) { if ( pytmpl->fPyName ) { int err = visit( (PyObject*)pytmpl->fPyName, args ); if ( err ) return err; } if ( pytmpl->fPyClass ) { int err = visit( (PyObject*)pytmpl->fPyClass, args ); if ( err ) return err; } if ( pytmpl->fSelf ) { int err = visit( (PyObject*)pytmpl->fSelf, args ); if ( err ) return err; } return 0; } //____________________________________________________________________________ int tpp_clear( TemplateProxy* pytmpl ) { Py_XDECREF( (PyObject*)pytmpl->fPyName ); pytmpl->fPyName = NULL; Py_XDECREF( (PyObject*)pytmpl->fPyClass ); pytmpl->fPyClass = NULL; Py_XDECREF( (PyObject*)pytmpl->fSelf ); pytmpl->fSelf = NULL; return 0; } //= PyROOT template proxy callable behavior ================================== PyObject* tpp_call( TemplateProxy* pytmpl, PyObject* args, PyObject* kwds ) { // dispatcher to the actual member method, args is self object + template arguments // (as in a function call); build full instantiation PyObject* pymeth = 0; Py_ssize_t nArgs = PyTuple_GET_SIZE( args ); if ( 1 <= nArgs ) { // build "< type, type, ... >" part of method name Py_INCREF( pytmpl->fPyName ); PyObject* pyname = pytmpl->fPyName; if ( Utility::BuildTemplateName( pyname, args, 0 ) ) { // lookup method on self (to make sure it propagates), which is readily callable pymeth = PyObject_GetAttr( pytmpl->fSelf, pyname ); } Py_XDECREF( pyname ); } if ( pymeth ) return pymeth; // templated, now called by the user // if the method lookup fails, try to locate the "generic" version of the template PyErr_Clear(); pymeth = PyObject_GetAttrString( pytmpl->fSelf, const_cast< char* >( (std::string( "__generic_" ) + PyString_AS_STRING( pytmpl->fPyName )).c_str()) ); if ( pymeth ) return PyObject_Call( pymeth, args, kwds ); // non-templated, executed as-is return pymeth; } //____________________________________________________________________________ TemplateProxy* tpp_descrget( TemplateProxy* pytmpl, PyObject* pyobj, PyObject* ) { // create and use a new template proxy (language requirement) TemplateProxy* newPyTmpl = (TemplateProxy*)TemplateProxy_Type.tp_alloc( &TemplateProxy_Type, 0 ); // copy name and class Py_INCREF( pytmpl->fPyName ); newPyTmpl->fPyName = pytmpl->fPyName; Py_XINCREF( pytmpl->fPyClass ); newPyTmpl->fPyClass = pytmpl->fPyClass; // new method is to be bound to current object (may be NULL) Py_XINCREF( pyobj ); newPyTmpl->fSelf = pyobj; return newPyTmpl; } } // unnamed namespace //= PyROOT template proxy type =============================================== PyTypeObject TemplateProxy_Type = { PyObject_HEAD_INIT( &PyType_Type ) 0, // ob_size (char*)"ROOT.TemplateProxy", // tp_name sizeof(TemplateProxy), // tp_basicsize 0, // tp_itemsize (destructor)tpp_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash (ternaryfunc)tpp_call, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags (char*)"PyROOT template proxy (internal)", // tp_doc (traverseproc)tpp_traverse,// tp_traverse (inquiry)tpp_clear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict (descrgetfunc)tpp_descrget,// tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)tpp_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0, // tp_weaklist #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3 0 // tp_del #endif }; } // namespace PyROOT <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> // stl #include <sstream> #include <vector> // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/feature_layer_desc.hpp> #include <mapnik/memory_datasource.hpp> using mapnik::datasource; using mapnik::point_datasource; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; struct ds_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const datasource& ds) { mapnik::parameters params = ds.params(); return boost::python::make_tuple(params); } }; namespace { //user-friendly wrapper that uses Python dictionary using namespace boost::python; boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d) { mapnik::parameters params; boost::python::list keys=d.keys(); for (int i=0; i<len(keys); ++i) { std::string key = extract<std::string>(keys[i]); object obj = d[key]; extract<std::string> ex0(obj); extract<int> ex1(obj); extract<double> ex2(obj); if (ex0.check()) { params[key] = ex0(); } else if (ex1.check()) { params[key] = ex1(); } else if (ex2.check()) { params[key] = ex2(); } } return mapnik::datasource_cache::create(params); } std::string describe(boost::shared_ptr<mapnik::datasource> const& ds) { std::stringstream ss; if (ds) { ss << ds->get_descriptor() << "\n"; } else { ss << "Null\n"; } return ss.str(); } std::string encoding(boost::shared_ptr<mapnik::datasource> const& ds) { layer_descriptor ld = ds->get_descriptor(); return ld.get_encoding(); } std::string name(boost::shared_ptr<mapnik::datasource> const& ds) { layer_descriptor ld = ds->get_descriptor(); return ld.get_name(); } boost::python::list fields(boost::shared_ptr<mapnik::datasource> const& ds) { boost::python::list flds; if (ds) { layer_descriptor ld = ds->get_descriptor(); std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors(); std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_ar.end(); for (; it != end; ++it) { flds.append(it->get_name()); } } return flds; } boost::python::list field_types(boost::shared_ptr<mapnik::datasource> const& ds) { boost::python::list fld_types; if (ds) { layer_descriptor ld = ds->get_descriptor(); std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors(); std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_ar.end(); for (; it != end; ++it) { unsigned type = it->get_type(); fld_types.append(type); } } return fld_types; }} void export_datasource() { using namespace boost::python; class_<datasource,boost::shared_ptr<datasource>, boost::noncopyable>("Datasource",no_init) .def_pickle(ds_pickle_suite()) .def("envelope",&datasource::envelope) .def("descriptor",&datasource::get_descriptor) //todo .def("features",&datasource::features) .def("fields",&fields) .def("_field_types",&field_types) .def("encoding",&encoding) //todo expose as property .def("name",&name) .def("features_at_point",&datasource::features_at_point) .def("params",&datasource::params,return_value_policy<copy_const_reference>(), "The configuration parameters of the data source. " "These vary depending on the type of data source.") ; def("Describe",&describe); def("CreateDatasource",&create_datasource); class_<point_datasource, bases<datasource>, boost::noncopyable>("PointDatasource", init<>()) .def("add_point",&point_datasource::add_point) ; } <commit_msg>revert pickling support on datsources since they can't be created directly from python - we now dump and load in the layer object via params as of r1149 - see #345<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> // stl #include <sstream> #include <vector> // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/feature_layer_desc.hpp> #include <mapnik/memory_datasource.hpp> using mapnik::datasource; using mapnik::point_datasource; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; namespace { //user-friendly wrapper that uses Python dictionary using namespace boost::python; boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d) { mapnik::parameters params; boost::python::list keys=d.keys(); for (int i=0; i<len(keys); ++i) { std::string key = extract<std::string>(keys[i]); object obj = d[key]; extract<std::string> ex0(obj); extract<int> ex1(obj); extract<double> ex2(obj); if (ex0.check()) { params[key] = ex0(); } else if (ex1.check()) { params[key] = ex1(); } else if (ex2.check()) { params[key] = ex2(); } } return mapnik::datasource_cache::create(params); } std::string describe(boost::shared_ptr<mapnik::datasource> const& ds) { std::stringstream ss; if (ds) { ss << ds->get_descriptor() << "\n"; } else { ss << "Null\n"; } return ss.str(); } std::string encoding(boost::shared_ptr<mapnik::datasource> const& ds) { layer_descriptor ld = ds->get_descriptor(); return ld.get_encoding(); } std::string name(boost::shared_ptr<mapnik::datasource> const& ds) { layer_descriptor ld = ds->get_descriptor(); return ld.get_name(); } boost::python::list fields(boost::shared_ptr<mapnik::datasource> const& ds) { boost::python::list flds; if (ds) { layer_descriptor ld = ds->get_descriptor(); std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors(); std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_ar.end(); for (; it != end; ++it) { flds.append(it->get_name()); } } return flds; } boost::python::list field_types(boost::shared_ptr<mapnik::datasource> const& ds) { boost::python::list fld_types; if (ds) { layer_descriptor ld = ds->get_descriptor(); std::vector<attribute_descriptor> const& desc_ar = ld.get_descriptors(); std::vector<attribute_descriptor>::const_iterator it = desc_ar.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_ar.end(); for (; it != end; ++it) { unsigned type = it->get_type(); fld_types.append(type); } } return fld_types; }} void export_datasource() { using namespace boost::python; class_<datasource,boost::shared_ptr<datasource>, boost::noncopyable>("Datasource",no_init) .def("envelope",&datasource::envelope) .def("descriptor",&datasource::get_descriptor) //todo .def("features",&datasource::features) .def("fields",&fields) .def("_field_types",&field_types) .def("encoding",&encoding) //todo expose as property .def("name",&name) .def("features_at_point",&datasource::features_at_point) .def("params",&datasource::params,return_value_policy<copy_const_reference>(), "The configuration parameters of the data source. " "These vary depending on the type of data source.") ; def("Describe",&describe); def("CreateDatasource",&create_datasource); class_<point_datasource, bases<datasource>, boost::noncopyable>("PointDatasource", init<>()) .def("add_point",&point_datasource::add_point) ; } <|endoftext|>
<commit_before>#include "GraphicBuffer.h" #include <string> #include <cstdlib> #include <iostream> using std::string; const int GRAPHICBUFFER_SIZE = 1024; template<typename Func> void setFuncPtr (Func*& funcPtr, const DynamicLibrary& lib, const string& symname) { funcPtr = reinterpret_cast<Func*>(lib.getFunctionPtr(symname.c_str())); } #if defined(__aarch64__) # define CPU_ARM_64 #elif defined(__arm__) || defined(__ARM__) || defined(__ARM_NEON__) || defined(ARM_BUILD) # define CPU_ARM #elif defined(_M_X64) || defined(__x86_64__) || defined(__amd64__) # define CPU_X86_64 #elif defined(__i386__) || defined(_M_X86) || defined(_M_IX86) || defined(X86_BUILD) # define CPU_X86 #else # warning "target CPU does not support ABI" #endif template <typename RT, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> RT* callConstructor7 (void (*fptr)(), void* memory, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7) { #if defined(CPU_ARM) // C1 constructors return pointer typedef RT* (*ABIFptr)(void*, T1, T2, T3, T4, T5, T6, T7); (void)((ABIFptr)fptr)(memory, param1, param2, param3, param4, param5, param6, param7); return reinterpret_cast<RT*>(memory); #else return nullptr; #endif } template <typename T> void callDestructor (void (*fptr)(), T* obj) { #if defined(CPU_ARM) // D1 destructor returns ptr typedef void* (*ABIFptr)(T* obj); (void)((ABIFptr)fptr)(obj); #elif defined(CPU_ARM_64) // D1 destructor returns void typedef void (*ABIFptr)(T* obj); ((ABIFptr)fptr)(obj); #elif defined(CPU_X86) || defined(CPU_X86_64) // dtor returns void typedef void (*ABIFptr)(T* obj); ((ABIFptr)fptr)(obj); #endif } template<typename T1, typename T2> T1* pointerToOffset (T2* ptr, size_t bytes) { return reinterpret_cast<T1*>((uint8_t *)ptr + bytes); } static android::android_native_base_t* getAndroidNativeBase (android::GraphicBuffer* gb) { return pointerToOffset<android::android_native_base_t>(gb, 2 * sizeof(void *)); } GraphicBuffer::GraphicBuffer(uint32_t width, uint32_t height, PixelFormat format, uint32_t usage): library("libui.so") { setFuncPtr(functions.constructor, library, "_ZN7android13GraphicBufferC2EjjijjP13native_handleb"); setFuncPtr(functions.destructor, library, "_ZN7android13GraphicBufferD1Ev"); setFuncPtr(functions.getNativeBuffer, library, "_ZNK7android13GraphicBuffer15getNativeBufferEv"); setFuncPtr(functions.lock, library, "_ZN7android13GraphicBuffer4lockEjPPv"); setFuncPtr(functions.unlock, library, "_ZN7android13GraphicBuffer6unlockEv"); setFuncPtr(functions.initCheck, library, "_ZNK7android13GraphicBuffer9initCheckEv"); // allocate memory for GraphicBuffer object void *const memory = malloc(GRAPHICBUFFER_SIZE); if (memory == nullptr) { std::cerr << "Could not alloc for GraphicBuffer" << std::endl; return; } try { android::GraphicBuffer* const gb = callConstructor7<android::GraphicBuffer, uint32_t, uint32_t, PixelFormat, uint32_t, uint32_t, void*, bool>( functions.constructor, memory, width, height, format, usage, 1, nullptr, false ); android::android_native_base_t* const base = getAndroidNativeBase(gb); status_t ctorStatus = functions.initCheck(gb); if (ctorStatus) { // ctor failed callDestructor<android::GraphicBuffer>(functions.destructor, gb); std::cerr << "GraphicBuffer ctor failed, initCheck returned " << ctorStatus << std::endl; } // check object layout if (base->magic != 0x5f626672u) // "_bfr" std::cerr << "GraphicBuffer layout unexpected" << std::endl; // check object version const uint32_t expectedVersion = sizeof(void *) == 4 ? 96 : 168; if (base->version != expectedVersion) std::cerr << "GraphicBuffer version unexpected" << std::endl; base->incRef(base); impl = gb; } catch (...) { free(memory); throw; } } GraphicBuffer::~GraphicBuffer() { if (impl) { android::android_native_base_t* const base = getAndroidNativeBase(impl); base->decRef(base); free(impl); } } status_t GraphicBuffer::lock(uint32_t usage, void** vaddr) { return functions.lock(impl, usage, vaddr); } status_t GraphicBuffer::unlock() { return functions.unlock(impl); } ANativeWindowBuffer *GraphicBuffer::getNativeBuffer() const { return functions.getNativeBuffer(impl); } uint32_t GraphicBuffer::getStride() const { return ((android::android_native_buffer_t*)getNativeBuffer())->stride; } <commit_msg>Use constructor with 5 arguments<commit_after>#include "GraphicBuffer.h" #include <string> #include <cstdlib> #include <iostream> using std::string; const int GRAPHICBUFFER_SIZE = 1024; template<typename Func> void setFuncPtr (Func*& funcPtr, const DynamicLibrary& lib, const string& symname) { funcPtr = reinterpret_cast<Func*>(lib.getFunctionPtr(symname.c_str())); } #if defined(__aarch64__) # define CPU_ARM_64 #elif defined(__arm__) || defined(__ARM__) || defined(__ARM_NEON__) || defined(ARM_BUILD) # define CPU_ARM #elif defined(_M_X64) || defined(__x86_64__) || defined(__amd64__) # define CPU_X86_64 #elif defined(__i386__) || defined(_M_X86) || defined(_M_IX86) || defined(X86_BUILD) # define CPU_X86 #else # warning "target CPU does not support ABI" #endif template <typename RT, typename T1, typename T2, typename T3, typename T4, typename T5> RT* callConstructor5 (void (*fptr)(), void* memory, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5) { #if defined(CPU_ARM) // C1 constructors return pointer typedef RT* (*ABIFptr)(void*, T1, T2, T3, T4, T5); (void)((ABIFptr)fptr)(memory, param1, param2, param3, param4, param5); return reinterpret_cast<RT*>(memory); #else qDebug() << "ERROR: UNSUPPORTED ARCH!"; return nullptr; #endif } template <typename T> void callDestructor (void (*fptr)(), T* obj) { #if defined(CPU_ARM) // D1 destructor returns ptr typedef void* (*ABIFptr)(T* obj); (void)((ABIFptr)fptr)(obj); #elif defined(CPU_ARM_64) // D1 destructor returns void typedef void (*ABIFptr)(T* obj); ((ABIFptr)fptr)(obj); #elif defined(CPU_X86) || defined(CPU_X86_64) // dtor returns void typedef void (*ABIFptr)(T* obj); ((ABIFptr)fptr)(obj); #endif } template<typename T1, typename T2> T1* pointerToOffset (T2* ptr, size_t bytes) { return reinterpret_cast<T1*>((uint8_t *)ptr + bytes); } static android::android_native_base_t* getAndroidNativeBase (android::GraphicBuffer* gb) { return pointerToOffset<android::android_native_base_t>(gb, 2 * sizeof(void *)); } GraphicBuffer::GraphicBuffer(uint32_t width, uint32_t height, PixelFormat format, uint32_t usage): library("libui.so") { setFuncPtr(functions.constructor, library, "_ZN7android13GraphicBufferC1EjjijNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE"); setFuncPtr(functions.destructor, library, "_ZN7android13GraphicBufferD1Ev"); setFuncPtr(functions.getNativeBuffer, library, "_ZNK7android13GraphicBuffer15getNativeBufferEv"); setFuncPtr(functions.lock, library, "_ZN7android13GraphicBuffer4lockEjPPv"); setFuncPtr(functions.unlock, library, "_ZN7android13GraphicBuffer6unlockEv"); setFuncPtr(functions.initCheck, library, "_ZNK7android13GraphicBuffer9initCheckEv"); // allocate memory for GraphicBuffer object void *const memory = malloc(GRAPHICBUFFER_SIZE); if (memory == nullptr) { std::cerr << "Could not alloc for GraphicBuffer" << std::endl; return; } try { static std::string name = std::string("DirtyHackUser"); android::GraphicBuffer* const gb = callConstructor5<android::GraphicBuffer, uint32_t, uint32_t, PixelFormat, uint32_t, std::string *>( functions.constructor, memory, width, height, format, usage, &name ); android::android_native_base_t* const base = getAndroidNativeBase(gb); status_t ctorStatus = functions.initCheck(gb); if (ctorStatus) { // ctor failed callDestructor<android::GraphicBuffer>(functions.destructor, gb); std::cerr << "GraphicBuffer ctor failed, initCheck returned " << ctorStatus << std::endl; } // check object layout if (base->magic != 0x5f626672u) // "_bfr" std::cerr << "GraphicBuffer layout unexpected" << std::endl; // check object version const uint32_t expectedVersion = sizeof(void *) == 4 ? 96 : 168; if (base->version != expectedVersion) std::cerr << "GraphicBuffer version unexpected" << std::endl; base->incRef(base); impl = gb; } catch (...) { free(memory); throw; } } GraphicBuffer::~GraphicBuffer() { if (impl) { android::android_native_base_t* const base = getAndroidNativeBase(impl); base->decRef(base); free(impl); } } status_t GraphicBuffer::lock(uint32_t usage, void** vaddr) { return functions.lock(impl, usage, vaddr); } status_t GraphicBuffer::unlock() { return functions.unlock(impl); } ANativeWindowBuffer *GraphicBuffer::getNativeBuffer() const { return functions.getNativeBuffer(impl); } uint32_t GraphicBuffer::getStride() const { return ((android::android_native_buffer_t*)getNativeBuffer())->stride; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/native_control_win.h" #include <windowsx.h> #include "app/l10n_util_win.h" #include "base/logging.h" #include "base/win_util.h" #include "views/focus/focus_manager.h" namespace views { // static const wchar_t* NativeControlWin::kNativeControlWinKey = L"__NATIVE_CONTROL_WIN__"; //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, public: NativeControlWin::NativeControlWin() { } NativeControlWin::~NativeControlWin() { HWND hwnd = native_view(); if (hwnd) { // Destroy the hwnd if it still exists. Otherwise we won't have shut things // down correctly, leading to leaking and crashing if another message // comes in for the hwnd. Detach(); DestroyWindow(hwnd); } } bool NativeControlWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { switch (message) { case WM_CONTEXTMENU: ShowContextMenu(gfx::Point(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param))); *result = 0; return true; case WM_CTLCOLORBTN: case WM_CTLCOLORSTATIC: *result = GetControlColor(message, reinterpret_cast<HDC>(w_param), native_view()); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, View overrides: void NativeControlWin::SetEnabled(bool enabled) { if (IsEnabled() != enabled) { View::SetEnabled(enabled); if (native_view()) EnableWindow(native_view(), IsEnabled()); } } void NativeControlWin::ViewHierarchyChanged(bool is_add, View* parent, View* child) { // Call the base class to hide the view if we're being removed. NativeViewHost::ViewHierarchyChanged(is_add, parent, child); // Create the HWND when we're added to a valid Widget. Many controls need a // parent HWND to function properly. if (is_add && GetWidget() && !native_view()) CreateNativeControl(); } void NativeControlWin::VisibilityChanged(View* starting_from, bool is_visible) { if (!is_visible) { // We destroy the child control HWND when we become invisible because of the // performance cost of maintaining many HWNDs. HWND hwnd = native_view(); Detach(); DestroyWindow(hwnd); } else if (!native_view()) { if (GetWidget()) CreateNativeControl(); } else { // The view becomes visible after native control is created. // Layout now. Layout(); } } void NativeControlWin::Focus() { DCHECK(native_view()); SetFocus(native_view()); // Since we are being wrapped by a view, accessibility should receive // the super class as the focused view. View* parent_view = GetParent(); // Due to some controls not behaving as expected without having // a native win32 control, we exclude the following from sending // their IAccessible as focus events. if (parent_view->GetClassName() != views::Combobox::kViewClassName && parent_view->HasFocus()) parent_view->NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS); } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, protected: void NativeControlWin::ShowContextMenu(const gfx::Point& location) { if (!GetContextMenuController()) return; if (location.x() == -1 && location.y() == -1) View::ShowContextMenu(GetKeyboardContextMenuLocation(), false); else View::ShowContextMenu(location, true); } void NativeControlWin::NativeControlCreated(HWND native_control) { // Associate this object with the control's HWND so that WidgetWin can find // this object when it receives messages from it. // Note that we never unset this property. We don't have to. SetProp(native_control, kNativeControlWinKey, this); // Subclass so we get WM_KEYDOWN and WM_SETFOCUS messages. original_wndproc_ = win_util::SetWindowProc(native_control, &NativeControlWin::NativeControlWndProc); Attach(native_control); // native_view() is now valid. // Update the newly created HWND with any resident enabled state. EnableWindow(native_view(), IsEnabled()); // This message ensures that the focus border is shown. SendMessage(native_view(), WM_CHANGEUISTATE, MAKEWPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0); } DWORD NativeControlWin::GetAdditionalExStyle() const { // If the UI for the view is mirrored, we should make sure we add the // extended window style for a right-to-left layout so the subclass creates // a mirrored HWND for the underlying control. DWORD ex_style = 0; if (base::i18n::IsRTL()) ex_style |= l10n_util::GetExtendedStyles(); return ex_style; } DWORD NativeControlWin::GetAdditionalRTLStyle() const { // If the UI for the view is mirrored, we should make sure we add the // extended window style for a right-to-left layout so the subclass creates // a mirrored HWND for the underlying control. DWORD ex_style = 0; if (base::i18n::IsRTL()) ex_style |= l10n_util::GetExtendedTooltipStyles(); return ex_style; } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, private: LRESULT NativeControlWin::GetControlColor(UINT message, HDC dc, HWND sender) { View *ancestor = this; while (ancestor) { const Background* background = ancestor->background(); if (background) { HBRUSH brush = background->GetNativeControlBrush(); if (brush) return reinterpret_cast<LRESULT>(brush); } ancestor = ancestor->GetParent(); } // COLOR_BTNFACE is the default for dialog box backgrounds. return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE)); } // static LRESULT NativeControlWin::NativeControlWndProc(HWND window, UINT message, WPARAM w_param, LPARAM l_param) { NativeControlWin* native_control = static_cast<NativeControlWin*>(GetProp(window, kNativeControlWinKey)); DCHECK(native_control); if (message == WM_KEYDOWN && native_control->OnKeyDown(static_cast<int>(w_param))) { return 0; } else if (message == WM_SETFOCUS) { // Let the focus manager know that the focus changed. FocusManager* focus_manager = native_control->GetFocusManager(); if (focus_manager) { focus_manager->SetFocusedView(native_control->focus_view()); } else { NOTREACHED(); } } else if (message == WM_DESTROY) { win_util::SetWindowProc(window, native_control->original_wndproc_); } return CallWindowProc(native_control->original_wndproc_, window, message, w_param, l_param); } } // namespace views <commit_msg>Make sure to only handle real visiblity changes in NativeViewHost.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/native_control_win.h" #include <windowsx.h> #include "app/l10n_util_win.h" #include "base/logging.h" #include "base/win_util.h" #include "views/focus/focus_manager.h" namespace views { // static const wchar_t* NativeControlWin::kNativeControlWinKey = L"__NATIVE_CONTROL_WIN__"; //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, public: NativeControlWin::NativeControlWin() { } NativeControlWin::~NativeControlWin() { HWND hwnd = native_view(); if (hwnd) { // Destroy the hwnd if it still exists. Otherwise we won't have shut things // down correctly, leading to leaking and crashing if another message // comes in for the hwnd. Detach(); DestroyWindow(hwnd); } } bool NativeControlWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { switch (message) { case WM_CONTEXTMENU: ShowContextMenu(gfx::Point(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param))); *result = 0; return true; case WM_CTLCOLORBTN: case WM_CTLCOLORSTATIC: *result = GetControlColor(message, reinterpret_cast<HDC>(w_param), native_view()); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, View overrides: void NativeControlWin::SetEnabled(bool enabled) { if (IsEnabled() != enabled) { View::SetEnabled(enabled); if (native_view()) EnableWindow(native_view(), IsEnabled()); } } void NativeControlWin::ViewHierarchyChanged(bool is_add, View* parent, View* child) { // Call the base class to hide the view if we're being removed. NativeViewHost::ViewHierarchyChanged(is_add, parent, child); // Create the HWND when we're added to a valid Widget. Many controls need a // parent HWND to function properly. if (is_add && GetWidget() && !native_view()) CreateNativeControl(); } void NativeControlWin::VisibilityChanged(View* starting_from, bool is_visible) { // We might get called due to visibility changes at any point in the // hierarchy, lets check whether we are really visible or not. bool visible = IsVisibleInRootView(); if (!visible && native_view()) { // We destroy the child control HWND when we become invisible because of the // performance cost of maintaining many HWNDs. HWND hwnd = native_view(); Detach(); DestroyWindow(hwnd); } else if (visible && !native_view()) { if (GetWidget()) CreateNativeControl(); } if (visible) { // The view becomes visible after native control is created. // Layout now. Layout(); } } void NativeControlWin::Focus() { DCHECK(native_view()); SetFocus(native_view()); // Since we are being wrapped by a view, accessibility should receive // the super class as the focused view. View* parent_view = GetParent(); // Due to some controls not behaving as expected without having // a native win32 control, we exclude the following from sending // their IAccessible as focus events. if (parent_view->GetClassName() != views::Combobox::kViewClassName && parent_view->HasFocus()) parent_view->NotifyAccessibilityEvent(AccessibilityTypes::EVENT_FOCUS); } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, protected: void NativeControlWin::ShowContextMenu(const gfx::Point& location) { if (!GetContextMenuController()) return; if (location.x() == -1 && location.y() == -1) View::ShowContextMenu(GetKeyboardContextMenuLocation(), false); else View::ShowContextMenu(location, true); } void NativeControlWin::NativeControlCreated(HWND native_control) { // Associate this object with the control's HWND so that WidgetWin can find // this object when it receives messages from it. // Note that we never unset this property. We don't have to. SetProp(native_control, kNativeControlWinKey, this); // Subclass so we get WM_KEYDOWN and WM_SETFOCUS messages. original_wndproc_ = win_util::SetWindowProc(native_control, &NativeControlWin::NativeControlWndProc); Attach(native_control); // native_view() is now valid. // Update the newly created HWND with any resident enabled state. EnableWindow(native_view(), IsEnabled()); // This message ensures that the focus border is shown. SendMessage(native_view(), WM_CHANGEUISTATE, MAKEWPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0); } DWORD NativeControlWin::GetAdditionalExStyle() const { // If the UI for the view is mirrored, we should make sure we add the // extended window style for a right-to-left layout so the subclass creates // a mirrored HWND for the underlying control. DWORD ex_style = 0; if (base::i18n::IsRTL()) ex_style |= l10n_util::GetExtendedStyles(); return ex_style; } DWORD NativeControlWin::GetAdditionalRTLStyle() const { // If the UI for the view is mirrored, we should make sure we add the // extended window style for a right-to-left layout so the subclass creates // a mirrored HWND for the underlying control. DWORD ex_style = 0; if (base::i18n::IsRTL()) ex_style |= l10n_util::GetExtendedTooltipStyles(); return ex_style; } //////////////////////////////////////////////////////////////////////////////// // NativeControlWin, private: LRESULT NativeControlWin::GetControlColor(UINT message, HDC dc, HWND sender) { View *ancestor = this; while (ancestor) { const Background* background = ancestor->background(); if (background) { HBRUSH brush = background->GetNativeControlBrush(); if (brush) return reinterpret_cast<LRESULT>(brush); } ancestor = ancestor->GetParent(); } // COLOR_BTNFACE is the default for dialog box backgrounds. return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_BTNFACE)); } // static LRESULT NativeControlWin::NativeControlWndProc(HWND window, UINT message, WPARAM w_param, LPARAM l_param) { NativeControlWin* native_control = static_cast<NativeControlWin*>(GetProp(window, kNativeControlWinKey)); DCHECK(native_control); if (message == WM_KEYDOWN && native_control->OnKeyDown(static_cast<int>(w_param))) { return 0; } else if (message == WM_SETFOCUS) { // Let the focus manager know that the focus changed. FocusManager* focus_manager = native_control->GetFocusManager(); if (focus_manager) { focus_manager->SetFocusedView(native_control->focus_view()); } else { NOTREACHED(); } } else if (message == WM_DESTROY) { win_util::SetWindowProc(window, native_control->original_wndproc_); } return CallWindowProc(native_control->original_wndproc_, window, message, w_param, l_param); } } // namespace views <|endoftext|>
<commit_before>/// HEADER #include "blob_detector.h" /// COMPONENT #include <vision_plugins/cvblob.h> /// PROJECT #include <csapex_core_plugins/vector_message.h> #include <csapex_vision/cv_mat_message.h> #include <csapex_vision/roi_message.h> #include <csapex_vision_features/keypoint_message.h> /// PROJECT #include <csapex/msg/output.h> #include <csapex/msg/input.h> #include <utils_param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/model/node_modifier.h> /// SYSTEM #include <sstream> CSAPEX_REGISTER_CLASS(csapex::BlobDetector, csapex::Node) using namespace csapex; using namespace connection_types; using namespace cvb; BlobDetector::BlobDetector() { } BlobDetector::~BlobDetector() { } #define _HSV2RGB_(H, S, V, R, G, B) \ { \ double _h = H/60.; \ int _hf = (int)floor(_h); \ int _hi = ((int)_h)%6; \ double _f = _h - _hf; \ \ double _p = V * (1. - S); \ double _q = V * (1. - _f * S); \ double _t = V * (1. - (1. - _f) * S); \ \ switch (_hi) \ { \ case 0: \ R = 255.*V; G = 255.*_t; B = 255.*_p; \ break; \ case 1: \ R = 255.*_q; G = 255.*V; B = 255.*_p; \ break; \ case 2: \ R = 255.*_p; G = 255.*V; B = 255.*_t; \ break; \ case 3: \ R = 255.*_p; G = 255.*_q; B = 255.*V; \ break; \ case 4: \ R = 255.*_t; G = 255.*_p; B = 255.*V; \ break; \ case 5: \ R = 255.*V; G = 255.*_p; B = 255.*_q; \ break; \ } \ } void BlobDetector::process() { CvMatMessage::Ptr img = input_->getMessage<CvMatMessage>(); if(img->hasChannels(1, CV_8U)) { throw std::runtime_error("image must be one channel grayscale."); } cv::Mat& gray = img->value; CvMatMessage::Ptr debug(new CvMatMessage(enc::bgr)); cv::cvtColor(gray, debug->value, CV_GRAY2BGR); CvBlobs blobs; IplImage* grayPtr = new IplImage(gray); IplImage* labelImgPtr = cvCreateImage(cvGetSize(grayPtr), IPL_DEPTH_LABEL, 1); cvLabel(grayPtr, labelImgPtr, blobs); VectorMessage::Ptr out(VectorMessage::make<RoiMessage>()); for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; RoiMessage::Ptr roi(new RoiMessage); double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); roi->value = Roi(blob.minx, blob.miny, (blob.maxx - blob.minx + 1), (blob.maxy - blob.miny + 1), color); out->value.push_back(roi); } output_->publish(out); if(output_debug_->isConnected()) { IplImage* debugPtr = new IplImage(debug->value); cvRenderBlobs(labelImgPtr, blobs, debugPtr, debugPtr); for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; const CvChainCodes& c = blob.contour.chainCode; cv::Point p = blob.contour.startingPoint; for(CvChainCodes::const_iterator i = c.begin(); i != c.end(); ++i) { const CvChainCode& chain = *i; cv::Point next = p + cv::Point(cvChainCodeMoves[chain][0], cvChainCodeMoves[chain][1]); double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); cv::line(debug->value, p, next, color, 5, CV_AA); p = next; } } for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; std::stringstream ss; ss << "Blob #" << blob.label << ": A=" << blob.area << ", C=(" << blob.centroid.x << ", " << blob.centroid.y << ")"; double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, color, 3); cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar::all(255), 1); } output_debug_->publish(debug); } cvReleaseImage(&labelImgPtr); } void BlobDetector::setup() { input_ = modifier_->addInput<CvMatMessage>("Image"); output_debug_ = modifier_->addOutput<CvMatMessage>("OutputImage"); output_ = modifier_->addOutput<VectorMessage, RoiMessage>("ROIs"); } <commit_msg>Parameter for showing the information of RoI in the image<commit_after>/// HEADER #include "blob_detector.h" /// COMPONENT #include <vision_plugins/cvblob.h> /// PROJECT #include <csapex_core_plugins/vector_message.h> #include <csapex_vision/cv_mat_message.h> #include <csapex_vision/roi_message.h> #include <csapex_vision_features/keypoint_message.h> /// PROJECT #include <csapex/msg/output.h> #include <csapex/msg/input.h> #include <utils_param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/model/node_modifier.h> /// SYSTEM #include <sstream> CSAPEX_REGISTER_CLASS(csapex::BlobDetector, csapex::Node) using namespace csapex; using namespace connection_types; using namespace cvb; BlobDetector::BlobDetector() { addParameter(param::ParameterFactory::declareBool("RoiInformation", param::ParameterDescription("Show the information of each RoI"), false)); } BlobDetector::~BlobDetector() { } #define _HSV2RGB_(H, S, V, R, G, B) \ { \ double _h = H/60.; \ int _hf = (int)floor(_h); \ int _hi = ((int)_h)%6; \ double _f = _h - _hf; \ \ double _p = V * (1. - S); \ double _q = V * (1. - _f * S); \ double _t = V * (1. - (1. - _f) * S); \ \ switch (_hi) \ { \ case 0: \ R = 255.*V; G = 255.*_t; B = 255.*_p; \ break; \ case 1: \ R = 255.*_q; G = 255.*V; B = 255.*_p; \ break; \ case 2: \ R = 255.*_p; G = 255.*V; B = 255.*_t; \ break; \ case 3: \ R = 255.*_p; G = 255.*_q; B = 255.*V; \ break; \ case 4: \ R = 255.*_t; G = 255.*_p; B = 255.*V; \ break; \ case 5: \ R = 255.*V; G = 255.*_p; B = 255.*_q; \ break; \ } \ } void BlobDetector::process() { bool roi_info = readParameter<bool>("RoiInformation"); CvMatMessage::Ptr img = input_->getMessage<CvMatMessage>(); if(img->hasChannels(1, CV_8U)) { throw std::runtime_error("image must be one channel grayscale."); } cv::Mat& gray = img->value; CvMatMessage::Ptr debug(new CvMatMessage(enc::bgr)); cv::cvtColor(gray, debug->value, CV_GRAY2BGR); CvBlobs blobs; IplImage* grayPtr = new IplImage(gray); IplImage* labelImgPtr = cvCreateImage(cvGetSize(grayPtr), IPL_DEPTH_LABEL, 1); cvLabel(grayPtr, labelImgPtr, blobs); VectorMessage::Ptr out(VectorMessage::make<RoiMessage>()); for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; RoiMessage::Ptr roi(new RoiMessage); double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); roi->value = Roi(blob.minx, blob.miny, (blob.maxx - blob.minx + 1), (blob.maxy - blob.miny + 1), color); out->value.push_back(roi); } output_->publish(out); if(output_debug_->isConnected()) { IplImage* debugPtr = new IplImage(debug->value); cvRenderBlobs(labelImgPtr, blobs, debugPtr, debugPtr); for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; const CvChainCodes& c = blob.contour.chainCode; cv::Point p = blob.contour.startingPoint; for(CvChainCodes::const_iterator i = c.begin(); i != c.end(); ++i) { const CvChainCode& chain = *i; cv::Point next = p + cv::Point(cvChainCodeMoves[chain][0], cvChainCodeMoves[chain][1]); double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); cv::line(debug->value, p, next, color, 5, CV_AA); p = next; } } if (roi_info){ for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) { const CvBlob& blob = *it->second; std::stringstream ss; ss << "Blob #" << blob.label << ": A=" << blob.area << ", C=(" << blob.centroid.x << ", " << blob.centroid.y << ")"; double r, g, b; _HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b); cv::Scalar color(b,g,r); cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, color, 3); cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar::all(255), 1); } } output_debug_->publish(debug); } cvReleaseImage(&labelImgPtr); } void BlobDetector::setup() { input_ = modifier_->addInput<CvMatMessage>("Image"); output_debug_ = modifier_->addOutput<CvMatMessage>("OutputImage"); output_ = modifier_->addOutput<VectorMessage, RoiMessage>("ROIs"); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkLevelWindowPropertySerializer_h_included #define mitkLevelWindowPropertySerializer_h_included #include "mitkBasePropertySerializer.h" #include "mitkLevelWindowProperty.h" namespace mitk { class LevelWindowPropertySerializer : public BasePropertySerializer { public: mitkClassMacro( LevelWindowPropertySerializer, BasePropertySerializer ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual TiXmlElement* Serialize() override { if (const LevelWindowProperty* prop = dynamic_cast<const LevelWindowProperty*>(m_Property.GetPointer())) { auto element = new TiXmlElement("LevelWindow"); LevelWindow lw = prop->GetLevelWindow(); std::string boolString("false"); if (lw.IsFixed() == true) boolString = "true"; element->SetAttribute("fixed", boolString.c_str()); auto child = new TiXmlElement("CurrentSettings"); element->LinkEndChild( child ); child->SetDoubleAttribute("level", lw.GetLevel()); child->SetDoubleAttribute("window", lw.GetWindow()); child = new TiXmlElement("DefaultSettings"); element->LinkEndChild( child ); child->SetDoubleAttribute("level", lw.GetDefaultLevel()); child->SetDoubleAttribute("window", lw.GetDefaultWindow()); child = new TiXmlElement("CurrentRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", lw.GetRangeMin()); child->SetDoubleAttribute("max", lw.GetRangeMax()); return element; } else return nullptr; } virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) override { if (!element) return nullptr; bool isFixed(false); if (element->Attribute("fixed")) isFixed = std::string(element->Attribute("fixed")) == "true"; float level; float window; TiXmlElement* child = element->FirstChildElement("CurrentSettings"); if ( child->QueryFloatAttribute( "level", &level ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "window", &window ) != TIXML_SUCCESS ) return nullptr; float defaultLevel; float defaultWindow; child = element->FirstChildElement("DefaultSettings"); if ( child->QueryFloatAttribute( "level", &defaultLevel ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "window", &defaultWindow ) != TIXML_SUCCESS ) return nullptr; float minRange; float maxRange; child = element->FirstChildElement("CurrentRange"); if ( child->QueryFloatAttribute( "min", &minRange ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "max", &maxRange ) != TIXML_SUCCESS ) return nullptr; LevelWindow lw; lw.SetRangeMinMax( minRange, maxRange ); lw.SetDefaultLevelWindow( defaultLevel, defaultWindow ); lw.SetLevelWindow( level, window ); lw.SetFixed( isFixed ); return LevelWindowProperty::New( lw ).GetPointer(); } protected: LevelWindowPropertySerializer() {} virtual ~LevelWindowPropertySerializer() {} }; } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') MITK_REGISTER_SERIALIZER(LevelWindowPropertySerializer); #endif <commit_msg>initialized formally uninitialized float variables which -Werror=maybe-uninitialized failed g++-compilation.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkLevelWindowPropertySerializer_h_included #define mitkLevelWindowPropertySerializer_h_included #include "mitkBasePropertySerializer.h" #include "mitkLevelWindowProperty.h" namespace mitk { class LevelWindowPropertySerializer : public BasePropertySerializer { public: mitkClassMacro( LevelWindowPropertySerializer, BasePropertySerializer ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual TiXmlElement* Serialize() override { if (const LevelWindowProperty* prop = dynamic_cast<const LevelWindowProperty*>(m_Property.GetPointer())) { auto element = new TiXmlElement("LevelWindow"); LevelWindow lw = prop->GetLevelWindow(); std::string boolString("false"); if (lw.IsFixed() == true) boolString = "true"; element->SetAttribute("fixed", boolString.c_str()); auto child = new TiXmlElement("CurrentSettings"); element->LinkEndChild( child ); child->SetDoubleAttribute("level", lw.GetLevel()); child->SetDoubleAttribute("window", lw.GetWindow()); child = new TiXmlElement("DefaultSettings"); element->LinkEndChild( child ); child->SetDoubleAttribute("level", lw.GetDefaultLevel()); child->SetDoubleAttribute("window", lw.GetDefaultWindow()); child = new TiXmlElement("CurrentRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", lw.GetRangeMin()); child->SetDoubleAttribute("max", lw.GetRangeMax()); return element; } else return nullptr; } virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) override { if (!element) return nullptr; bool isFixed(false); if (element->Attribute("fixed")) isFixed = std::string(element->Attribute("fixed")) == "true"; float level = 0; float window = 0; TiXmlElement* child = element->FirstChildElement("CurrentSettings"); if ( child->QueryFloatAttribute( "level", &level ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "window", &window ) != TIXML_SUCCESS ) return nullptr; float defaultLevel; float defaultWindow; child = element->FirstChildElement("DefaultSettings"); if ( child->QueryFloatAttribute( "level", &defaultLevel ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "window", &defaultWindow ) != TIXML_SUCCESS ) return nullptr; float minRange; float maxRange; child = element->FirstChildElement("CurrentRange"); if ( child->QueryFloatAttribute( "min", &minRange ) != TIXML_SUCCESS ) return nullptr; if ( child->QueryFloatAttribute( "max", &maxRange ) != TIXML_SUCCESS ) return nullptr; LevelWindow lw; lw.SetRangeMinMax( minRange, maxRange ); lw.SetDefaultLevelWindow( defaultLevel, defaultWindow ); lw.SetLevelWindow( level, window ); lw.SetFixed( isFixed ); return LevelWindowProperty::New( lw ).GetPointer(); } protected: LevelWindowPropertySerializer() {} virtual ~LevelWindowPropertySerializer() {} }; } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') MITK_REGISTER_SERIALIZER(LevelWindowPropertySerializer); #endif <|endoftext|>
<commit_before>// Example: exercise2-advanced // // Goal: implement a simple adaptive strategy based on exact solution // // Reference: see https://fusionforge.zih.tu-dresden.de/plugins/mediawiki/wiki/amdis/index.php/AMDiS::Expressions // for a detailed description of possible expression terms. // // Compile-and-run: // > cd build // > make exercise2b // > cd .. // > build/exercise2b init/exercise2.dat.2d // #include "AMDiS.h" #include <array> #include <boost/numeric/mtl/mtl.hpp> using namespace AMDiS; void convergence_factor(std::vector<std::array<double,2>> const& error) { mtl::dense_vector<double> rhs_res(error.size()); mtl::dense2D<double> A_res(error.size(), 2); for (size_t i = 0; i < error.size(); ++i) { rhs_res(i) = std::log(error[i][1]); A_res(i, 0) = 1; A_res(i, 1) = std::log(error[i][0]); } mtl::dense_vector<double> convergence(2); mtl::dense2D<double> Q(num_rows(A_res), num_rows(A_res)), R(num_rows(A_res), num_cols(A_res)); boost::tie(Q, R)= mtl::matrix::qr(A_res); mtl::dense_vector<double> b(trans(Q)*rhs_res); mtl::irange rows(0,num_cols(A_res)); convergence = mtl::matrix::upper_trisolve(R[rows][rows], b[rows]); std::cout << "\n|u - u_h| = C * h^k\n C = " << std::exp(convergence(0)) << "\n k = " << convergence(1) << "\n\n"; } inline double calcMeshSizes(Mesh* mesh) { TraverseStack stack; ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS); double maxH = 0.0; while (elInfo) { auto coords = elInfo->getCoords(); for (int i = 0; i < coords.getSize(); i++) for (int j = i+1; j < coords.getSize(); j++) maxH = std::max(maxH, norm(coords[i] - coords[j])); elInfo = stack.traverseNext(elInfo); } return maxH; } struct G : AbstractFunction<double, WorldVector<double> > { double operator()(WorldVector<double> const& x) const { return std::exp(-10.0*(x*x)); } }; // solve: -laplace(u) = f(x) in Omega, u = g on Gamma int main(int argc, char* argv[]) { FUNCNAME("Main"); AMDiS::init(argc, argv); // ===== create and init the scalar problem ===== ProblemStat prob("poisson"); prob.initialize(INIT_ALL); // ===== define operators ===== Operator opLaplace(prob.getFeSpace(), prob.getFeSpace()); addSOT(opLaplace, 1.0); Operator opF(prob.getFeSpace()); auto f = -(400.0*(X()*X()) - 40.0)*exp(-10.0*(X()*X())); addZOT(opF, f); // f(x) // ===== add operators to problem ===== prob.addMatrixOperator(opLaplace, 0, 0); // -laplace(u) prob.addVectorOperator(opF, 0); // f(x) // ===== add boundary conditions ===== BoundaryType nr = 1; prob.addDirichletBC(nr, 0, 0, new G); // g(x) // ===== create info-object, that holds parameters === AdaptInfo adaptInfo("adapt"); DOFVector<double>& U = *prob.getSolution(0); DOFVector<double> ErrVec(U), UExact(U); auto u_exact = exp(-10.0*(X()*X())); std::vector<std::array<double, 2>> error_vec_L2; std::vector<std::array<double, 2>> error_vec_H1; std::vector<std::array<double, 2>> error_vec_P; double error = 1.e10; for (int i = 0; i < adaptInfo.getMaxSpaceIteration(); ++i) { // ===== assemble and solve linear system ===== prob.assemble(&adaptInfo); prob.solve(&adaptInfo); ErrVec << absolute(valueOf(U) - u_exact); io::writeFile(ErrVec, "error_" + std::to_string(i) + ".vtu"); UExact << u_exact; double errorL2 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) ) ); double errorH1 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) + unary_dot(gradientOf(U) - gradientOf(UExact)) ) ); double h_max = calcMeshSizes(prob.getMesh()); WorldVector<double> p; p[0] = 0.5; p[1] = 0.5; double errorP = std::abs(U(p) - exp(-10.0*(p*p))); MSG("h(%d) = %f\n", i, h_max); MSG("errorL2(%d) = %e\n", i, errorL2); MSG("errorH1(%d) = %e\n", i, errorH1); MSG("errorP(%d) = %e\n", i, errorP); error_vec_L2.push_back({h_max, errorL2}); error_vec_H1.push_back({h_max, errorH1}); error_vec_P.push_back({h_max, errorP}); error = errorL2; if (error < adaptInfo.getSpaceTolerance(0)) break; // refine mesh RefinementManager* refManager = prob.getRefinementManager(); Flag f = refManager->globalRefine(prob.getMesh(), 1); } std::cout << "L2-norm:\n"; convergence_factor(error_vec_L2); std::cout << "H1-norm:\n"; convergence_factor(error_vec_H1); std::cout << "pointwise-norm:\n"; convergence_factor(error_vec_P); AMDiS::finalize(); } <commit_msg>init-file for ex2b added<commit_after>// Example: exercise2-advanced // // Goal: implement a simple adaptive strategy based on exact solution // // Reference: see https://fusionforge.zih.tu-dresden.de/plugins/mediawiki/wiki/amdis/index.php/AMDiS::Expressions // for a detailed description of possible expression terms. // // Compile-and-run: // > cd build // > make exercise2b // > cd .. // > build/exercise2b init/exercise2.dat.2d // #include "AMDiS.h" #include <array> #include <boost/numeric/mtl/mtl.hpp> using namespace AMDiS; void convergence_factor(std::vector<std::array<double,2>> const& error) { mtl::dense_vector<double> rhs_res(error.size()); mtl::dense2D<double> A_res(error.size(), 2); for (size_t i = 0; i < error.size(); ++i) { rhs_res(i) = std::log(error[i][1]); A_res(i, 0) = 1; A_res(i, 1) = std::log(error[i][0]); } mtl::dense_vector<double> convergence(2); mtl::dense2D<double> Q(num_rows(A_res), num_rows(A_res)), R(num_rows(A_res), num_cols(A_res)); boost::tie(Q, R)= mtl::matrix::qr(A_res); mtl::dense_vector<double> b(trans(Q)*rhs_res); mtl::irange rows(0,num_cols(A_res)); mtl::dense2D<double> R_ = R[rows][rows]; convergence = mtl::matrix::upper_trisolve(R_, b[rows]); std::cout << "\n|u - u_h| = C * h^k\n C = " << std::exp(convergence(0)) << "\n k = " << convergence(1) << "\n\n"; } inline double calcMeshSizes(Mesh* mesh) { TraverseStack stack; ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS); double maxH = 0.0; while (elInfo) { auto coords = elInfo->getCoords(); for (int i = 0; i < coords.getSize(); i++) for (int j = i+1; j < coords.getSize(); j++) maxH = std::max(maxH, norm(coords[i] - coords[j])); elInfo = stack.traverseNext(elInfo); } return maxH; } struct G : AbstractFunction<double, WorldVector<double> > { double operator()(WorldVector<double> const& x) const { return std::exp(-10.0*(x*x)); } }; // solve: -laplace(u) = f(x) in Omega, u = g on Gamma int main(int argc, char* argv[]) { FUNCNAME("Main"); AMDiS::init(argc, argv); // ===== create and init the scalar problem ===== ProblemStat prob("poisson"); prob.initialize(INIT_ALL); // ===== define operators ===== Operator opLaplace(prob.getFeSpace(), prob.getFeSpace()); addSOT(opLaplace, 1.0); Operator opF(prob.getFeSpace()); auto f = -(400.0*(X()*X()) - 40.0)*exp(-10.0*(X()*X())); addZOT(opF, f); // f(x) // ===== add operators to problem ===== prob.addMatrixOperator(opLaplace, 0, 0); // -laplace(u) prob.addVectorOperator(opF, 0); // f(x) // ===== add boundary conditions ===== BoundaryType nr = 1; prob.addDirichletBC(nr, 0, 0, new G); // g(x) // ===== create info-object, that holds parameters === AdaptInfo adaptInfo("adapt"); DOFVector<double>& U = *prob.getSolution(0); DOFVector<double> ErrVec(U), UExact(U); auto u_exact = exp(-10.0*(X()*X())); std::vector<std::array<double, 2>> error_vec_L2; std::vector<std::array<double, 2>> error_vec_H1; std::vector<std::array<double, 2>> error_vec_P; double error = 1.e10; for (int i = 0; i < adaptInfo.getMaxSpaceIteration(); ++i) { // ===== assemble and solve linear system ===== prob.assemble(&adaptInfo); prob.solve(&adaptInfo); ErrVec << absolute(valueOf(U) - u_exact); io::writeFile(ErrVec, "error_" + std::to_string(i) + ".vtu"); UExact << u_exact; double errorL2 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) ) ); double errorH1 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) + unary_dot(gradientOf(U) - gradientOf(UExact)) ) ); double h_max = calcMeshSizes(prob.getMesh()); WorldVector<double> p; p[0] = 0.5; p[1] = 0.5; double errorP = std::abs(U(p) - exp(-10.0*(p*p))); MSG("h(%d) = %f\n", i, h_max); MSG("errorL2(%d) = %e\n", i, errorL2); MSG("errorH1(%d) = %e\n", i, errorH1); MSG("errorP(%d) = %e\n", i, errorP); error_vec_L2.push_back({h_max, errorL2}); error_vec_H1.push_back({h_max, errorH1}); error_vec_P.push_back({h_max, errorP}); error = errorL2; if (error < adaptInfo.getSpaceTolerance(0)) break; // refine mesh RefinementManager* refManager = prob.getRefinementManager(); Flag f = refManager->globalRefine(prob.getMesh(), 1); } std::cout << "L2-norm:\n"; convergence_factor(error_vec_L2); std::cout << "H1-norm:\n"; convergence_factor(error_vec_H1); std::cout << "pointwise-norm:\n"; convergence_factor(error_vec_P); AMDiS::finalize(); } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@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/. */ #pragma once #include <ox/std/error.hpp> #include "desctypes.hpp" namespace ox { template<typename Reader, typename T> class DataWalker { template<typename ReaderBase, typename FH> friend ox::Error parseField(const DescriptorField &field, ReaderBase *rdr, DataWalker<ReaderBase, FH> *walker); private: Vector<const DescriptorType*> m_typeStack; T m_fieldHandler; Vector<FieldName> m_path; Vector<TypeName> m_typePath; public: DataWalker(DescriptorType *type, T fieldHandler); [[nodiscard]] const DescriptorType *type() const noexcept; ox::Error read(const DescriptorField&, Reader *rdr); protected: void pushNamePath(FieldName fn); void popNamePath(); void pushType(const DescriptorType *type); void popType(); }; template<typename Reader, typename T> DataWalker<Reader, T>::DataWalker(DescriptorType *type, T fieldHandler): m_fieldHandler(fieldHandler) { m_typeStack.push_back(type); } template<typename Reader, typename T> const DescriptorType *DataWalker<Reader, T>::type() const noexcept { return m_typeStack.back(); } template<typename Reader, typename T> ox::Error DataWalker<Reader, T>::read(const DescriptorField &f, Reader *rdr) { // get const ref of paths const auto &pathCr = m_path; const auto &typePathCr = m_typePath; return m_fieldHandler(pathCr, typePathCr, f, rdr); } template<typename Reader, typename T> void DataWalker<Reader, T>::pushNamePath(FieldName fn) { m_path.push_back(fn); } template<typename Reader, typename T> void DataWalker<Reader, T>::popNamePath() { m_path.pop_back(); } template<typename Reader, typename T> void DataWalker<Reader, T>::pushType(const DescriptorType *type) { m_typeStack.push_back(type); } template<typename Reader, typename T> void DataWalker<Reader, T>::popType() { m_typeStack.pop_back(); } template<typename Reader, typename FH> static ox::Error parseField(const DescriptorField &field, Reader *rdr, DataWalker<Reader, FH> *walker) { walker->pushNamePath(field.fieldName); if (field.subscriptLevels) { // add array handling const auto arrayLen = rdr->arrayLength(true); auto child = rdr->child(); child.setTypeInfo(field.fieldName.c_str(), arrayLen); DescriptorField f(field); // create mutable copy --f.subscriptLevels; BString<100> subscript; for (ArrayLength i = 0; i < arrayLen; i++) { subscript = "["; subscript += i; subscript += "]"; walker->pushNamePath(subscript); oxReturnError(parseField(f, &child, walker)); walker->popNamePath(); } rdr->nextField(); } else { switch (field.type->primitiveType) { case PrimitiveType::UnsignedInteger: case PrimitiveType::SignedInteger: case PrimitiveType::Bool: case PrimitiveType::String: oxReturnError(walker->read(field, rdr)); break; case PrimitiveType::Struct: if (rdr->fieldPresent()) { auto child = rdr->child(); walker->pushType(field.type); oxReturnError(ioOp(&child, walker)); walker->popType(); rdr->nextField(); } else { // skip and discard absent field int discard; oxReturnError(rdr->op("", &discard)); } break; } } walker->popNamePath(); return OxError(0); } template<typename Reader, typename FH> ox::Error ioOp(Reader *rdr, DataWalker<Reader, FH> *walker) { auto type = walker->type(); if (!type) { return OxError(1); } auto typeName = type->typeName.c_str(); auto &fields = type->fieldList; rdr->setTypeInfo(typeName, fields.size()); for (std::size_t i = 0; i < fields.size(); i++) { auto &field = fields[i]; if (field.type->primitiveType == PrimitiveType::Struct) { } oxReturnError(parseField(field, rdr, walker)); } return OxError(0); } } <commit_msg>[ox/ser] Cleanup<commit_after>/* * Copyright 2015 - 2018 gtalent2@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/. */ #pragma once #include <ox/std/error.hpp> #include "desctypes.hpp" namespace ox { template<typename Reader, typename T> class DataWalker { template<typename ReaderBase, typename FH> friend ox::Error parseField(const DescriptorField &field, ReaderBase *rdr, DataWalker<ReaderBase, FH> *walker); private: Vector<const DescriptorType*> m_typeStack; T m_fieldHandler; Vector<FieldName> m_path; Vector<TypeName> m_typePath; public: DataWalker(DescriptorType *type, T fieldHandler); [[nodiscard]] const DescriptorType *type() const noexcept; ox::Error read(const DescriptorField&, Reader *rdr); protected: void pushNamePath(FieldName fn); void popNamePath(); void pushType(const DescriptorType *type); void popType(); }; template<typename Reader, typename T> DataWalker<Reader, T>::DataWalker(DescriptorType *type, T fieldHandler): m_fieldHandler(fieldHandler) { m_typeStack.push_back(type); } template<typename Reader, typename T> const DescriptorType *DataWalker<Reader, T>::type() const noexcept { return m_typeStack.back(); } template<typename Reader, typename T> ox::Error DataWalker<Reader, T>::read(const DescriptorField &f, Reader *rdr) { // get const ref of paths const auto &pathCr = m_path; const auto &typePathCr = m_typePath; return m_fieldHandler(pathCr, typePathCr, f, rdr); } template<typename Reader, typename T> void DataWalker<Reader, T>::pushNamePath(FieldName fn) { m_path.push_back(fn); } template<typename Reader, typename T> void DataWalker<Reader, T>::popNamePath() { m_path.pop_back(); } template<typename Reader, typename T> void DataWalker<Reader, T>::pushType(const DescriptorType *type) { m_typeStack.push_back(type); } template<typename Reader, typename T> void DataWalker<Reader, T>::popType() { m_typeStack.pop_back(); } template<typename Reader, typename FH> static ox::Error parseField(const DescriptorField &field, Reader *rdr, DataWalker<Reader, FH> *walker) { walker->pushNamePath(field.fieldName); if (field.subscriptLevels) { // add array handling const auto arrayLen = rdr->arrayLength(true); auto child = rdr->child(); child.setTypeInfo(field.fieldName.c_str(), arrayLen); DescriptorField f(field); // create mutable copy --f.subscriptLevels; BString<100> subscript; for (ArrayLength i = 0; i < arrayLen; i++) { subscript = "["; subscript += i; subscript += "]"; walker->pushNamePath(subscript); oxReturnError(parseField(f, &child, walker)); walker->popNamePath(); } rdr->nextField(); } else { switch (field.type->primitiveType) { case PrimitiveType::UnsignedInteger: case PrimitiveType::SignedInteger: case PrimitiveType::Bool: case PrimitiveType::String: oxReturnError(walker->read(field, rdr)); break; case PrimitiveType::Struct: if (rdr->fieldPresent()) { auto child = rdr->child(); walker->pushType(field.type); oxReturnError(ioOp(&child, walker)); walker->popType(); rdr->nextField(); } else { // skip and discard absent field int discard; oxReturnError(rdr->op("", &discard)); } break; } } walker->popNamePath(); return OxError(0); } template<typename Reader, typename FH> ox::Error ioOp(Reader *rdr, DataWalker<Reader, FH> *walker) { auto type = walker->type(); if (!type) { return OxError(1); } auto typeName = type->typeName.c_str(); auto &fields = type->fieldList; rdr->setTypeInfo(typeName, fields.size()); for (std::size_t i = 0; i < fields.size(); i++) { oxReturnError(parseField(fields[i], rdr, walker)); } return OxError(0); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "after_initialization_fixture.h" #include "test/testsupport/fileutils.h" namespace { const int kSampleRateHz = 16000; const int kTestDurationMs = 1000; const int kSkipOutputMs = 50; const int16_t kInputValue = 15000; const int16_t kSilenceValue = 0; } // namespace class FileBeforeStreamingTest : public AfterInitializationFixture { protected: FileBeforeStreamingTest() : input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"), output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") { } void SetUp() { channel_ = voe_base_->CreateChannel(); } void TearDown() { voe_base_->DeleteChannel(channel_); } // TODO(andrew): consolidate below methods in a shared place? // Generate input file with constant values as |kInputValue|. The file // will be one second longer than the duration of the test. void GenerateInputFile() { FILE* input_file = fopen(input_filename_.c_str(), "wb"); ASSERT_TRUE(input_file != NULL); for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) { ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file)); } ASSERT_EQ(0, fclose(input_file)); } void RecordOutput() { // Start recording the mixed output for |kTestDurationMs| long. EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1, output_filename_.c_str())); Sleep(kTestDurationMs); EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1)); } void VerifyOutput(int16_t target_value) { FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); int16_t output_value = 0; int samples_read = 0; // Skip the first segment to avoid initialization and ramping-in effects. EXPECT_EQ(0, fseek(output_file, sizeof(output_value) * kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET)); while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) { samples_read++; EXPECT_EQ(output_value, target_value); } // Ensure the recording length is close to the duration of the test. ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs); // Ensure we read the entire file. ASSERT_NE(0, feof(output_file)); ASSERT_EQ(0, fclose(output_file)); } void VerifyEmptyOutput() { FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); ASSERT_EQ(0, fseek(output_file, 0, SEEK_END)); EXPECT_EQ(0, ftell(output_file)); ASSERT_EQ(0, fclose(output_file)); } int channel_; const std::string input_filename_; const std::string output_filename_; }; // This test case is to ensure that StartPlayingFileLocally() and // StartPlayout() can be called in any order. // A DC signal is used as input. And the output of mixer is supposed to be: // 1. the same DC signal if file is played out, // 2. total silence if file is not played out, // 3. no output if playout is not started. TEST_F(FileBeforeStreamingTest, TestStartPlayingFileLocallyWithStartPlayout) { GenerateInputFile(); TEST_LOG("Playout is not started. File will not be played out.\n"); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally( channel_, input_filename_.c_str(), true)); EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyEmptyOutput(); TEST_LOG("Playout is now started. File will be played out.\n"); EXPECT_EQ(0, voe_base_->StartPlayout(channel_)); RecordOutput(); VerifyOutput(kInputValue); TEST_LOG("Stop playing file. Only silence will be played out.\n"); EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_)); EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyOutput(kSilenceValue); TEST_LOG("Start playing file again. File will be played out.\n"); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally( channel_, input_filename_.c_str(), true)); EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyOutput(kInputValue); EXPECT_EQ(0, voe_base_->StopPlayout(channel_)); EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_)); } <commit_msg>Disabled FileBeforeStreamingTest.TestStartPlayingFileLocallyWithStartPlayout.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "after_initialization_fixture.h" #include "test/testsupport/fileutils.h" namespace { const int kSampleRateHz = 16000; const int kTestDurationMs = 1000; const int kSkipOutputMs = 50; const int16_t kInputValue = 15000; const int16_t kSilenceValue = 0; } // namespace class FileBeforeStreamingTest : public AfterInitializationFixture { protected: FileBeforeStreamingTest() : input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"), output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") { } void SetUp() { channel_ = voe_base_->CreateChannel(); } void TearDown() { voe_base_->DeleteChannel(channel_); } // TODO(andrew): consolidate below methods in a shared place? // Generate input file with constant values as |kInputValue|. The file // will be one second longer than the duration of the test. void GenerateInputFile() { FILE* input_file = fopen(input_filename_.c_str(), "wb"); ASSERT_TRUE(input_file != NULL); for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) { ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file)); } ASSERT_EQ(0, fclose(input_file)); } void RecordOutput() { // Start recording the mixed output for |kTestDurationMs| long. EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1, output_filename_.c_str())); Sleep(kTestDurationMs); EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1)); } void VerifyOutput(int16_t target_value) { FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); int16_t output_value = 0; int samples_read = 0; // Skip the first segment to avoid initialization and ramping-in effects. EXPECT_EQ(0, fseek(output_file, sizeof(output_value) * kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET)); while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) { samples_read++; EXPECT_EQ(output_value, target_value); } // Ensure the recording length is close to the duration of the test. ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs); // Ensure we read the entire file. ASSERT_NE(0, feof(output_file)); ASSERT_EQ(0, fclose(output_file)); } void VerifyEmptyOutput() { FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); ASSERT_EQ(0, fseek(output_file, 0, SEEK_END)); EXPECT_EQ(0, ftell(output_file)); ASSERT_EQ(0, fclose(output_file)); } int channel_; const std::string input_filename_; const std::string output_filename_; }; // This test case is to ensure that StartPlayingFileLocally() and // StartPlayout() can be called in any order. // A DC signal is used as input. And the output of mixer is supposed to be: // 1. the same DC signal if file is played out, // 2. total silence if file is not played out, // 3. no output if playout is not started. TEST_F(FileBeforeStreamingTest, DISABLED_TestStartPlayingFileLocallyWithStartPlayout) { GenerateInputFile(); TEST_LOG("Playout is not started. File will not be played out.\n"); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally( channel_, input_filename_.c_str(), true)); EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyEmptyOutput(); TEST_LOG("Playout is now started. File will be played out.\n"); EXPECT_EQ(0, voe_base_->StartPlayout(channel_)); RecordOutput(); VerifyOutput(kInputValue); TEST_LOG("Stop playing file. Only silence will be played out.\n"); EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_)); EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyOutput(kSilenceValue); TEST_LOG("Start playing file again. File will be played out.\n"); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally( channel_, input_filename_.c_str(), true)); EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_)); RecordOutput(); VerifyOutput(kInputValue); EXPECT_EQ(0, voe_base_->StopPlayout(channel_)); EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_)); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 James Hughes. 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. */ /// \author James Hughes /// \date December 2013 #ifndef IAUNS_GLM_AABB_HPP #define IAUNS_GLM_AABB_HPP #include <glm/glm.hpp> namespace CPM_GLM_AABB_NS { /// Standalone axis aligned bounding box implemented built on top of GLM. class AABB { public: /// Builds a null AABB. AABB(); /// Builds an AABB that encompasses a sphere of \p radius and \p center. AABB(const glm::vec3& center, glm::float_t radius); /// Builds an AABB that contains the two points. AABB(const glm::vec3& p1, const glm::vec3& p2); /// Copy constructor. AABB(const AABB& aabb); ~AABB(); /// Set the AABB as NULL (not set). void setNull() {mMin = glm::vec3(1.0); mMax = glm::vec3(-1.0);} /// Returns true if AABB is NULL (not set). bool isNull() const {return mMin.x > mMax.x || mMin.y > mMax.y || mMin.z > mMax.z;} /// Extend the bounding box on all sides by \p val. void extend(glm::float_t val); /// Expand the AABB to include point \p p. void extend(const glm::vec3& p); /// Expand the AABB to include a sphere centered at \p p and of radius \p /// radius. void extend(const glm::vec3& p, glm::float_t radius); /// Expand the AABB to encompass the given AABB. void extend(const AABB& aabb); /// Expand the AABB to include a disk centered at \p center, with normal \p /// normal, and radius \p radius. /// \todo Untested -- This function is not represented in our unit tests. void extendDisk(const glm::vec3& center, const glm::vec3& normal, glm::float_t radius); /// Translates AABB by vector \p v. void translate(const glm::vec3& v); /// Scale the AABB by \p scale, centered around \p origin. void scale(const glm::vec3& scale, const glm::vec3& origin); /// Retrieves the center of the AABB. glm::vec3 getCenter() const; /// Retrieves the diagonal vector (computed as mMax - mMin). /// If the AABB is NULL, then a vector of all zeros is returned. glm::vec3 getDiagonal() const; /// Retrieves the longest edge. /// If the AABB is NULL, then 0 is returned. glm::float_t getLongestEdge() const; /// Retrieves the shortest edge. /// If the AABB is NULL, then 0 is returned. glm::float_t getShortestEdge() const; /// Retrieves the AABB's minimum point. glm::vec3 getMin() const {return mMin;} /// Retrieves the AABB's maximum point. glm::vec3 getMax() const {return mMax;} /// Returns true if AABBs share a face overlap. /// \todo Untested -- This function is not represented in our unit tests. bool overlaps(const AABB& bb) const; /// Type returned from call to intersect. enum INTERSECTION_TYPE { INSIDE, INTERSECT, OUTSIDE }; /// Returns one of the intersection types. If either of the aabbs are invalid, /// then OUTSIDE is returned. INTERSECTION_TYPE intersect(const AABB& bb) const; /// Function from SCIRun. Here is a summary of SCIRun's description: /// Returns true if the two AABB's are similar. If diff is 1.0, the two /// bboxes have to have about 50% overlap each for x,y,z. If diff is 0.0, /// they have to have 100% overlap. /// If either of the two AABBs is NULL, then false is returned. /// \todo Untested -- This function is not represented in our unit tests. bool isSimilarTo(const AABB& b, glm::float_t diff = 0.5) const; protected: glm::vec3 mMin; glm::vec3 mMax; }; } // namespace CPM_GLM_AABB_NS #endif <commit_msg>Description for parameters.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 James Hughes. 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. */ /// \author James Hughes /// \date December 2013 #ifndef IAUNS_GLM_AABB_HPP #define IAUNS_GLM_AABB_HPP #include <glm/glm.hpp> namespace CPM_GLM_AABB_NS { /// Standalone axis aligned bounding box implemented built on top of GLM. class AABB { public: /// Builds a null AABB. AABB(); /// Builds an AABB that encompasses a sphere of \p radius and \p center. AABB(const glm::vec3& center, glm::float_t radius); /// Builds an AABB that contains the two points. AABB(const glm::vec3& p1, const glm::vec3& p2); /// Copy constructor. AABB(const AABB& aabb); ~AABB(); /// Set the AABB as NULL (not set). void setNull() {mMin = glm::vec3(1.0); mMax = glm::vec3(-1.0);} /// Returns true if AABB is NULL (not set). bool isNull() const {return mMin.x > mMax.x || mMin.y > mMax.y || mMin.z > mMax.z;} /// Extend the bounding box on all sides by \p val. void extend(glm::float_t val); /// Expand the AABB to include point \p p. void extend(const glm::vec3& p); /// Expand the AABB to include a sphere centered at \p p and of radius \p /// radius. void extend(const glm::vec3& p, glm::float_t radius); /// Expand the AABB to encompass the given AABB. void extend(const AABB& aabb); /// Expand the AABB to include a disk centered at \p center, with normal \p /// normal, and radius \p radius. /// \todo Untested -- This function is not represented in our unit tests. void extendDisk(const glm::vec3& center, const glm::vec3& normal, glm::float_t radius); /// Translates AABB by vector \p v. void translate(const glm::vec3& v); /// Scale the AABB by \p scale, centered around \p origin. void scale(const glm::vec3& scale, const glm::vec3& origin); /// Retrieves the center of the AABB. glm::vec3 getCenter() const; /// Retrieves the diagonal vector (computed as mMax - mMin). /// If the AABB is NULL, then a vector of all zeros is returned. glm::vec3 getDiagonal() const; /// Retrieves the longest edge. /// If the AABB is NULL, then 0 is returned. glm::float_t getLongestEdge() const; /// Retrieves the shortest edge. /// If the AABB is NULL, then 0 is returned. glm::float_t getShortestEdge() const; /// Retrieves the AABB's minimum point. glm::vec3 getMin() const {return mMin;} /// Retrieves the AABB's maximum point. glm::vec3 getMax() const {return mMax;} /// Returns true if AABBs share a face overlap. /// \todo Untested -- This function is not represented in our unit tests. bool overlaps(const AABB& bb) const; /// Type returned from call to intersect. enum INTERSECTION_TYPE { INSIDE, INTERSECT, OUTSIDE }; /// Returns one of the intersection types. If either of the aabbs are invalid, /// then OUTSIDE is returned. INTERSECTION_TYPE intersect(const AABB& bb) const; /// Function from SCIRun. Here is a summary of SCIRun's description: /// Returns true if the two AABB's are similar. If diff is 1.0, the two /// bboxes have to have about 50% overlap each for x,y,z. If diff is 0.0, /// they have to have 100% overlap. /// If either of the two AABBs is NULL, then false is returned. /// \todo Untested -- This function is not represented in our unit tests. bool isSimilarTo(const AABB& b, glm::float_t diff = 0.5) const; protected: glm::vec3 mMin; ///< Minimum point. glm::vec3 mMax; ///< Maximum point. }; } // namespace CPM_GLM_AABB_NS #endif <|endoftext|>
<commit_before>#include <glib.h> #include <qpid/messaging/Message.h> #include <qpid/messaging/Receiver.h> #include <qpid/messaging/Sender.h> #include <qpid/messaging/Session.h> #include <gqpidreceiver.h> #include <gqpidmessage.h> using namespace qpid::messaging; struct _GQpidReceiver { Receiver rcv; _GQpidReceiver (Session &s, const gchar *add) { rcv = s.createReceiver (add); } }; GQpidReceiver* g_qpid_receiver_new (Session &s, const gchar *add) { GQpidReceiver *rcv; rcv = new GQpidReceiver (s, add); return rcv; } /** * g_qpid_receiver_fetch: * @rcv: a #GQpidReceiver* object * @duration: number of seconds as duration, pass -1 for * FOREVER waiting. * * Fetches a message. * * Return value: a new created #GQpidMessage* instance. **/ GQpidMessage* g_qpid_receiver_fetch (GQpidReceiver *rcv, int duration) { g_return_val_if_fail (rcv !=NULL, NULL); Message m = rcv->rcv.fetch (Duration::SECOND * duration); return g_qpid_message_new_from_msg (m); } <commit_msg>g_qpid_receiver_fetch: pass -1 as duration for FOREVER wait.<commit_after>#include <glib.h> #include <qpid/messaging/Message.h> #include <qpid/messaging/Receiver.h> #include <qpid/messaging/Sender.h> #include <qpid/messaging/Session.h> #include <gqpidreceiver.h> #include <gqpidmessage.h> using namespace qpid::messaging; struct _GQpidReceiver { Receiver rcv; _GQpidReceiver (Session &s, const gchar *add) { rcv = s.createReceiver (add); } }; GQpidReceiver* g_qpid_receiver_new (Session &s, const gchar *add) { GQpidReceiver *rcv; rcv = new GQpidReceiver (s, add); return rcv; } /** * g_qpid_receiver_fetch: * @rcv: a #GQpidReceiver* object * @duration: number of seconds as duration, pass -1 for * FOREVER waiting. * * Fetches a message. * * Return value: a new created #GQpidMessage* instance. **/ GQpidMessage* g_qpid_receiver_fetch (GQpidReceiver *rcv, int duration) { g_return_val_if_fail (rcv !=NULL, NULL); if (duration == -1) { Message m = rcv->rcv.fetch (Duration::FOREVER); return g_qpid_message_new_from_msg (m); } Message m = rcv->rcv.fetch (Duration::SECOND * duration); return g_qpid_message_new_from_msg (m); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkItkImageWrite.h" #include "mitkImage.h" #include "mitkImageTimeSelector.h" #include "mitkImageAccessByItk.h" #include "mitkPicFileWriter.h" #include <itksys/SystemTools.hxx> #include <sstream> mitk::ImageWriter::ImageWriter() { this->SetNumberOfRequiredInputs( 1 ); m_MimeType = ""; SetDefaultExtension(); } mitk::ImageWriter::~ImageWriter() { } void mitk::ImageWriter::SetDefaultExtension() { m_Extension = ".mhd"; } #include <vtkConfigure.h> #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) #include <vtkImageData.h> #include <vtkXMLImageDataWriter.h> static void writeVti(const char * filename, mitk::Image* image, int t=0) { vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New(); vtkwriter->SetFileName( filename ); vtkwriter->SetInput(image->GetVtkImageData(t)); vtkwriter->Write(); vtkwriter->Delete(); } #endif void mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& filename) { if(image->GetPixelType().GetNumberOfComponents()==1) { AccessByItk_1( image, _mitkItkImageWrite, filename ); } //// Extension for RGB (and maybe also for vector types) //// Does not work yet, see bug 320 and mitkImageCastPart2.cpp //else //if(image->GetPixelType().GetNumberOfComponents()==3) //{ // const std::type_info& typeId=*(image)->GetPixelType().GetTypeId(); // if ( typeId == typeid(unsigned char) ) // { // if(image->GetDimension()==2) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 2> itkImageRGBUC2; // itkImageRGBUC2::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // else // if(image->GetDimension()==3) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 3> itkImageRGBUC3; // itkImageRGBUC3::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // } // else // { // itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==3 that " // << "have pixeltype " << typeId.name() << " using ITK writers ."); // } //} else { itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==" << image->GetPixelType().GetNumberOfComponents() << " using ITK writers ."); } } void mitk::ImageWriter::GenerateData() { if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } FILE* tempFile = fopen(m_FileName.c_str(),"w"); if (tempFile==NULL) { itkExceptionMacro(<<"File location not writeable"); return; } fclose(tempFile); remove(m_FileName.c_str()); mitk::Image::Pointer input = const_cast<mitk::Image*>(this->GetInput()); #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) bool vti = (m_Extension.find(".vti") != std::string::npos); #endif if ( m_Extension.find(".pic") == std::string::npos ) { if(input->GetDimension() > 3) { int t, timesteps; timesteps = input->GetDimension(3); ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(input); mitk::Image::Pointer image = timeSelector->GetOutput(); for(t = 0; t < timesteps; ++t) { ::itk::OStringStream filename; timeSelector->SetTimeNr(t); timeSelector->Update(); if(input->GetTimeSlicedGeometry()->IsValidTime(t)) { const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds(); filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" << std::setprecision(0) << timebounds[1] << "_T" << t << m_Extension; } else { itkWarningMacro(<<"Error on write: TimeSlicedGeometry invalid of image " << filename << "."); filename << m_FileName.c_str() << "_T" << t << m_Extension; } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) if ( vti ) { writeVti(filename.str().c_str(), input, t); } else #endif { WriteByITK(input, filename.str()); } } } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) else if ( vti ) { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; writeVti(filename.str().c_str(), input); } #endif else { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; WriteByITK(input, filename.str()); } } else { PicFileWriter::Pointer picWriter = PicFileWriter::New(); size_t found; found = m_FileName.find( m_Extension ); // !!! HAS to be at the very end of the filename (not somewhere in the middle) if( m_FileName.length() > 3 && found != m_FileName.length() - 4 ) { //if Extension not in Filename ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; picWriter->SetFileName( filename.str().c_str() ); } else picWriter->SetFileName( m_FileName.c_str() ); picWriter->SetInput( input ); picWriter->Write(); } m_MimeType = "application/MITK.Pic"; } bool mitk::ImageWriter::CanWriteDataType( DataTreeNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( data ); if( image.IsNotNull() ) { //"SetDefaultExtension()" set m_Extension to ".mhd" ????? m_Extension = ".pic"; return true; } } } return false; } void mitk::ImageWriter::SetInput( DataTreeNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::Image*>( input->GetData() ) ); } std::string mitk::ImageWriter::GetWritenMIMEType() { return m_MimeType; } std::vector<std::string> mitk::ImageWriter::GetPossibleFileExtensions() { std::vector<std::string> possibleFileExtensions; possibleFileExtensions.push_back(".pic"); possibleFileExtensions.push_back(".bmp"); possibleFileExtensions.push_back(".dcm"); possibleFileExtensions.push_back(".DCM"); possibleFileExtensions.push_back(".dicom"); possibleFileExtensions.push_back(".DICOM"); possibleFileExtensions.push_back(".gipl"); possibleFileExtensions.push_back(".gipl.gz"); possibleFileExtensions.push_back(".mha"); possibleFileExtensions.push_back(".nii"); possibleFileExtensions.push_back(".nrrd"); possibleFileExtensions.push_back(".nhdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".PNG"); possibleFileExtensions.push_back(".spr"); possibleFileExtensions.push_back(".mhd"); possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".vti"); possibleFileExtensions.push_back(".hdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".tif"); possibleFileExtensions.push_back(".jpg"); return possibleFileExtensions; } std::string mitk::ImageWriter::GetFileExtension() { return m_Extension; } void mitk::ImageWriter::SetInput( mitk::Image* image ) { this->ProcessObject::SetNthInput( 0, image ); } const mitk::Image* mitk::ImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) ); } } <commit_msg>CHG (#2724): ImageWriter updates m_FileName if it decides to add the extension.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkItkImageWrite.h" #include "mitkImage.h" #include "mitkImageTimeSelector.h" #include "mitkImageAccessByItk.h" #include "mitkPicFileWriter.h" #include <itksys/SystemTools.hxx> #include <sstream> mitk::ImageWriter::ImageWriter() { this->SetNumberOfRequiredInputs( 1 ); m_MimeType = ""; SetDefaultExtension(); } mitk::ImageWriter::~ImageWriter() { } void mitk::ImageWriter::SetDefaultExtension() { m_Extension = ".mhd"; } #include <vtkConfigure.h> #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) #include <vtkImageData.h> #include <vtkXMLImageDataWriter.h> static void writeVti(const char * filename, mitk::Image* image, int t=0) { vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New(); vtkwriter->SetFileName( filename ); vtkwriter->SetInput(image->GetVtkImageData(t)); vtkwriter->Write(); vtkwriter->Delete(); } #endif void mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& filename) { if(image->GetPixelType().GetNumberOfComponents()==1) { AccessByItk_1( image, _mitkItkImageWrite, filename ); } //// Extension for RGB (and maybe also for vector types) //// Does not work yet, see bug 320 and mitkImageCastPart2.cpp //else //if(image->GetPixelType().GetNumberOfComponents()==3) //{ // const std::type_info& typeId=*(image)->GetPixelType().GetTypeId(); // if ( typeId == typeid(unsigned char) ) // { // if(image->GetDimension()==2) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 2> itkImageRGBUC2; // itkImageRGBUC2::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // else // if(image->GetDimension()==3) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 3> itkImageRGBUC3; // itkImageRGBUC3::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // } // else // { // itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==3 that " // << "have pixeltype " << typeId.name() << " using ITK writers ."); // } //} else { itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==" << image->GetPixelType().GetNumberOfComponents() << " using ITK writers ."); } } void mitk::ImageWriter::GenerateData() { if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } FILE* tempFile = fopen(m_FileName.c_str(),"w"); if (tempFile==NULL) { itkExceptionMacro(<<"File location not writeable"); return; } fclose(tempFile); remove(m_FileName.c_str()); mitk::Image::Pointer input = const_cast<mitk::Image*>(this->GetInput()); #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) bool vti = (m_Extension.find(".vti") != std::string::npos); #endif if ( m_Extension.find(".pic") == std::string::npos ) { if(input->GetDimension() > 3) { int t, timesteps; timesteps = input->GetDimension(3); ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(input); mitk::Image::Pointer image = timeSelector->GetOutput(); for(t = 0; t < timesteps; ++t) { ::itk::OStringStream filename; timeSelector->SetTimeNr(t); timeSelector->Update(); if(input->GetTimeSlicedGeometry()->IsValidTime(t)) { const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds(); filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" << std::setprecision(0) << timebounds[1] << "_T" << t << m_Extension; } else { itkWarningMacro(<<"Error on write: TimeSlicedGeometry invalid of image " << filename << "."); filename << m_FileName.c_str() << "_T" << t << m_Extension; } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) if ( vti ) { writeVti(filename.str().c_str(), input, t); } else #endif { WriteByITK(input, filename.str()); } } } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) else if ( vti ) { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; writeVti(filename.str().c_str(), input); } #endif else { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; WriteByITK(input, filename.str()); } } else { PicFileWriter::Pointer picWriter = PicFileWriter::New(); size_t found; found = m_FileName.find( m_Extension ); // !!! HAS to be at the very end of the filename (not somewhere in the middle) if( m_FileName.length() > 3 && found != m_FileName.length() - 4 ) { //if Extension not in Filename ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; m_FileName = filename.str().c_str(); } picWriter->SetFileName( m_FileName.c_str() ); picWriter->SetInput( input ); picWriter->Write(); } m_MimeType = "application/MITK.Pic"; } bool mitk::ImageWriter::CanWriteDataType( DataTreeNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( data ); if( image.IsNotNull() ) { //"SetDefaultExtension()" set m_Extension to ".mhd" ????? m_Extension = ".pic"; return true; } } } return false; } void mitk::ImageWriter::SetInput( DataTreeNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::Image*>( input->GetData() ) ); } std::string mitk::ImageWriter::GetWritenMIMEType() { return m_MimeType; } std::vector<std::string> mitk::ImageWriter::GetPossibleFileExtensions() { std::vector<std::string> possibleFileExtensions; possibleFileExtensions.push_back(".pic"); possibleFileExtensions.push_back(".bmp"); possibleFileExtensions.push_back(".dcm"); possibleFileExtensions.push_back(".DCM"); possibleFileExtensions.push_back(".dicom"); possibleFileExtensions.push_back(".DICOM"); possibleFileExtensions.push_back(".gipl"); possibleFileExtensions.push_back(".gipl.gz"); possibleFileExtensions.push_back(".mha"); possibleFileExtensions.push_back(".nii"); possibleFileExtensions.push_back(".nrrd"); possibleFileExtensions.push_back(".nhdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".PNG"); possibleFileExtensions.push_back(".spr"); possibleFileExtensions.push_back(".mhd"); possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".vti"); possibleFileExtensions.push_back(".hdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".tif"); possibleFileExtensions.push_back(".jpg"); return possibleFileExtensions; } std::string mitk::ImageWriter::GetFileExtension() { return m_Extension; } void mitk::ImageWriter::SetInput( mitk::Image* image ) { this->ProcessObject::SetNthInput( 0, image ); } const mitk::Image* mitk::ImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) ); } } <|endoftext|>
<commit_before>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "GenericHDF5Format.h" #include <DataExchangeFormat.h> #include <h5cpp/h5readwrite.h> #include <h5cpp/h5vtktypemaps.h> #include <QComboBox> #include <QDialog> #include <QDialogButtonBox> #include <QLabel> #include <QVBoxLayout> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <string> #include <vector> #include <iostream> namespace tomviz { template <typename T> void ReorderArrayC(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(i * dim[1] + j) * dim[2] + k] = in[(k * dim[1] + j) * dim[0] + i]; } } } } template <typename T> void ReorderArrayF(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(k * dim[1] + j) * dim[0] + i] = in[(i * dim[1] + j) * dim[2] + k]; } } } } bool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); // Check if one of the dimensions is greater than 1100 // If so, we will use a stride of 2. // TODO: make this an option in the UI int stride = 1; for (const auto& dim : dims) { if (dim > 1100) { stride = 2; std::cout << "Using a stride of " << stride << " because the data " << "set is very large\n"; break; } } // Re-shape the dimensions according to the stride for (auto& dim : dims) dim /= stride; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&dims[0]); tmp->AllocateScalars(vtkDataType, 1); image->SetDimensions(&dims[0]); image->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride)) { std::cerr << "Failed to read the data\n"; return false; } // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0); switch (image->GetPointData()->GetScalars()->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &dims[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image) { using h5::H5ReadWrite; H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly; H5ReadWrite reader(fileName.c_str(), mode); // If /exchange/data is a dataset, assume this is a DataExchangeFormat if (reader.isDataSet("/exchange/data")) { reader.close(); DataExchangeFormat deFormat; return deFormat.read(fileName, image); } // Find all 3D datasets. If there is more than one, have the user choose. std::vector<std::string> datasets = reader.allDataSets(); for (auto it = datasets.begin(); it != datasets.end();) { // Remove all non-3D datasets std::vector<int> dims = reader.getDimensions(*it); if (dims.size() != 3) datasets.erase(it); else ++it; } if (datasets.empty()) { std::cerr << "No 3D datasets found in " << fileName.c_str() << "\n"; return false; } std::string dataNode = datasets[0]; if (datasets.size() != 1) { // If there is more than one dataset, have the user choose one QDialog dialog; QVBoxLayout layout; dialog.setLayout(&layout); dialog.setWindowTitle("Choose volume"); QLabel label("Choose volume to load:"); layout.addWidget(&label); QComboBox combo; for (const auto& dataset : datasets) combo.addItem(dataset.c_str()); layout.addWidget(&combo); QDialogButtonBox okButton(QDialogButtonBox::Ok); layout.addWidget(&okButton); layout.setAlignment(&okButton, Qt::AlignCenter); QObject::connect(&okButton, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); dialog.exec(); dataNode = datasets[combo.currentIndex()]; } return GenericHDF5Format::readVolume(reader, dataNode, image); } } // namespace tomviz <commit_msg>Allow user to choose stride for big HDF5 data<commit_after>/* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "GenericHDF5Format.h" #include <DataExchangeFormat.h> #include <h5cpp/h5readwrite.h> #include <h5cpp/h5vtktypemaps.h> #include <QComboBox> #include <QDialog> #include <QDialogButtonBox> #include <QInputDialog> #include <QLabel> #include <QVBoxLayout> #include <vtkDataArray.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <string> #include <vector> #include <iostream> namespace tomviz { template <typename T> void ReorderArrayC(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(i * dim[1] + j) * dim[2] + k] = in[(k * dim[1] + j) * dim[0] + i]; } } } } template <typename T> void ReorderArrayF(T* in, T* out, int dim[3]) { for (int i = 0; i < dim[0]; ++i) { for (int j = 0; j < dim[1]; ++j) { for (int k = 0; k < dim[2]; ++k) { out[(k * dim[1] + j) * dim[0] + i] = in[(i * dim[1] + j) * dim[2] + k]; } } } } bool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader, const std::string& path, vtkImageData* image) { // Get the type of the data h5::H5ReadWrite::DataType type = reader.dataType(path); int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type); // Get the dimensions std::vector<int> dims = reader.getDimensions(path); // Check if one of the dimensions is greater than 1200. // If so, ask the user to choose a stride. int stride = 1; for (const auto& dim : dims) { if (dim > 1200) { bool ok; stride = QInputDialog::getInt(nullptr, "Large Dataset", "Choose Stride", 1, 1, 1e5, 1, &ok); if (!ok) return false; break; } } // Re-shape the dimensions according to the stride for (auto& dim : dims) dim /= stride; vtkNew<vtkImageData> tmp; tmp->SetDimensions(&dims[0]); tmp->AllocateScalars(vtkDataType, 1); image->SetDimensions(&dims[0]); image->AllocateScalars(vtkDataType, 1); if (!reader.readData(path, type, tmp->GetScalarPointer(), stride)) { std::cerr << "Failed to read the data\n"; return false; } // HDF5 typically stores data as row major order. // VTK expects column major order. auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0); auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0); switch (image->GetPointData()->GetScalars()->GetDataType()) { vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr), reinterpret_cast<VTK_TT*>(outPtr), &dims[0])); default: cout << "Generic HDF5 Format: Unknown data type" << endl; } image->Modified(); return true; } bool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image) { using h5::H5ReadWrite; H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly; H5ReadWrite reader(fileName.c_str(), mode); // If /exchange/data is a dataset, assume this is a DataExchangeFormat if (reader.isDataSet("/exchange/data")) { reader.close(); DataExchangeFormat deFormat; return deFormat.read(fileName, image); } // Find all 3D datasets. If there is more than one, have the user choose. std::vector<std::string> datasets = reader.allDataSets(); for (auto it = datasets.begin(); it != datasets.end();) { // Remove all non-3D datasets std::vector<int> dims = reader.getDimensions(*it); if (dims.size() != 3) datasets.erase(it); else ++it; } if (datasets.empty()) { std::cerr << "No 3D datasets found in " << fileName.c_str() << "\n"; return false; } std::string dataNode = datasets[0]; if (datasets.size() != 1) { // If there is more than one dataset, have the user choose one QDialog dialog; QVBoxLayout layout; dialog.setLayout(&layout); dialog.setWindowTitle("Choose volume"); QLabel label("Choose volume to load:"); layout.addWidget(&label); QComboBox combo; for (const auto& dataset : datasets) combo.addItem(dataset.c_str()); layout.addWidget(&combo); QDialogButtonBox okButton(QDialogButtonBox::Ok); layout.addWidget(&okButton); layout.setAlignment(&okButton, Qt::AlignCenter); QObject::connect(&okButton, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); dialog.exec(); dataNode = datasets[combo.currentIndex()]; } return GenericHDF5Format::readVolume(reader, dataNode, image); } } // namespace tomviz <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "LoadStackReaction.h" #include "DataSource.h" #include "ImageStackDialog.h" #include "ImageStackModel.h" #include "LoadDataReaction.h" #include "SetTiltAnglesOperator.h" #include "Utilities.h" #include <vtkImageData.h> #include <vtkNew.h> #include <vtkTIFFReader.h> namespace tomviz { LoadStackReaction::LoadStackReaction(QAction* parentObject) : pqReaction(parentObject) { } LoadStackReaction::~LoadStackReaction() = default; void LoadStackReaction::onTriggered() { loadData(); } DataSource* LoadStackReaction::loadData(QStringList fileNames) { ImageStackDialog dialog(tomviz::mainWidget()); dialog.processFiles(fileNames); return execStackDialog(dialog); } DataSource* LoadStackReaction::loadData() { ImageStackDialog dialog(tomviz::mainWidget()); return execStackDialog(dialog); } DataSource* LoadStackReaction::execStackDialog(ImageStackDialog& dialog) { int result = dialog.exec(); if (result == QDialog::Accepted) { QStringList fNames; QList<ImageInfo> summary = dialog.getStackSummary(); fNames = summaryToFileNames(summary); if (fNames.size() < 1) { return nullptr; } DataSource* dataSource = LoadDataReaction::loadData(fNames); DataSource::DataSourceType stackType = dialog.getStackType(); if (stackType == DataSource::DataSourceType::TiltSeries) { auto op = new SetTiltAnglesOperator; QMap<size_t, double> angles; for (int i = 0; i < summary.size(); ++i) { angles[i] = summary[i].pos; } op->setTiltAngles(angles); dataSource->addOperator(op); } return dataSource; } else { return nullptr; } } QStringList LoadStackReaction::summaryToFileNames( const QList<ImageInfo>& summary) { QStringList fileNames; foreach (auto image, summary) { if (image.selected) { fileNames << image.fileInfo.absoluteFilePath(); } } return fileNames; } QList<ImageInfo> LoadStackReaction::loadTiffStack(const QStringList& fileNames) { QList<ImageInfo> summary; vtkNew<vtkTIFFReader> reader; int n = -1; int m = -1; int dims[3]; int i = -1; bool consistent; foreach (QString file, fileNames) { i++; consistent = true; reader->SetFileName(file.toLatin1().data()); reader->Update(); reader->GetOutput()->GetDimensions(dims); if (n == -1 && m == -1) { n = dims[0]; m = dims[1]; } else { if (n != dims[0] || m != dims[1]) { consistent = false; } } summary.push_back(ImageInfo(file, 0, dims[0], dims[1], consistent)); } return summary; } } <commit_msg>Fix segmentation fault<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "LoadStackReaction.h" #include "DataSource.h" #include "ImageStackDialog.h" #include "ImageStackModel.h" #include "LoadDataReaction.h" #include "SetTiltAnglesOperator.h" #include "Utilities.h" #include <vtkImageData.h> #include <vtkNew.h> #include <vtkTIFFReader.h> namespace tomviz { LoadStackReaction::LoadStackReaction(QAction* parentObject) : pqReaction(parentObject) { } LoadStackReaction::~LoadStackReaction() = default; void LoadStackReaction::onTriggered() { loadData(); } DataSource* LoadStackReaction::loadData(QStringList fileNames) { ImageStackDialog dialog(tomviz::mainWidget()); dialog.processFiles(fileNames); return execStackDialog(dialog); } DataSource* LoadStackReaction::loadData() { ImageStackDialog dialog(tomviz::mainWidget()); return execStackDialog(dialog); } DataSource* LoadStackReaction::execStackDialog(ImageStackDialog& dialog) { int result = dialog.exec(); if (result == QDialog::Accepted) { QStringList fNames; QList<ImageInfo> summary = dialog.getStackSummary(); fNames = summaryToFileNames(summary); if (fNames.size() < 1) { return nullptr; } DataSource* dataSource = LoadDataReaction::loadData(fNames); DataSource::DataSourceType stackType = dialog.getStackType(); if (stackType == DataSource::DataSourceType::TiltSeries) { auto op = new SetTiltAnglesOperator; QMap<size_t, double> angles; int j = 0; for (int i = 0; i < summary.size(); ++i) { if (summary[i].selected) { angles[j++] = summary[i].pos; } } op->setTiltAngles(angles); dataSource->addOperator(op); } return dataSource; } else { return nullptr; } } QStringList LoadStackReaction::summaryToFileNames( const QList<ImageInfo>& summary) { QStringList fileNames; foreach (auto image, summary) { if (image.selected) { fileNames << image.fileInfo.absoluteFilePath(); } } return fileNames; } QList<ImageInfo> LoadStackReaction::loadTiffStack(const QStringList& fileNames) { QList<ImageInfo> summary; vtkNew<vtkTIFFReader> reader; int n = -1; int m = -1; int dims[3]; int i = -1; bool consistent; foreach (QString file, fileNames) { i++; consistent = true; reader->SetFileName(file.toLatin1().data()); reader->Update(); reader->GetOutput()->GetDimensions(dims); if (n == -1 && m == -1) { n = dims[0]; m = dims[1]; } else { if (n != dims[0] || m != dims[1]) { consistent = false; } } summary.push_back(ImageInfo(file, 0, dims[0], dims[1], consistent)); } return summary; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * 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/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "debug.h" #include "math/math.h" #include "dwi/shells.h" namespace MR { namespace DWI { using namespace App; using namespace Eigen; const OptionGroup ShellOption = OptionGroup ("DW Shell selection options") + Option ("shell", "specify one or more diffusion-weighted gradient shells to use during " "processing, as a comma-separated list of the desired approximate b-values. " "Note that some commands are incompatible with multiple shells, and " "will throw an error if more than one b-value are provided.") + Argument ("list").type_sequence_float(); Shell::Shell (const MatrixXd& grad, const std::vector<size_t>& indices) : volumes (indices), mean (0.0), stdev (0.0), min (std::numeric_limits<default_type>::max()), max (0.0) { assert (volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) { const default_type b = grad (*i, 3); mean += b; min = std::min (min, b); max = std::max (min, b); } mean /= default_type(volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) stdev += Math::pow2 (grad (*i, 3) - mean); stdev = std::sqrt (stdev / (volumes.size() - 1)); } Shells& Shells::select_shells (const bool keep_bzero, const bool force_single_shell) { // Easiest way to restrict processing to particular shells is to simply erase // the unwanted shells; makes it command independent BitSet to_retain (shells.size(), false); if (keep_bzero && smallest().is_bzero()) to_retain[0] = true; auto opt = App::get_options ("shell"); if (opt.size()) { std::vector<default_type> desired_bvalues = opt[0][0]; if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell) throw Exception ("Command not compatible with multiple non-zero b-shells"); for (std::vector<default_type>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) { if (*b < 0) throw Exception ("Cannot select shells corresponding to negative b-values"); // Automatically select a b=0 shell if the requested b-value is zero if (*b <= bzero_threshold()) { if (smallest().is_bzero()) { to_retain[0] = true; DEBUG ("User requested b-value " + str(*b) + "; got b=0 shell : " + str(smallest().get_mean()) + " +- " + str(smallest().get_stdev()) + " with " + str(smallest().count()) + " volumes"); } else { throw Exception ("User selected b=0 shell, but no such data exists"); } } else { // First, see if the b-value lies within the range of one of the shells // If this doesn't occur, need to make a decision based on the shell distributions // Few ways this could be done: // * Compute number of standard deviations away from each shell mean, see if there's a clear winner // - Won't work if any of the standard deviations are zero // * Assume each is a Poisson distribution, see if there's a clear winner // Prompt warning if decision is slightly askew, exception if ambiguous bool shell_selected = false; for (size_t s = 0; s != shells.size(); ++s) { if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) { to_retain[s] = true; shell_selected = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(s) + ": " + str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()) + " with " + str(shells[s].count()) + " volumes"); } } if (!shell_selected) { // Check to see if we can unambiguously select a shell based on b-value integer rounding size_t best_shell = 0; bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { if (std::abs (*b - shells[s].get_mean()) <= 1.0) { if (shell_selected) { ambiguous = true; } else { best_shell = s; shell_selected = true; } } } if (shell_selected && !ambiguous) { to_retain[best_shell] = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(best_shell) + ": " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev()) + " with " + str(shells[best_shell].count()) + " volumes"); } else { // First, check to see if all non-zero shells have (effectively) non-zero standard deviation // (If one non-zero shell has negligible standard deviation, assume a Poisson distribution for all shells) bool zero_stdev = false; for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) { if (!s->is_bzero() && s->get_stdev() < 1.0) { zero_stdev = true; break; } } size_t best_shell = 0; default_type best_num_stdevs = std::numeric_limits<default_type>::max(); bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { const default_type stdev = (shells[s].is_bzero() ? 0.5 * bzero_threshold() : (zero_stdev ? std::sqrt (shells[s].get_mean()) : shells[s].get_stdev())); const default_type num_stdev = std::abs ((*b - shells[s].get_mean()) / stdev); if (num_stdev < best_num_stdevs) { ambiguous = (num_stdev >= 0.1 * best_num_stdevs); best_shell = s; best_num_stdevs = num_stdev; } else { ambiguous = (num_stdev < 10.0 * best_num_stdevs); } } if (ambiguous) { std::string bvalues; for (size_t s = 0; s != shells.size(); ++s) { if (bvalues.size()) bvalues += ", "; bvalues += str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()); } throw Exception ("Unable to robustly select desired shell b=" + str(*b) + " (detected shells are: " + bvalues + ")"); } else { WARN ("User requested shell b=" + str(*b) + "; have selected shell " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev())); to_retain[best_shell] = true; } } // End checking if the requested b-value is within 1.0 of a shell mean } // End checking if the shell can be selected because of lying within the numerical range of a shell } // End checking to see if requested shell is b=0 } // End looping over list of requested b-value shells } else { if (force_single_shell && !is_single_shell()) WARN ("Multiple non-zero b-value shells detected; automatically selecting b=" + str(largest().get_mean()) + " with " + str(largest().count()) + " volumes"); to_retain[shells.size()-1] = true; } if (to_retain.full()) { DEBUG ("No DW shells to be removed"); return *this; } // Erase the unwanted shells std::vector<Shell> new_shells; for (size_t s = 0; s != shells.size(); ++s) { if (to_retain[s]) new_shells.push_back (shells[s]); } shells.swap (new_shells); return *this; } Shells& Shells::reject_small_shells (const size_t min_volumes) { for (std::vector<Shell>::iterator s = shells.begin(); s != shells.end();) { if (!s->is_bzero() && s->count() < min_volumes) s = shells.erase (s); else ++s; } return *this; } Shells::Shells (const MatrixXd& grad) { BValueList bvals = grad.col (3); std::vector<size_t> clusters (bvals.size(), 0); const size_t num_shells = clusterBvalues (bvals, clusters); if ((num_shells < 1) || (num_shells > std::sqrt (default_type(grad.rows())))) throw Exception ("Gradient encoding matrix does not represent a HARDI sequence"); for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) { std::vector<size_t> volumes; for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) { if (clusters[volumeIdx] == shellIdx) volumes.push_back (volumeIdx); } if (shellIdx) { shells.push_back (Shell (grad, volumes)); } else if (volumes.size()) { std::string unassigned; for (size_t i = 0; i != volumes.size(); ++i) { if (unassigned.size()) unassigned += ", "; unassigned += str(volumes[i]) + " (" + str(bvals[volumes[i]]) + ")"; } WARN ("The following image volumes were not successfully assigned to a b-value shell:"); WARN (unassigned); } } std::sort (shells.begin(), shells.end()); if (smallest().is_bzero()) { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells - 1) + " non-zero shells and " + str(smallest().count()) + " b=0 volumes"); } else { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells) + " shells (no b=0 volumes)"); } DEBUG ("Shells: b = { " + str ([&]{ std::string m; for (auto& s : shells) m += str(s.get_mean()) + "(" + str(s.count()) + ") "; return m; }()) + "}"); } size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const { BitSet visited (bvals.size(), false); size_t clusterIdx = 0; for (ssize_t ii = 0; ii != bvals.size(); ii++) { if (!visited[ii]) { visited[ii] = true; const default_type b = bvals[ii]; std::vector<size_t> neighborIdx; regionQuery (bvals, b, neighborIdx); if (b > bzero_threshold() && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) { clusters[ii] = 0; } else { clusters[ii] = ++clusterIdx; for (size_t i = 0; i < neighborIdx.size(); i++) { if (!visited[neighborIdx[i]]) { visited[neighborIdx[i]] = true; std::vector<size_t> neighborIdx2; regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2); if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE) for (size_t j = 0; j != neighborIdx2.size(); j++) neighborIdx.push_back (neighborIdx2[j]); } if (clusters[neighborIdx[i]] == 0) clusters[neighborIdx[i]] = clusterIdx; } } } } return clusterIdx; } void Shells::regionQuery (const BValueList& bvals, const default_type b, std::vector<size_t>& idx) const { for (ssize_t i = 0; i < bvals.size(); i++) { if (std::abs (b - bvals[i]) < DWI_SHELLS_EPSILON) idx.push_back (i); } } } } <commit_msg>grammar<commit_after>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * 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/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "debug.h" #include "math/math.h" #include "dwi/shells.h" namespace MR { namespace DWI { using namespace App; using namespace Eigen; const OptionGroup ShellOption = OptionGroup ("DW Shell selection options") + Option ("shell", "specify one or more diffusion-weighted gradient shells to use during " "processing, as a comma-separated list of the desired approximate b-values. " "Note that some commands are incompatible with multiple shells, and " "will throw an error if more than one b-value is provided.") + Argument ("list").type_sequence_float(); Shell::Shell (const MatrixXd& grad, const std::vector<size_t>& indices) : volumes (indices), mean (0.0), stdev (0.0), min (std::numeric_limits<default_type>::max()), max (0.0) { assert (volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) { const default_type b = grad (*i, 3); mean += b; min = std::min (min, b); max = std::max (min, b); } mean /= default_type(volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) stdev += Math::pow2 (grad (*i, 3) - mean); stdev = std::sqrt (stdev / (volumes.size() - 1)); } Shells& Shells::select_shells (const bool keep_bzero, const bool force_single_shell) { // Easiest way to restrict processing to particular shells is to simply erase // the unwanted shells; makes it command independent BitSet to_retain (shells.size(), false); if (keep_bzero && smallest().is_bzero()) to_retain[0] = true; auto opt = App::get_options ("shell"); if (opt.size()) { std::vector<default_type> desired_bvalues = opt[0][0]; if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell) throw Exception ("Command not compatible with multiple non-zero b-shells"); for (std::vector<default_type>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) { if (*b < 0) throw Exception ("Cannot select shells corresponding to negative b-values"); // Automatically select a b=0 shell if the requested b-value is zero if (*b <= bzero_threshold()) { if (smallest().is_bzero()) { to_retain[0] = true; DEBUG ("User requested b-value " + str(*b) + "; got b=0 shell : " + str(smallest().get_mean()) + " +- " + str(smallest().get_stdev()) + " with " + str(smallest().count()) + " volumes"); } else { throw Exception ("User selected b=0 shell, but no such data exists"); } } else { // First, see if the b-value lies within the range of one of the shells // If this doesn't occur, need to make a decision based on the shell distributions // Few ways this could be done: // * Compute number of standard deviations away from each shell mean, see if there's a clear winner // - Won't work if any of the standard deviations are zero // * Assume each is a Poisson distribution, see if there's a clear winner // Prompt warning if decision is slightly askew, exception if ambiguous bool shell_selected = false; for (size_t s = 0; s != shells.size(); ++s) { if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) { to_retain[s] = true; shell_selected = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(s) + ": " + str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()) + " with " + str(shells[s].count()) + " volumes"); } } if (!shell_selected) { // Check to see if we can unambiguously select a shell based on b-value integer rounding size_t best_shell = 0; bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { if (std::abs (*b - shells[s].get_mean()) <= 1.0) { if (shell_selected) { ambiguous = true; } else { best_shell = s; shell_selected = true; } } } if (shell_selected && !ambiguous) { to_retain[best_shell] = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(best_shell) + ": " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev()) + " with " + str(shells[best_shell].count()) + " volumes"); } else { // First, check to see if all non-zero shells have (effectively) non-zero standard deviation // (If one non-zero shell has negligible standard deviation, assume a Poisson distribution for all shells) bool zero_stdev = false; for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) { if (!s->is_bzero() && s->get_stdev() < 1.0) { zero_stdev = true; break; } } size_t best_shell = 0; default_type best_num_stdevs = std::numeric_limits<default_type>::max(); bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { const default_type stdev = (shells[s].is_bzero() ? 0.5 * bzero_threshold() : (zero_stdev ? std::sqrt (shells[s].get_mean()) : shells[s].get_stdev())); const default_type num_stdev = std::abs ((*b - shells[s].get_mean()) / stdev); if (num_stdev < best_num_stdevs) { ambiguous = (num_stdev >= 0.1 * best_num_stdevs); best_shell = s; best_num_stdevs = num_stdev; } else { ambiguous = (num_stdev < 10.0 * best_num_stdevs); } } if (ambiguous) { std::string bvalues; for (size_t s = 0; s != shells.size(); ++s) { if (bvalues.size()) bvalues += ", "; bvalues += str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()); } throw Exception ("Unable to robustly select desired shell b=" + str(*b) + " (detected shells are: " + bvalues + ")"); } else { WARN ("User requested shell b=" + str(*b) + "; have selected shell " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev())); to_retain[best_shell] = true; } } // End checking if the requested b-value is within 1.0 of a shell mean } // End checking if the shell can be selected because of lying within the numerical range of a shell } // End checking to see if requested shell is b=0 } // End looping over list of requested b-value shells } else { if (force_single_shell && !is_single_shell()) WARN ("Multiple non-zero b-value shells detected; automatically selecting b=" + str(largest().get_mean()) + " with " + str(largest().count()) + " volumes"); to_retain[shells.size()-1] = true; } if (to_retain.full()) { DEBUG ("No DW shells to be removed"); return *this; } // Erase the unwanted shells std::vector<Shell> new_shells; for (size_t s = 0; s != shells.size(); ++s) { if (to_retain[s]) new_shells.push_back (shells[s]); } shells.swap (new_shells); return *this; } Shells& Shells::reject_small_shells (const size_t min_volumes) { for (std::vector<Shell>::iterator s = shells.begin(); s != shells.end();) { if (!s->is_bzero() && s->count() < min_volumes) s = shells.erase (s); else ++s; } return *this; } Shells::Shells (const MatrixXd& grad) { BValueList bvals = grad.col (3); std::vector<size_t> clusters (bvals.size(), 0); const size_t num_shells = clusterBvalues (bvals, clusters); if ((num_shells < 1) || (num_shells > std::sqrt (default_type(grad.rows())))) throw Exception ("Gradient encoding matrix does not represent a HARDI sequence"); for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) { std::vector<size_t> volumes; for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) { if (clusters[volumeIdx] == shellIdx) volumes.push_back (volumeIdx); } if (shellIdx) { shells.push_back (Shell (grad, volumes)); } else if (volumes.size()) { std::string unassigned; for (size_t i = 0; i != volumes.size(); ++i) { if (unassigned.size()) unassigned += ", "; unassigned += str(volumes[i]) + " (" + str(bvals[volumes[i]]) + ")"; } WARN ("The following image volumes were not successfully assigned to a b-value shell:"); WARN (unassigned); } } std::sort (shells.begin(), shells.end()); if (smallest().is_bzero()) { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells - 1) + " non-zero shells and " + str(smallest().count()) + " b=0 volumes"); } else { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells) + " shells (no b=0 volumes)"); } DEBUG ("Shells: b = { " + str ([&]{ std::string m; for (auto& s : shells) m += str(s.get_mean()) + "(" + str(s.count()) + ") "; return m; }()) + "}"); } size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const { BitSet visited (bvals.size(), false); size_t clusterIdx = 0; for (ssize_t ii = 0; ii != bvals.size(); ii++) { if (!visited[ii]) { visited[ii] = true; const default_type b = bvals[ii]; std::vector<size_t> neighborIdx; regionQuery (bvals, b, neighborIdx); if (b > bzero_threshold() && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) { clusters[ii] = 0; } else { clusters[ii] = ++clusterIdx; for (size_t i = 0; i < neighborIdx.size(); i++) { if (!visited[neighborIdx[i]]) { visited[neighborIdx[i]] = true; std::vector<size_t> neighborIdx2; regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2); if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE) for (size_t j = 0; j != neighborIdx2.size(); j++) neighborIdx.push_back (neighborIdx2[j]); } if (clusters[neighborIdx[i]] == 0) clusters[neighborIdx[i]] = clusterIdx; } } } } return clusterIdx; } void Shells::regionQuery (const BValueList& bvals, const default_type b, std::vector<size_t>& idx) const { for (ssize_t i = 0; i < bvals.size(); i++) { if (std::abs (b - bvals[i]) < DWI_SHELLS_EPSILON) idx.push_back (i); } } } } <|endoftext|>
<commit_before>//system stuff #include <string> #include <stdint.h> //ros stuff #include "ros/ros.h" #include "sensor_msgs/Joy.h" #include "geometry_msgs/Twist.h" #include "capybarauno/capybara_ticks.h" using namespace std; ros::Publisher ticks_publisher; struct configuration{ string cmdvel_topic; string ticks_topic; int left_meter_to_ticks; int right_meter_to_ticks; int debug; }; struct configuration c; uint32_t tick_sequence; float left_meter_to_ticks,right_meter_to_ticks; void cmdvelCallback(const geometry_msgs::Twist::ConstPtr& twist) { if(!ros::ok()) return; //get absolute speed values, expressed in tick per interval float translational_velocity = twist->linear.x; float rotational_velocity = twist->angular.z; if(c.debug){ ROS_INFO("LINEAR %f ANGULAR %f", twist->linear.x, twist->angular.z); } capybarauno::capybara_ticks ct; ct.leftEncoder=(-translational_velocity+rotational_velocity)*left_meter_to_ticks; ct.rightEncoder=(translational_velocity+rotational_velocity)*right_meter_to_ticks; if(c.debug){ ROS_INFO("TICKS %d %d",ct.leftEncoder, ct.rightEncoder); } ct.header.stamp=ros::Time::now(); ct.header.seq=tick_sequence; tick_sequence++; ticks_publisher.publish(ct); } void EchoParameters(){ printf("%s %s\n","_cmdvel_topic",c.cmdvel_topic.c_str()); printf("%s %s\n","_ticks_topic",c.ticks_topic.c_str()); printf("%s %d\n","_left_meter_to_ticks",c.left_meter_to_ticks); printf("%s %d\n","_right_meter_to_ticks",c.right_meter_to_ticks); printf("%s %d\n","_debug",c.debug); } int main(int argc, char **argv) { ros::init(argc, argv, "capybarauno_twist2ticks",ros::init_options::AnonymousName); ros::NodeHandle n("~"); n.param<string>("cmdvel_topic", c.cmdvel_topic, "/cmd_vel"); n.param<string>("tick_topic", c.ticks_topic, "/requested_ticks"); n.param("left_meter_to_ticks",c.left_meter_to_ticks,1); n.param("right_meter_to_ticks",c.right_meter_to_ticks,1); n.param("debug", c.debug, 1); EchoParameters(); left_meter_to_ticks = (float)c.left_meter_to_ticks; right_meter_to_ticks = (float)c.right_meter_to_ticks; ros::Subscriber cmdvel_subscriber = n.subscribe(c.cmdvel_topic.c_str(), 1000, cmdvelCallback); ticks_publisher = n.advertise<capybarauno::capybara_ticks>(c.ticks_topic.c_str(), 1000); ros::spin(); return 0; } <commit_msg>added baseline parameter<commit_after>//system stuff #include <string> #include <stdint.h> //ros stuff #include "ros/ros.h" #include "sensor_msgs/Joy.h" #include "geometry_msgs/Twist.h" #include "capybarauno/capybara_ticks.h" using namespace std; ros::Publisher ticks_publisher; struct configuration{ string cmdvel_topic; string ticks_topic; double left_ticks; double right_ticks; double baseline; int debug; }; struct configuration c; uint32_t tick_sequence; float left_meter_to_ticks,right_meter_to_ticks,baseline; void cmdvelCallback(const geometry_msgs::Twist::ConstPtr& twist) { if(!ros::ok()) return; //get absolute speed values, expressed in tick per interval float translational_velocity = twist->linear.x; float rotational_velocity = twist->angular.z/baseline; if(c.debug){ ROS_INFO("LINEAR %f ANGULAR %f ANGULAR AFTER BASELINE %f", twist->linear.x, twist->angular.z,rotational_velocity); } capybarauno::capybara_ticks ct; ct.leftEncoder=(-translational_velocity+rotational_velocity)*left_meter_to_ticks; ct.rightEncoder=(translational_velocity+rotational_velocity)*right_meter_to_ticks; if(c.debug){ ROS_INFO("TICKS %d %d",ct.leftEncoder, ct.rightEncoder); } ct.header.stamp=ros::Time::now(); ct.header.seq=tick_sequence; tick_sequence++; ticks_publisher.publish(ct); } void EchoParameters(){ printf("%s %s\n","_cmdvel_topic",c.cmdvel_topic.c_str()); printf("%s %s\n","_ticks_topic",c.ticks_topic.c_str()); printf("%s %f\n","_left_ticks",c.left_ticks); printf("%s %f\n","_right_ticks",c.right_ticks); printf("%s %f\n","_baseline",c.baseline); printf("%s %d\n","_debug",c.debug); } int main(int argc, char **argv) { ros::init(argc, argv, "capybarauno_twist2ticks",ros::init_options::AnonymousName); ros::NodeHandle n("~"); n.param<string>("cmdvel_topic", c.cmdvel_topic, "/cmd_vel"); n.param<string>("tick_topic", c.ticks_topic, "/requested_ticks"); n.param("left_ticks",c.left_ticks,1.0d); n.param("right_ticks",c.right_ticks,1.0d); n.param("baseline",c.baseline,1.0d); n.param("debug", c.debug, 1); EchoParameters(); left_meter_to_ticks = (float)c.left_ticks; right_meter_to_ticks = (float)c.right_ticks; baseline= (float)c.baseline; ros::Subscriber cmdvel_subscriber = n.subscribe(c.cmdvel_topic.c_str(), 1000, cmdvelCallback); ticks_publisher = n.advertise<capybarauno::capybara_ticks>(c.ticks_topic.c_str(), 1000); ros::spin(); return 0; } <|endoftext|>
<commit_before>//============================================================================= // // Copyright (C)1999 by Eric Sunshine <sunshine@sunshineco.com> // // The contents of this file are copyrighted by Eric Sunshine. This work 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. You may distribute this file provided that this // copyright notice is retained. Send comments to <sunshine@sunshineco.com>. // //============================================================================= //----------------------------------------------------------------------------- // NeXTProxy2D.cpp // // C++ object which interacts with Objective-C world on behalf of // NeXTDriver2D which can not directly interface with Objective-C on // account of COM-related conflicts. See README.NeXT for details. // // *WARNING* Do NOT include any COM headers in this file. //----------------------------------------------------------------------------- #include "NeXTProxy2D.h" #include "NeXTDelegate.h" #include "NeXTFrameBuffer15.h" #include "NeXTFrameBuffer32.h" #include "NeXTView.h" extern "Objective-C" { #import <appkit/Application.h> #import <appkit/NXBitmapImageRep.h> #import <appkit/NXCursor.h> #import <appkit/NXImage.h> #import <appkit/Window.h> } extern "C" { #include <assert.h> } //----------------------------------------------------------------------------- // window_server_depth // Directly query the Window Server for its preferred depth. Note that // this value may be different from the depth limit reported by the // Window class. See get_device_depth() for a full discussion. The // Window Server is queried for its preferred depth by creating a small // image cache which is painted with color so as to promote it from gray // to color. The Window Server is then asked to return an // NXBitmapImageRep holding the contents of the image cache. The Window // Server always returns the NXBitmapImageRep in the format which it most // prefers. //----------------------------------------------------------------------------- static NXWindowDepth window_server_depth() { NXRect const r = {{ 0, 0 }, { 4, 4 }}; NXImage* image = [[NXImage alloc] initSize:&r.size]; [image lockFocus]; NXSetColor( NX_COLORBLUE ); NXRectFill(&r); NXBitmapImageRep* rep = [[NXBitmapImageRep alloc] initData:0 fromRect:&r]; NXWindowDepth depth; NXGetBestDepth( &depth, [rep numColors], [rep bitsPerSample] ); [rep free]; [image unlockFocus]; [image free]; return depth; } //----------------------------------------------------------------------------- // best_bits_per_sample // Determine the ideal number of bits per sample for the default display // depth. All display depths are supported, though optimizations only // work for 12-bit RGB and 24-bit RGB. Consequently this function only // reports 4 or 8 bits per sample, representing 12-bit and 24-bit depths, // respectively. Other depths still work, but more slowly. See // README.NeXT for details. // // Note that as of OpenStep 4.1, the Window Server may prefer a depth // greater than that of the "deepest" screen as reported by the Window // class. The reason for this is that "true" RGB/5:5:5 was implemented // in OpenStep 4.1. Previously this had been simulated with 4:4:4. A // consequence of this change is that for 5:5:5 displays, the Window // Server actually prefers 24-bit rather than 12-bit RGB as was the case // with previous versions. It is important to note that the Window class // still reports a depth limit of 12-bit even though the Window Server // prefers 24-bit. Consequently, window_server_depth() is used to // directly query the WindowServer for its preference instead. The // behavior in the OpenStep Window Server impacts all applications, // including those compiled with earlier versions of OpenStep or // NextStep. //----------------------------------------------------------------------------- static int best_bits_per_sample() { NXWindowDepth const depth = window_server_depth(); if (NXColorSpaceFromDepth( depth ) == NX_RGBColorSpace) { int const bps = NXBPSFromDepth( depth ); if (bps == 4 || bps == 8) return bps; } return 4; } //----------------------------------------------------------------------------- // determine_bits_per_sample //----------------------------------------------------------------------------- static int determine_bits_per_sample( int simulate_depth ) { int bps; switch (simulate_depth) { case 15: bps = 4; break; case 32: bps = 8; break; default: bps = best_bits_per_sample(); break; } return bps; } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- NeXTProxy2D::NeXTProxy2D( unsigned int w, unsigned int h, int simulate_depth ): window(0), view(0), width(w), height(h), frame_buffer(0) { switch (determine_bits_per_sample( simulate_depth )) { case 4: frame_buffer = new NeXTFrameBuffer15( width, height ); break; case 8: frame_buffer = new NeXTFrameBuffer32( width, height ); break; } } //----------------------------------------------------------------------------- // Destructor //----------------------------------------------------------------------------- NeXTProxy2D::~NeXTProxy2D() { [[NXApp delegate] showMouse]; [[NXApp delegate] registerAnimationWindow:0]; [window setDelegate:0]; [window close]; [window free]; // Window frees NeXTView. delete frame_buffer; } //----------------------------------------------------------------------------- // open // Opens a titled Window and installs a NeXTView as its contentView. // Registers the window with the application's delegate as its "animation // window". Passes the raw frame-buffer along to the NeXTView which blits // it directly to the WindowServer via NXBitmapImageRep. // // *NOTE* // Window must have valid PostScript windowNum before registering with // application's delegate since a tracking rectangle is set up. // Therefore window must be on-screen before registering the window. The // alternative of using a non-deferred window does not seem to be an // option since, for some inexplicable reason, the contents of a Retained // non-deferred window are never drawn. //----------------------------------------------------------------------------- bool NeXTProxy2D::open( char const* title ) { NXRect const r = {{ 0, 0 }, { width, height }}; window = [[Window alloc] initContent:&r style:NX_TITLEDSTYLE backing:NX_RETAINED buttonMask:NX_CLOSEBUTTONMASK defer:YES]; [window setTitle:title]; [window setFreeWhenClosed:NO]; view = [[NeXTView alloc] initFrame:&r]; [view setFrameBuffer:frame_buffer->get_cooked_buffer() bitsPerSample:frame_buffer->bits_per_sample()]; [[window setContentView:view] free]; [window center]; [window makeFirstResponder:view]; [window makeKeyAndOrderFront:0]; [[NXApp delegate] registerAnimationWindow:window]; // *NOTE* return true; } //----------------------------------------------------------------------------- // close //----------------------------------------------------------------------------- void NeXTProxy2D::close() { [window close]; } //----------------------------------------------------------------------------- // flush // Convert the CrystalSpace frame-buffer into NeXT format and blit the // image to the display. //----------------------------------------------------------------------------- void NeXTProxy2D::flush() { assert( frame_buffer != 0 ); frame_buffer->cook(); [view flush]; DPSFlush(); } //----------------------------------------------------------------------------- // set_mouse_cursor //----------------------------------------------------------------------------- bool NeXTProxy2D::set_mouse_cursor( csMouseCursorID shape, iTextureHandle* ) { bool handled = false; if (shape == csmcArrow) { [NXArrow set]; handled = true; } if (handled) [[NXApp delegate] showMouse]; else [[NXApp delegate] hideMouse]; return handled; } <commit_msg>Actually compiles now.<commit_after>//============================================================================= // // Copyright (C)1999 by Eric Sunshine <sunshine@sunshineco.com> // // The contents of this file are copyrighted by Eric Sunshine. This work 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. You may distribute this file provided that this // copyright notice is retained. Send comments to <sunshine@sunshineco.com>. // //============================================================================= //----------------------------------------------------------------------------- // NeXTProxy2D.cpp // // C++ object which interacts with Objective-C world on behalf of // NeXTDriver2D which can not directly interface with Objective-C on // account of COM-related conflicts. See README.NeXT for details. // // *WARNING* Do NOT include any COM headers in this file. //----------------------------------------------------------------------------- #include "sysdef.h" #include "NeXTProxy2D.h" #include "NeXTDelegate.h" #include "NeXTFrameBuffer15.h" #include "NeXTFrameBuffer32.h" #include "NeXTView.h" extern "Objective-C" { #import <appkit/Application.h> #import <appkit/NXBitmapImageRep.h> #import <appkit/NXCursor.h> #import <appkit/NXImage.h> #import <appkit/Window.h> } extern "C" { #include <assert.h> } //----------------------------------------------------------------------------- // window_server_depth // Directly query the Window Server for its preferred depth. Note that // this value may be different from the depth limit reported by the // Window class. See get_device_depth() for a full discussion. The // Window Server is queried for its preferred depth by creating a small // image cache which is painted with color so as to promote it from gray // to color. The Window Server is then asked to return an // NXBitmapImageRep holding the contents of the image cache. The Window // Server always returns the NXBitmapImageRep in the format which it most // prefers. //----------------------------------------------------------------------------- static NXWindowDepth window_server_depth() { NXRect const r = {{ 0, 0 }, { 4, 4 }}; NXImage* image = [[NXImage alloc] initSize:&r.size]; [image lockFocus]; NXSetColor( NX_COLORBLUE ); NXRectFill(&r); NXBitmapImageRep* rep = [[NXBitmapImageRep alloc] initData:0 fromRect:&r]; NXWindowDepth depth; NXGetBestDepth( &depth, [rep numColors], [rep bitsPerSample] ); [rep free]; [image unlockFocus]; [image free]; return depth; } //----------------------------------------------------------------------------- // best_bits_per_sample // Determine the ideal number of bits per sample for the default display // depth. All display depths are supported, though optimizations only // work for 12-bit RGB and 24-bit RGB. Consequently this function only // reports 4 or 8 bits per sample, representing 12-bit and 24-bit depths, // respectively. Other depths still work, but more slowly. See // README.NeXT for details. // // Note that as of OpenStep 4.1, the Window Server may prefer a depth // greater than that of the "deepest" screen as reported by the Window // class. The reason for this is that "true" RGB/5:5:5 was implemented // in OpenStep 4.1. Previously this had been simulated with 4:4:4. A // consequence of this change is that for 5:5:5 displays, the Window // Server actually prefers 24-bit rather than 12-bit RGB as was the case // with previous versions. It is important to note that the Window class // still reports a depth limit of 12-bit even though the Window Server // prefers 24-bit. Consequently, window_server_depth() is used to // directly query the WindowServer for its preference instead. The // behavior in the OpenStep Window Server impacts all applications, // including those compiled with earlier versions of OpenStep or // NextStep. //----------------------------------------------------------------------------- static int best_bits_per_sample() { NXWindowDepth const depth = window_server_depth(); if (NXColorSpaceFromDepth( depth ) == NX_RGBColorSpace) { int const bps = NXBPSFromDepth( depth ); if (bps == 4 || bps == 8) return bps; } return 4; } //----------------------------------------------------------------------------- // determine_bits_per_sample //----------------------------------------------------------------------------- static int determine_bits_per_sample( int simulate_depth ) { int bps; switch (simulate_depth) { case 15: bps = 4; break; case 32: bps = 8; break; default: bps = best_bits_per_sample(); break; } return bps; } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- NeXTProxy2D::NeXTProxy2D( unsigned int w, unsigned int h, int simulate_depth ): window(0), view(0), width(w), height(h), frame_buffer(0) { switch (determine_bits_per_sample( simulate_depth )) { case 4: frame_buffer = new NeXTFrameBuffer15( width, height ); break; case 8: frame_buffer = new NeXTFrameBuffer32( width, height ); break; } } //----------------------------------------------------------------------------- // Destructor //----------------------------------------------------------------------------- NeXTProxy2D::~NeXTProxy2D() { [[NXApp delegate] showMouse]; [[NXApp delegate] registerAnimationWindow:0]; [window setDelegate:0]; [window close]; [window free]; // Window frees NeXTView. delete frame_buffer; } //----------------------------------------------------------------------------- // open // Opens a titled Window and installs a NeXTView as its contentView. // Registers the window with the application's delegate as its "animation // window". Passes the raw frame-buffer along to the NeXTView which blits // it directly to the WindowServer via NXBitmapImageRep. // // *NOTE* // Window must have valid PostScript windowNum before registering with // application's delegate since a tracking rectangle is set up. // Therefore window must be on-screen before registering the window. The // alternative of using a non-deferred window does not seem to be an // option since, for some inexplicable reason, the contents of a Retained // non-deferred window are never drawn. //----------------------------------------------------------------------------- bool NeXTProxy2D::open( char const* title ) { NXRect const r = {{ 0, 0 }, { width, height }}; window = [[Window alloc] initContent:&r style:NX_TITLEDSTYLE backing:NX_RETAINED buttonMask:NX_CLOSEBUTTONMASK defer:YES]; [window setTitle:title]; [window setFreeWhenClosed:NO]; view = [[NeXTView alloc] initFrame:&r]; [view setFrameBuffer:frame_buffer->get_cooked_buffer() bitsPerSample:frame_buffer->bits_per_sample()]; [[window setContentView:view] free]; [window center]; [window makeFirstResponder:view]; [window makeKeyAndOrderFront:0]; [[NXApp delegate] registerAnimationWindow:window]; // *NOTE* return true; } //----------------------------------------------------------------------------- // close //----------------------------------------------------------------------------- void NeXTProxy2D::close() { [window close]; } //----------------------------------------------------------------------------- // flush // Convert the CrystalSpace frame-buffer into NeXT format and blit the // image to the display. //----------------------------------------------------------------------------- void NeXTProxy2D::flush() { assert( frame_buffer != 0 ); frame_buffer->cook(); [view flush]; DPSFlush(); } //----------------------------------------------------------------------------- // set_mouse_cursor //----------------------------------------------------------------------------- bool NeXTProxy2D::set_mouse_cursor( csMouseCursorID shape, iTextureHandle* ) { bool handled = false; if (shape == csmcArrow) { [NXArrow set]; handled = true; } if (handled) [[NXApp delegate] showMouse]; else [[NXApp delegate] hideMouse]; return handled; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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 * *****************************************************************************/ // mapnik #include <mapnik/expression.hpp> #include <mapnik/config_error.hpp> #include <mapnik/unicode.hpp> #include <mapnik/expression_node_types.hpp> #include <mapnik/expression_grammar.hpp> #include <boost/spirit/include/qi.hpp> // boost #include <boost/make_shared.hpp> namespace mapnik { expression_ptr parse_expression(std::string const& str, std::string const& encoding) { transcoder tr(encoding); expression_grammar<std::string::const_iterator> g(tr); return parse_expression(str, g); } expression_ptr parse_expression(std::string const& str, mapnik::expression_grammar<std::string::const_iterator> const& g) { expr_node node; std::string::const_iterator itr = str.begin(); std::string::const_iterator end = str.end(); bool r = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::standard_wide::space, node); if (r && itr == end) { return boost::make_shared<expr_node>(node); } else { throw config_error( "Failed to parse expression: \"" + str + "\"" ); } } } <commit_msg>expression parser - avoid extra level of indirection<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 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 * *****************************************************************************/ // mapnik #include <mapnik/expression.hpp> #include <mapnik/config_error.hpp> #include <mapnik/unicode.hpp> #include <mapnik/expression_node_types.hpp> #include <mapnik/expression_grammar.hpp> #include <boost/spirit/include/qi.hpp> // boost #include <boost/make_shared.hpp> namespace mapnik { expression_ptr parse_expression(std::string const& str, std::string const& encoding) { transcoder tr(encoding); expression_grammar<std::string::const_iterator> g(tr); return parse_expression(str, g); } expression_ptr parse_expression(std::string const& str, mapnik::expression_grammar<std::string::const_iterator> const& g) { expression_ptr node = boost::make_shared<expr_node>(); std::string::const_iterator itr = str.begin(); std::string::const_iterator end = str.end(); bool r = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::standard_wide::space, *node); if (r && itr == end) { return node; } else { throw config_error( "Failed to parse expression: \"" + str + "\"" ); } } } <|endoftext|>
<commit_before>#include "anki/gl/GlState.h" #include "anki/gl/ShaderProgram.h" #include "anki/gl/Fbo.h" #include "anki/gl/Vao.h" #include "anki/util/Assert.h" #include <limits> namespace anki { //============================================================================== GLenum GlState::flagEnums[] = { GL_DEPTH_TEST, GL_BLEND, GL_STENCIL_TEST, GL_CULL_FACE, GL_RASTERIZER_DISCARD, GL_POLYGON_OFFSET_FILL, 0 }; //============================================================================== void GlState::enable(GLenum glFlag, bool enable) { ANKI_ASSERT(flags.find(glFlag) != flags.end()); bool state = flags[glFlag]; ANKI_ASSERT(glIsEnabled(glFlag) == state); if(enable != state) { if(enable) { glEnable(glFlag); } else { glDisable(glFlag); } flags[glFlag] = enable; } } //============================================================================== bool GlState::isEnabled(GLenum glFlag) { ANKI_ASSERT(flags.find(glFlag) != flags.end()); bool state = flags[glFlag]; ANKI_ASSERT(glIsEnabled(glFlag) == state); return state; } //============================================================================== void GlState::sync() { // Set flags GLenum* flagEnum = &flagEnums[0]; while(*flagEnum != 0) { flags[*flagEnum] = glIsEnabled(*flagEnum); ++flagEnum; } // viewport GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, &viewport[0]); viewportX = viewport[0]; viewportY = viewport[1]; viewportW = viewport[2]; viewportH = viewport[3]; // pointers prog = fbo = vao = std::numeric_limits<decltype(prog)>::max(); } //============================================================================== void GlState::setViewport(uint32_t x, uint32_t y, uint32_t w, uint32_t h) { if(x != (uint32_t)viewportX || y != (uint32_t)viewportY || w != (uint32_t)viewportW || h != (uint32_t)viewportH) { glViewport(x, y, w, h); viewportX = x; viewportY = y; viewportW = w; viewportH = h; } } //============================================================================== void GlState::setProgram(ShaderProgram* prog_) { ANKI_ASSERT(prog_); prog_->bind(); } //============================================================================== void GlState::setFbo(Fbo* fbo_) { if(fbo_ == nullptr) { Fbo::unbindAll(); } else { ANKI_ASSERT(fbo_->isComplete()); fbo_->bind(); } } //============================================================================== void GlState::setVao(Vao* vao_) { ANKI_ASSERT(vao_); vao_->bind(); } } // end namespace <commit_msg>A small fix<commit_after>#include "anki/gl/GlState.h" #include "anki/gl/ShaderProgram.h" #include "anki/gl/Fbo.h" #include "anki/gl/Vao.h" #include "anki/util/Assert.h" #include <limits> namespace anki { //============================================================================== GLenum GlState::flagEnums[] = { GL_DEPTH_TEST, GL_BLEND, GL_STENCIL_TEST, GL_CULL_FACE, GL_RASTERIZER_DISCARD, GL_POLYGON_OFFSET_FILL, 0 }; //============================================================================== void GlState::enable(GLenum glFlag, bool enable) { ANKI_ASSERT(flags.find(glFlag) != flags.end()); bool state = flags[glFlag]; ANKI_ASSERT(glIsEnabled(glFlag) == state); if(enable != state) { if(enable) { glEnable(glFlag); } else { glDisable(glFlag); } flags[glFlag] = enable; } } //============================================================================== bool GlState::isEnabled(GLenum glFlag) { ANKI_ASSERT(flags.find(glFlag) != flags.end()); bool state = flags[glFlag]; ANKI_ASSERT(glIsEnabled(glFlag) == state); return state; } //============================================================================== void GlState::sync() { // Set flags GLenum* flagEnum = &flagEnums[0]; while(*flagEnum != 0) { flags[*flagEnum] = glIsEnabled(*flagEnum); ++flagEnum; } // viewport GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, &viewport[0]); viewportX = viewport[0]; viewportY = viewport[1]; viewportW = viewport[2]; viewportH = viewport[3]; } //============================================================================== void GlState::setViewport(uint32_t x, uint32_t y, uint32_t w, uint32_t h) { if(x != (uint32_t)viewportX || y != (uint32_t)viewportY || w != (uint32_t)viewportW || h != (uint32_t)viewportH) { glViewport(x, y, w, h); viewportX = x; viewportY = y; viewportW = w; viewportH = h; } } //============================================================================== void GlState::setProgram(ShaderProgram* prog_) { ANKI_ASSERT(prog_); prog_->bind(); } //============================================================================== void GlState::setFbo(Fbo* fbo_) { if(fbo_ == nullptr) { Fbo::unbindAll(); } else { ANKI_ASSERT(fbo_->isComplete()); fbo_->bind(); } } //============================================================================== void GlState::setVao(Vao* vao_) { ANKI_ASSERT(vao_); vao_->bind(); } } // end namespace <|endoftext|>
<commit_before>namespace tz::gl { template<template<typename> class PixelType, typename ComponentType> void Texture::set_data(const tz::gl::Image<PixelType<ComponentType>>& image) { constexpr GLint internal_format = tz::gl::pixel::parse_internal_format<PixelType, ComponentType>(); constexpr GLenum format = tz::gl::pixel::parse_format<PixelType, ComponentType>(); constexpr GLenum type = tz::gl::pixel::parse_component_type<ComponentType>(); static_assert(internal_format != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); static_assert(format != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); static_assert(type != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); this->internal_bind(); glTexImage2D(GL_TEXTURE_2D, 0, internal_format, static_cast<GLsizei>(image.get_width()), static_cast<GLsizei>(image.get_height()), 0, format, type, image.data()); this->descriptor = {static_cast<TextureComponentType>(type), static_cast<TextureInternalFormat>(internal_format), static_cast<TextureFormat>(format), image.get_width(), image.get_height()}; } template<template<typename> class PixelType, typename ComponentType> tz::gl::Image<PixelType<ComponentType>> Texture::get_data() const { topaz_assert(this->descriptor.has_value(), "tz::gl::Texture::get_data<PixelType, ComponentType>(): Cannot get data because we never detected an invocation of set_data!"); constexpr GLint internal_format = tz::gl::pixel::parse_internal_format<PixelType, ComponentType>(); constexpr GLenum format = tz::gl::pixel::parse_format<PixelType, ComponentType>(); constexpr GLenum type = tz::gl::pixel::parse_component_type<ComponentType>(); TextureDataDescriptor desired_descriptor{type, internal_format, format}; TextureDataDescriptor expected_descriptor = this->descriptor.value(); topaz_assert(desired_descriptor == expected_descriptor, "tz::gl::Texture::get_data<PixelType, ComponentType>(): TextureDataDescriptors didn't match. This means you are attempting to retrieve a texture with a different descriptor than what was set:\n\ Desired Descriptor:\n\ \tComponent-Type: ", type, "\n\ \tInternal-Format: ", internal_format, "\n\ \tFormat: ", format, "\ Provided Descriptor:\n\ \tComponent-Type: ", expected_descriptor.component_type, "\n\ \tInternal-Format: ", expected_descriptor.internal_format, "\n\ \tFormat: ", expected_descriptor.format); // Make the empty image. tz::gl::Image<PixelType<ComponentType>> img{expected_descriptor.width, expected_descriptor.height}; // Can safely get the image data now. img.data() will have the correct allocation size. this->internal_bind(); glGetTexImage(GL_TEXTURE_2D, 0, format, type, img.data()); return std::move(img); } }<commit_msg>* Fixed broken tests<commit_after>namespace tz::gl { template<template<typename> class PixelType, typename ComponentType> void Texture::set_data(const tz::gl::Image<PixelType<ComponentType>>& image) { constexpr GLint internal_format = tz::gl::pixel::parse_internal_format<PixelType, ComponentType>(); constexpr GLenum format = tz::gl::pixel::parse_format<PixelType, ComponentType>(); constexpr GLenum type = tz::gl::pixel::parse_component_type<ComponentType>(); static_assert(internal_format != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); static_assert(format != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); static_assert(type != GL_INVALID_VALUE, "Texture::set_data<PixelType, ComponentType>: Unsupported pixel/component types."); this->internal_bind(); glTexImage2D(GL_TEXTURE_2D, 0, internal_format, static_cast<GLsizei>(image.get_width()), static_cast<GLsizei>(image.get_height()), 0, format, type, image.data()); this->descriptor = {static_cast<TextureComponentType>(type), static_cast<TextureInternalFormat>(internal_format), static_cast<TextureFormat>(format), image.get_width(), image.get_height()}; } template<template<typename> class PixelType, typename ComponentType> tz::gl::Image<PixelType<ComponentType>> Texture::get_data() const { topaz_assert(this->descriptor.has_value(), "tz::gl::Texture::get_data<PixelType, ComponentType>(): Cannot get data because we never detected an invocation of set_data!"); constexpr GLint internal_format = tz::gl::pixel::parse_internal_format<PixelType, ComponentType>(); constexpr GLenum format = tz::gl::pixel::parse_format<PixelType, ComponentType>(); constexpr GLenum type = tz::gl::pixel::parse_component_type<ComponentType>(); TextureDataDescriptor desired_descriptor{static_cast<TextureComponentType>(type), static_cast<TextureInternalFormat>(internal_format), static_cast<TextureFormat>(format)}; TextureDataDescriptor expected_descriptor = this->descriptor.value(); topaz_assert(desired_descriptor == expected_descriptor, "tz::gl::Texture::get_data<PixelType, ComponentType>(): TextureDataDescriptors didn't match. This means you are attempting to retrieve a texture with a different descriptor than what was set:\n\ Desired Descriptor:\n\ \tComponent-Type: ", static_cast<GLenum>(type), "\n\ \tInternal-Format: ", static_cast<GLint>(internal_format), "\n\ \tFormat: ", static_cast<GLenum>(format), "\ Provided Descriptor:\n\ \tComponent-Type: ", static_cast<GLenum>(expected_descriptor.component_type), "\n\ \tInternal-Format: ", static_cast<GLint>(expected_descriptor.internal_format), "\n\ \tFormat: ", static_cast<GLenum>(expected_descriptor.format)); // Make the empty image. tz::gl::Image<PixelType<ComponentType>> img{expected_descriptor.width, expected_descriptor.height}; // Can safely get the image data now. img.data() will have the correct allocation size. this->internal_bind(); glGetTexImage(GL_TEXTURE_2D, 0, format, type, img.data()); return img; } }<|endoftext|>
<commit_before>/* * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uvar.hh #ifndef URBI_UVAR_HH # define URBI_UVAR_HH # include <iosfwd> # include <string> # include <libport/fwd.hh> # include <libport/ufloat.hh> # include <urbi/ucontext.hh> # include <urbi/uvalue.hh> # include <urbi/uprop.hh> # include <urbi/uproperty.hh> namespace urbi { /** UVar class definition Each UVar instance corresponds to one URBI variable. The class provides access to the variable properties, and reading/writing the value to/from all known types. */ class URBI_SDK_API UVar: public UContext { public: /// Creates an unbound UVar. Call init() to bind it. UVar(); UVar(const std::string&, impl::UContextImpl* = 0); UVar(const std::string&, const std::string&, impl::UContextImpl* = 0); UVar(UObject&, const std::string&, impl::UContextImpl* = 0); UVar(const UVar&); private: UVar& operator=(const UVar&); public: ~UVar(); // Bind to \a object.slot. void init(const std::string& varname, impl::UContextImpl* = 0); void init(const std::string& object, const std::string& slot, impl::UContextImpl* = 0); void setOwned(); /// The type of the current content. UDataType type() const; /// Request the current value, wait until it is available. void syncValue(); /// Keep this UVar synchronized with kernel value. void keepSynchronized(); void reset (ufloat); UVar& operator=(ufloat); UVar& operator=(const std::string&); /// Deep copy. UVar& operator=(const UBinary&); /// Deep copy. UVar& operator=(const UImage& i); /// Deep copy. UVar& operator=(const USound& s); UVar& operator=(const UList& l); UVar& operator=(const UDictionary& d); UVar& operator=(const UValue& v); template<typename T> UVar& operator=(const T&); operator int() const; operator bool() const; // Cast to a UBinary to make copy through this operator. operator const UBinary&() const; /// Deep copy, binary will have to be deleted by the user. operator UBinary*() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator UImage() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator USound() const; operator ufloat() const; operator std::string() const; operator UList() const; operator UDictionary() const; /// No effect in plugin mode. In remote mode, updates the value /// once asynchronously. void requestValue(); /// Deactivate all callbacks associated with this UVar and stop synchro. void unnotify(); /// Kernel operators. ufloat& in(); ufloat& out(); /// Is the variable owned by the module? bool owned; /// Property accessors. UProp rangemin; UProp rangemax; UProp speedmin; UProp speedmax; UProp delta; UProp blend; UValue getProp(UProperty prop); void setProp(UProperty prop, const UValue &v); void setProp(UProperty prop, ufloat v); void setProp(UProperty prop, const char * v); void setProp(UProperty prop, const std::string& v) { setProp(prop, v.c_str()); } /// Enable bypass-mode for this UVar. Plugin-mode only. /// In bypass mode, if the UVar contains binary data, the data is never /// copied. The consequence is that the data is only accessible from /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon /// as all callbacks have returned. bool setBypass(bool enable=true); /// Use RTP mode to transmit this variable if possible. void useRTP(bool enable=true); impl::UVarImpl* impl_; const UValue& val() const; private: /// Check that impl_ is set or throw a runtime error. void check_() const; /// Pointer to internal data specifics. UVardata* vardata; void __init(); /// Define an attribute and its accessors. # define PRIVATE(Type, Name) \ public: \ Type get_ ## Name () \ { \ return Name; \ } \ Type get_ ## Name () const \ { \ return Name; \ } \ void set_ ## Name (const Type& v) \ { \ Name = v; \ } \ private: \ Type Name; /// Full name of the variable as seen in URBI. PRIVATE(std::string, name) /// True if the variable is a temporary and must not be stored in callbacks PRIVATE(bool, temp); PRIVATE(bool, rtp); # undef PRIVATE // Check that the invariants of this class are verified. bool invariant() const; friend class impl::UVarImpl; }; /*-------------------------. | Inline implementations. | `-------------------------*/ /// Helper macro to initialize UProps in UVar constructors. # define VAR_PROP_INIT \ rangemin(*this, PROP_RANGEMIN), \ rangemax(*this, PROP_RANGEMAX), \ speedmin(*this, PROP_SPEEDMIN), \ speedmax(*this, PROP_SPEEDMAX), \ delta(*this, PROP_DELTA), \ blend(*this, PROP_BLEND) } // end namespace urbi /// Report \a u on \a o for debugging. URBI_SDK_API std::ostream& operator<< (std::ostream& o, const urbi::UVar& u); # include <urbi/uvar.hxx> #endif // ! URBI_UVAR_HH <commit_msg>uobject: Remove declaration of unimplemented requestvalue().<commit_after>/* * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uvar.hh #ifndef URBI_UVAR_HH # define URBI_UVAR_HH # include <iosfwd> # include <string> # include <libport/fwd.hh> # include <libport/ufloat.hh> # include <urbi/ucontext.hh> # include <urbi/uvalue.hh> # include <urbi/uprop.hh> # include <urbi/uproperty.hh> namespace urbi { /** UVar class definition Each UVar instance corresponds to one URBI variable. The class provides access to the variable properties, and reading/writing the value to/from all known types. */ class URBI_SDK_API UVar: public UContext { public: /// Creates an unbound UVar. Call init() to bind it. UVar(); UVar(const std::string&, impl::UContextImpl* = 0); UVar(const std::string&, const std::string&, impl::UContextImpl* = 0); UVar(UObject&, const std::string&, impl::UContextImpl* = 0); UVar(const UVar&); private: UVar& operator=(const UVar&); public: ~UVar(); // Bind to \a object.slot. void init(const std::string& varname, impl::UContextImpl* = 0); void init(const std::string& object, const std::string& slot, impl::UContextImpl* = 0); void setOwned(); /// The type of the current content. UDataType type() const; /// Request the current value, wait until it is available. void syncValue(); /// Keep this UVar synchronized with kernel value. void keepSynchronized(); void reset (ufloat); UVar& operator=(ufloat); UVar& operator=(const std::string&); /// Deep copy. UVar& operator=(const UBinary&); /// Deep copy. UVar& operator=(const UImage& i); /// Deep copy. UVar& operator=(const USound& s); UVar& operator=(const UList& l); UVar& operator=(const UDictionary& d); UVar& operator=(const UValue& v); template<typename T> UVar& operator=(const T&); operator int() const; operator bool() const; // Cast to a UBinary to make copy through this operator. operator const UBinary&() const; /// Deep copy, binary will have to be deleted by the user. operator UBinary*() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator UImage() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator USound() const; operator ufloat() const; operator std::string() const; operator UList() const; operator UDictionary() const; /// Deactivate all callbacks associated with this UVar and stop synchro. void unnotify(); /// Kernel operators. ufloat& in(); ufloat& out(); /// Is the variable owned by the module? bool owned; /// Property accessors. UProp rangemin; UProp rangemax; UProp speedmin; UProp speedmax; UProp delta; UProp blend; UValue getProp(UProperty prop); void setProp(UProperty prop, const UValue &v); void setProp(UProperty prop, ufloat v); void setProp(UProperty prop, const char * v); void setProp(UProperty prop, const std::string& v) { setProp(prop, v.c_str()); } /// Enable bypass-mode for this UVar. Plugin-mode only. /// In bypass mode, if the UVar contains binary data, the data is never /// copied. The consequence is that the data is only accessible from /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon /// as all callbacks have returned. bool setBypass(bool enable=true); /// Use RTP mode to transmit this variable if possible. void useRTP(bool enable=true); impl::UVarImpl* impl_; const UValue& val() const; private: /// Check that impl_ is set or throw a runtime error. void check_() const; /// Pointer to internal data specifics. UVardata* vardata; void __init(); /// Define an attribute and its accessors. # define PRIVATE(Type, Name) \ public: \ Type get_ ## Name () \ { \ return Name; \ } \ Type get_ ## Name () const \ { \ return Name; \ } \ void set_ ## Name (const Type& v) \ { \ Name = v; \ } \ private: \ Type Name; /// Full name of the variable as seen in URBI. PRIVATE(std::string, name) /// True if the variable is a temporary and must not be stored in callbacks PRIVATE(bool, temp); PRIVATE(bool, rtp); # undef PRIVATE // Check that the invariants of this class are verified. bool invariant() const; friend class impl::UVarImpl; }; /*-------------------------. | Inline implementations. | `-------------------------*/ /// Helper macro to initialize UProps in UVar constructors. # define VAR_PROP_INIT \ rangemin(*this, PROP_RANGEMIN), \ rangemax(*this, PROP_RANGEMAX), \ speedmin(*this, PROP_SPEEDMIN), \ speedmax(*this, PROP_SPEEDMAX), \ delta(*this, PROP_DELTA), \ blend(*this, PROP_BLEND) } // end namespace urbi /// Report \a u on \a o for debugging. URBI_SDK_API std::ostream& operator<< (std::ostream& o, const urbi::UVar& u); # include <urbi/uvar.hxx> #endif // ! URBI_UVAR_HH <|endoftext|>
<commit_before>#pragma once #include "search/search_common.hpp" #include "search/search_query.hpp" #include "search/search_query_params.hpp" #include "indexer/search_trie.hpp" #include "base/mutex.hpp" #include "base/scope_guard.hpp" #include "base/stl_add.hpp" #include "base/string_utils.hpp" #include "std/algorithm.hpp" #include "std/target_os.hpp" #include "std/unique_ptr.hpp" #include "std/unordered_set.hpp" #include "std/utility.hpp" #include "std/vector.hpp" namespace search { namespace impl { template <class TSrcIter, class TCompIter> size_t CalcEqualLength(TSrcIter b, TSrcIter e, TCompIter bC, TCompIter eC) { size_t count = 0; while ((b != e) && (bC != eC) && (*b++ == *bC++)) ++count; return count; } inline shared_ptr<trie::DefaultIterator> MoveTrieIteratorToString( trie::DefaultIterator const & trieRoot, strings::UniString const & queryS, size_t & symbolsMatched, bool & bFullEdgeMatched) { symbolsMatched = 0; bFullEdgeMatched = false; auto it = trieRoot.Clone(); size_t const szQuery = queryS.size(); while (symbolsMatched < szQuery) { bool bMatched = false; ASSERT_LESS(it->m_edge.size(), std::numeric_limits<uint32_t>::max(), ()); uint32_t const edgeCount = static_cast<uint32_t>(it->m_edge.size()); for (uint32_t i = 0; i < edgeCount; ++i) { size_t const szEdge = it->m_edge[i].m_str.size(); size_t const count = CalcEqualLength(it->m_edge[i].m_str.begin(), it->m_edge[i].m_str.end(), queryS.begin() + symbolsMatched, queryS.end()); if ((count > 0) && (count == szEdge || szQuery == count + symbolsMatched)) { it = it->GoToEdge(i); bFullEdgeMatched = (count == szEdge); symbolsMatched += count; bMatched = true; break; } } if (!bMatched) return NULL; } return it->Clone(); } namespace { bool CheckMatchString(strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString & s) { if (rootPrefixSize > 0) { if (s.size() < rootPrefixSize || !StartsWith(s.begin(), s.end(), rootPrefix, rootPrefix + rootPrefixSize)) return false; s = strings::UniString(s.begin() + rootPrefixSize, s.end()); } return true; } } template <typename F> void FullMatchInTrie(trie::DefaultIterator const & trieRoot, strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString s, F & f) { if (!CheckMatchString(rootPrefix, rootPrefixSize, s)) return; size_t symbolsMatched = 0; bool bFullEdgeMatched; auto const it = MoveTrieIteratorToString(trieRoot, s, symbolsMatched, bFullEdgeMatched); if (!it || (!s.empty() && !bFullEdgeMatched) || symbolsMatched != s.size()) return; #if defined(OMIM_OS_IPHONE) && !defined(__clang__) // Here is the dummy mutex to avoid mysterious iOS GCC-LLVM bug here. static threads::Mutex dummyM; threads::MutexGuard dummyG(dummyM); #endif ASSERT_EQUAL ( symbolsMatched, s.size(), () ); for (size_t i = 0; i < it->m_value.size(); ++i) f(it->m_value[i]); } template <typename F> void PrefixMatchInTrie(trie::DefaultIterator const & trieRoot, strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString s, F & f) { if (!CheckMatchString(rootPrefix, rootPrefixSize, s)) return; using TQueue = vector<shared_ptr<trie::DefaultIterator>>; TQueue trieQueue; { size_t symbolsMatched = 0; bool bFullEdgeMatched; auto const it = MoveTrieIteratorToString(trieRoot, s, symbolsMatched, bFullEdgeMatched); UNUSED_VALUE(symbolsMatched); UNUSED_VALUE(bFullEdgeMatched); if (!it) return; trieQueue.push_back(it); } while (!trieQueue.empty()) { // Next 2 lines don't throw any exceptions while moving // ownership from container to smart pointer. auto const it = trieQueue.back(); trieQueue.pop_back(); for (size_t i = 0; i < it->m_value.size(); ++i) f(it->m_value[i]); for (size_t i = 0; i < it->m_edge.size(); ++i) trieQueue.push_back(it->GoToEdge(i)); } } template <class TFilter> class OffsetIntersecter { using ValueT = trie::ValueReader::ValueType; struct HashFn { size_t operator() (ValueT const & v) const { return v.m_featureId; } }; struct EqualFn { bool operator() (ValueT const & v1, ValueT const & v2) const { return (v1.m_featureId == v2.m_featureId); } }; using TSet = unordered_set<ValueT, HashFn, EqualFn>; TFilter const & m_filter; unique_ptr<TSet> m_prevSet; unique_ptr<TSet> m_set; public: explicit OffsetIntersecter(TFilter const & filter) : m_filter(filter), m_set(new TSet) {} void operator() (ValueT const & v) { if (m_prevSet && !m_prevSet->count(v)) return; if (!m_filter(v.m_featureId)) return; m_set->insert(v); } void NextStep() { if (!m_prevSet) m_prevSet.reset(new TSet); m_prevSet.swap(m_set); m_set->clear(); } template <class ToDo> void ForEachResult(ToDo && toDo) const { if (!m_prevSet) return; for (auto const & value : *m_prevSet) toDo(value); } }; } // namespace search::impl struct TrieRootPrefix { trie::DefaultIterator const & m_root; strings::UniChar const * m_prefix; size_t m_prefixSize; TrieRootPrefix(trie::DefaultIterator const & root, trie::DefaultIterator::Edge::EdgeStrT const & edge) : m_root(root) { if (edge.size() == 1) { m_prefix = 0; m_prefixSize = 0; } else { m_prefix = &edge[1]; m_prefixSize = edge.size() - 1; } } }; template <class TFilter> class TrieValuesHolder { public: TrieValuesHolder(TFilter const & filter) : m_filter(filter) {} void Resize(size_t count) { m_holder.resize(count); } void SwitchTo(size_t index) { ASSERT_LESS(index, m_holder.size(), ()); m_index = index; } void operator()(Query::TTrieValue const & v) { if (m_filter(v.m_featureId)) m_holder[m_index].push_back(v); } template <class ToDo> void ForEachValue(size_t index, ToDo && toDo) const { for (auto const & value : m_holder[index]) toDo(value); } private: vector<vector<Query::TTrieValue>> m_holder; size_t m_index; TFilter const & m_filter; }; // Calls toDo for each feature corresponding to at least one synonym. // *NOTE* toDo may be called several times for the same feature. template <typename ToDo> void MatchTokenInTrie(SearchQueryParams::TSynonymsVector const & syns, TrieRootPrefix const & trieRoot, ToDo && toDo) { for (auto const & syn : syns) { ASSERT(!syn.empty(), ()); impl::FullMatchInTrie(trieRoot.m_root, trieRoot.m_prefix, trieRoot.m_prefixSize, syn, toDo); } } // Calls toDo for each feature whose tokens contains at least one // synonym as a prefix. // *NOTE* toDo may be called serveral times for the same feature. template <typename ToDo> void MatchTokenPrefixInTrie(SearchQueryParams::TSynonymsVector const & syns, TrieRootPrefix const & trieRoot, ToDo && toDo) { for (auto const & syn : syns) { ASSERT(!syn.empty(), ()); impl::PrefixMatchInTrie(trieRoot.m_root, trieRoot.m_prefix, trieRoot.m_prefixSize, syn, toDo); } } // Fills holder with features whose names correspond to tokens list up to synonyms. // *NOTE* the same feature may be put in the same holder's slot several times. template <typename THolder> void MatchTokensInTrie(vector<SearchQueryParams::TSynonymsVector> const & tokens, TrieRootPrefix const & trieRoot, THolder && holder) { holder.Resize(tokens.size()); for (size_t i = 0; i < tokens.size(); ++i) { holder.SwitchTo(i); MatchTokenInTrie(tokens[i], trieRoot, holder); } } // Fills holder with features whose names correspond to tokens list up to synonyms, // also, last holder's slot will be filled with features corresponding to prefixTokens. // *NOTE* the same feature may be put in the same holder's slot several times. template <typename THolder> void MatchTokensAndPrefixInTrie(vector<SearchQueryParams::TSynonymsVector> const & tokens, SearchQueryParams::TSynonymsVector const & prefixTokens, TrieRootPrefix const & trieRoot, THolder && holder) { MatchTokensInTrie(tokens, trieRoot, holder); holder.Resize(tokens.size() + 1); holder.SwitchTo(tokens.size()); MatchTokenPrefixInTrie(prefixTokens, trieRoot, holder); } // Fills holder with categories whose description matches to at least one // token from a search query. // *NOTE* query prefix will be treated as a complete token in the function. template <typename THolder> bool MatchCategoriesInTrie(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, THolder && holder) { ASSERT_LESS(trieRoot.m_edge.size(), numeric_limits<uint32_t>::max(), ()); uint32_t const numLangs = static_cast<uint32_t>(trieRoot.m_edge.size()); for (uint32_t langIx = 0; langIx < numLangs; ++langIx) { auto const & edge = trieRoot.m_edge[langIx].m_str; ASSERT_GREATER_OR_EQUAL(edge.size(), 1, ()); if (edge[0] == search::kCategoriesLang) { auto const catRoot = trieRoot.GoToEdge(langIx); MatchTokensInTrie(params.m_tokens, TrieRootPrefix(*catRoot, edge), holder); // Last token's prefix is used as a complete token here, to // limit the number of features in the last bucket of a // holder. Probably, this is a false optimization. holder.Resize(params.m_tokens.size() + 1); holder.SwitchTo(params.m_tokens.size()); MatchTokenInTrie(params.m_prefixTokens, TrieRootPrefix(*catRoot, edge), holder); return true; } } return false; } // Calls toDo with trie root prefix and language code on each language // allowed by params. template <typename ToDo> void ForEachLangPrefix(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, ToDo && toDo) { ASSERT_LESS(trieRoot.m_edge.size(), numeric_limits<uint32_t>::max(), ()); uint32_t const numLangs = static_cast<uint32_t>(trieRoot.m_edge.size()); for (uint32_t langIx = 0; langIx < numLangs; ++langIx) { auto const & edge = trieRoot.m_edge[langIx].m_str; ASSERT_GREATER_OR_EQUAL(edge.size(), 1, ()); int8_t const lang = static_cast<int8_t>(edge[0]); if (edge[0] < search::kCategoriesLang && params.IsLangExist(lang)) { auto const langRoot = trieRoot.GoToEdge(langIx); TrieRootPrefix langPrefix(*langRoot, edge); toDo(langPrefix, lang); } } } // Calls toDo for each feature whose description contains *ALL* tokens from a search query. // Each feature will be passed to toDo only once. template <typename TFilter, typename ToDo> void MatchFeaturesInTrie(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, TFilter const & filter, ToDo && toDo) { TrieValuesHolder<TFilter> categoriesHolder(filter); if (!MatchCategoriesInTrie(params, trieRoot, categoriesHolder)) { LOG(LERROR, ("Can't find categories.")); return; } impl::OffsetIntersecter<TFilter> intersecter(filter); for (size_t i = 0; i < params.m_tokens.size(); ++i) { ForEachLangPrefix(params, trieRoot, [&](TrieRootPrefix & langRoot, int8_t lang) { MatchTokenInTrie(params.m_tokens[i], langRoot, intersecter); }); categoriesHolder.ForEachValue(i, intersecter); intersecter.NextStep(); } if (!params.m_prefixTokens.empty()) { ForEachLangPrefix(params, trieRoot, [&](TrieRootPrefix & langRoot, int8_t /* lang */) { MatchTokenPrefixInTrie(params.m_prefixTokens, langRoot, intersecter); }); categoriesHolder.ForEachValue(params.m_tokens.size(), intersecter); intersecter.NextStep(); } intersecter.ForEachResult(forward<ToDo>(toDo)); } } // namespace search <commit_msg>[search] Fixed retrieval on Mwms without categories section.<commit_after>#pragma once #include "search/search_common.hpp" #include "search/search_query.hpp" #include "search/search_query_params.hpp" #include "indexer/search_trie.hpp" #include "base/mutex.hpp" #include "base/scope_guard.hpp" #include "base/stl_add.hpp" #include "base/string_utils.hpp" #include "std/algorithm.hpp" #include "std/target_os.hpp" #include "std/unique_ptr.hpp" #include "std/unordered_set.hpp" #include "std/utility.hpp" #include "std/vector.hpp" namespace search { namespace impl { template <class TSrcIter, class TCompIter> size_t CalcEqualLength(TSrcIter b, TSrcIter e, TCompIter bC, TCompIter eC) { size_t count = 0; while ((b != e) && (bC != eC) && (*b++ == *bC++)) ++count; return count; } inline shared_ptr<trie::DefaultIterator> MoveTrieIteratorToString( trie::DefaultIterator const & trieRoot, strings::UniString const & queryS, size_t & symbolsMatched, bool & bFullEdgeMatched) { symbolsMatched = 0; bFullEdgeMatched = false; auto it = trieRoot.Clone(); size_t const szQuery = queryS.size(); while (symbolsMatched < szQuery) { bool bMatched = false; ASSERT_LESS(it->m_edge.size(), std::numeric_limits<uint32_t>::max(), ()); uint32_t const edgeCount = static_cast<uint32_t>(it->m_edge.size()); for (uint32_t i = 0; i < edgeCount; ++i) { size_t const szEdge = it->m_edge[i].m_str.size(); size_t const count = CalcEqualLength(it->m_edge[i].m_str.begin(), it->m_edge[i].m_str.end(), queryS.begin() + symbolsMatched, queryS.end()); if ((count > 0) && (count == szEdge || szQuery == count + symbolsMatched)) { it = it->GoToEdge(i); bFullEdgeMatched = (count == szEdge); symbolsMatched += count; bMatched = true; break; } } if (!bMatched) return NULL; } return it->Clone(); } namespace { bool CheckMatchString(strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString & s) { if (rootPrefixSize > 0) { if (s.size() < rootPrefixSize || !StartsWith(s.begin(), s.end(), rootPrefix, rootPrefix + rootPrefixSize)) return false; s = strings::UniString(s.begin() + rootPrefixSize, s.end()); } return true; } } template <typename F> void FullMatchInTrie(trie::DefaultIterator const & trieRoot, strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString s, F & f) { if (!CheckMatchString(rootPrefix, rootPrefixSize, s)) return; size_t symbolsMatched = 0; bool bFullEdgeMatched; auto const it = MoveTrieIteratorToString(trieRoot, s, symbolsMatched, bFullEdgeMatched); if (!it || (!s.empty() && !bFullEdgeMatched) || symbolsMatched != s.size()) return; #if defined(OMIM_OS_IPHONE) && !defined(__clang__) // Here is the dummy mutex to avoid mysterious iOS GCC-LLVM bug here. static threads::Mutex dummyM; threads::MutexGuard dummyG(dummyM); #endif ASSERT_EQUAL ( symbolsMatched, s.size(), () ); for (size_t i = 0; i < it->m_value.size(); ++i) f(it->m_value[i]); } template <typename F> void PrefixMatchInTrie(trie::DefaultIterator const & trieRoot, strings::UniChar const * rootPrefix, size_t rootPrefixSize, strings::UniString s, F & f) { if (!CheckMatchString(rootPrefix, rootPrefixSize, s)) return; using TQueue = vector<shared_ptr<trie::DefaultIterator>>; TQueue trieQueue; { size_t symbolsMatched = 0; bool bFullEdgeMatched; auto const it = MoveTrieIteratorToString(trieRoot, s, symbolsMatched, bFullEdgeMatched); UNUSED_VALUE(symbolsMatched); UNUSED_VALUE(bFullEdgeMatched); if (!it) return; trieQueue.push_back(it); } while (!trieQueue.empty()) { // Next 2 lines don't throw any exceptions while moving // ownership from container to smart pointer. auto const it = trieQueue.back(); trieQueue.pop_back(); for (size_t i = 0; i < it->m_value.size(); ++i) f(it->m_value[i]); for (size_t i = 0; i < it->m_edge.size(); ++i) trieQueue.push_back(it->GoToEdge(i)); } } template <class TFilter> class OffsetIntersecter { using ValueT = trie::ValueReader::ValueType; struct HashFn { size_t operator() (ValueT const & v) const { return v.m_featureId; } }; struct EqualFn { bool operator() (ValueT const & v1, ValueT const & v2) const { return (v1.m_featureId == v2.m_featureId); } }; using TSet = unordered_set<ValueT, HashFn, EqualFn>; TFilter const & m_filter; unique_ptr<TSet> m_prevSet; unique_ptr<TSet> m_set; public: explicit OffsetIntersecter(TFilter const & filter) : m_filter(filter), m_set(new TSet) {} void operator() (ValueT const & v) { if (m_prevSet && !m_prevSet->count(v)) return; if (!m_filter(v.m_featureId)) return; m_set->insert(v); } void NextStep() { if (!m_prevSet) m_prevSet.reset(new TSet); m_prevSet.swap(m_set); m_set->clear(); } template <class ToDo> void ForEachResult(ToDo && toDo) const { if (!m_prevSet) return; for (auto const & value : *m_prevSet) toDo(value); } }; } // namespace search::impl struct TrieRootPrefix { trie::DefaultIterator const & m_root; strings::UniChar const * m_prefix; size_t m_prefixSize; TrieRootPrefix(trie::DefaultIterator const & root, trie::DefaultIterator::Edge::EdgeStrT const & edge) : m_root(root) { if (edge.size() == 1) { m_prefix = 0; m_prefixSize = 0; } else { m_prefix = &edge[1]; m_prefixSize = edge.size() - 1; } } }; template <class TFilter> class TrieValuesHolder { public: TrieValuesHolder(TFilter const & filter) : m_filter(filter) {} void Resize(size_t count) { m_holder.resize(count); } void SwitchTo(size_t index) { ASSERT_LESS(index, m_holder.size(), ()); m_index = index; } void operator()(Query::TTrieValue const & v) { if (m_filter(v.m_featureId)) m_holder[m_index].push_back(v); } template <class ToDo> void ForEachValue(size_t index, ToDo && toDo) const { ASSERT_LESS(index, m_holder.size(), ()); for (auto const & value : m_holder[index]) toDo(value); } private: vector<vector<Query::TTrieValue>> m_holder; size_t m_index; TFilter const & m_filter; }; // Calls toDo for each feature corresponding to at least one synonym. // *NOTE* toDo may be called several times for the same feature. template <typename ToDo> void MatchTokenInTrie(SearchQueryParams::TSynonymsVector const & syns, TrieRootPrefix const & trieRoot, ToDo && toDo) { for (auto const & syn : syns) { ASSERT(!syn.empty(), ()); impl::FullMatchInTrie(trieRoot.m_root, trieRoot.m_prefix, trieRoot.m_prefixSize, syn, toDo); } } // Calls toDo for each feature whose tokens contains at least one // synonym as a prefix. // *NOTE* toDo may be called serveral times for the same feature. template <typename ToDo> void MatchTokenPrefixInTrie(SearchQueryParams::TSynonymsVector const & syns, TrieRootPrefix const & trieRoot, ToDo && toDo) { for (auto const & syn : syns) { ASSERT(!syn.empty(), ()); impl::PrefixMatchInTrie(trieRoot.m_root, trieRoot.m_prefix, trieRoot.m_prefixSize, syn, toDo); } } // Fills holder with features whose names correspond to tokens list up to synonyms. // *NOTE* the same feature may be put in the same holder's slot several times. template <typename THolder> void MatchTokensInTrie(vector<SearchQueryParams::TSynonymsVector> const & tokens, TrieRootPrefix const & trieRoot, THolder && holder) { holder.Resize(tokens.size()); for (size_t i = 0; i < tokens.size(); ++i) { holder.SwitchTo(i); MatchTokenInTrie(tokens[i], trieRoot, holder); } } // Fills holder with features whose names correspond to tokens list up to synonyms, // also, last holder's slot will be filled with features corresponding to prefixTokens. // *NOTE* the same feature may be put in the same holder's slot several times. template <typename THolder> void MatchTokensAndPrefixInTrie(vector<SearchQueryParams::TSynonymsVector> const & tokens, SearchQueryParams::TSynonymsVector const & prefixTokens, TrieRootPrefix const & trieRoot, THolder && holder) { MatchTokensInTrie(tokens, trieRoot, holder); holder.Resize(tokens.size() + 1); holder.SwitchTo(tokens.size()); MatchTokenPrefixInTrie(prefixTokens, trieRoot, holder); } // Fills holder with categories whose description matches to at least one // token from a search query. // *NOTE* query prefix will be treated as a complete token in the function. template <typename THolder> bool MatchCategoriesInTrie(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, THolder && holder) { ASSERT_LESS(trieRoot.m_edge.size(), numeric_limits<uint32_t>::max(), ()); uint32_t const numLangs = static_cast<uint32_t>(trieRoot.m_edge.size()); for (uint32_t langIx = 0; langIx < numLangs; ++langIx) { auto const & edge = trieRoot.m_edge[langIx].m_str; ASSERT_GREATER_OR_EQUAL(edge.size(), 1, ()); if (edge[0] == search::kCategoriesLang) { auto const catRoot = trieRoot.GoToEdge(langIx); MatchTokensInTrie(params.m_tokens, TrieRootPrefix(*catRoot, edge), holder); // Last token's prefix is used as a complete token here, to // limit the number of features in the last bucket of a // holder. Probably, this is a false optimization. holder.Resize(params.m_tokens.size() + 1); holder.SwitchTo(params.m_tokens.size()); MatchTokenInTrie(params.m_prefixTokens, TrieRootPrefix(*catRoot, edge), holder); return true; } } return false; } // Calls toDo with trie root prefix and language code on each language // allowed by params. template <typename ToDo> void ForEachLangPrefix(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, ToDo && toDo) { ASSERT_LESS(trieRoot.m_edge.size(), numeric_limits<uint32_t>::max(), ()); uint32_t const numLangs = static_cast<uint32_t>(trieRoot.m_edge.size()); for (uint32_t langIx = 0; langIx < numLangs; ++langIx) { auto const & edge = trieRoot.m_edge[langIx].m_str; ASSERT_GREATER_OR_EQUAL(edge.size(), 1, ()); int8_t const lang = static_cast<int8_t>(edge[0]); if (edge[0] < search::kCategoriesLang && params.IsLangExist(lang)) { auto const langRoot = trieRoot.GoToEdge(langIx); TrieRootPrefix langPrefix(*langRoot, edge); toDo(langPrefix, lang); } } } // Calls toDo for each feature whose description contains *ALL* tokens from a search query. // Each feature will be passed to toDo only once. template <typename TFilter, typename ToDo> void MatchFeaturesInTrie(SearchQueryParams const & params, trie::DefaultIterator const & trieRoot, TFilter const & filter, ToDo && toDo) { TrieValuesHolder<TFilter> categoriesHolder(filter); bool const categoriesMatched = MatchCategoriesInTrie(params, trieRoot, categoriesHolder); impl::OffsetIntersecter<TFilter> intersecter(filter); for (size_t i = 0; i < params.m_tokens.size(); ++i) { ForEachLangPrefix(params, trieRoot, [&](TrieRootPrefix & langRoot, int8_t lang) { MatchTokenInTrie(params.m_tokens[i], langRoot, intersecter); }); if (categoriesMatched) categoriesHolder.ForEachValue(i, intersecter); intersecter.NextStep(); } if (!params.m_prefixTokens.empty()) { ForEachLangPrefix(params, trieRoot, [&](TrieRootPrefix & langRoot, int8_t /* lang */) { MatchTokenPrefixInTrie(params.m_prefixTokens, langRoot, intersecter); }); if (categoriesMatched) categoriesHolder.ForEachValue(params.m_tokens.size(), intersecter); intersecter.NextStep(); } intersecter.ForEachResult(forward<ToDo>(toDo)); } } // namespace search <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "ProxyDestination.h" #include <folly/Conv.h> #include <folly/Memory.h> #include "mcrouter/config-impl.h" #include "mcrouter/config.h" #include "mcrouter/lib/fbi/asox_timer.h" #include "mcrouter/lib/fbi/nstring.h" #include "mcrouter/lib/fbi/timer.h" #include "mcrouter/lib/fbi/util.h" #include "mcrouter/lib/fibers/Fiber.h" #include "mcrouter/lib/network/AsyncMcClient.h" #include "mcrouter/pclient.h" #include "mcrouter/ProxyClientCommon.h" #include "mcrouter/routes/DestinationRoute.h" #include "mcrouter/stats.h" #include "mcrouter/TkoTracker.h" namespace facebook { namespace memcache { namespace mcrouter { namespace { constexpr double kProbeExponentialFactor = 1.5; constexpr double kProbeJitterMin = 0.05; constexpr double kProbeJitterMax = 0.5; constexpr double kProbeJitterDelta = kProbeJitterMax - kProbeJitterMin; static_assert(kProbeJitterMax >= kProbeJitterMin, "ProbeJitterMax should be greater or equal tham ProbeJitterMin"); void on_probe_timer(const asox_timer_t timer, void* arg) { ProxyDestination* pdstn = (ProxyDestination*)arg; pdstn->on_timer(timer); } } // anonymous namespace void ProxyDestination::schedule_next_probe() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(!proxy->opts.disable_tko_tracking); int delay_ms = probe_delay_next_ms; if (probe_delay_next_ms < 2) { // int(1 * 1.5) == 1, so advance it to 2 first probe_delay_next_ms = 2; } else { probe_delay_next_ms *= kProbeExponentialFactor; } if (probe_delay_next_ms > proxy->opts.probe_delay_max_ms) { probe_delay_next_ms = proxy->opts.probe_delay_max_ms; } // Calculate random jitter double r = (double)rand() / (double)RAND_MAX; double tmo_jitter_pct = r * kProbeJitterDelta + kProbeJitterMin; uint64_t delay_us = (double)delay_ms * 1000 * (1.0 + tmo_jitter_pct); FBI_ASSERT(delay_us > 0); timeval_t delay; delay.tv_sec = (delay_us / 1000000); delay.tv_usec = (delay_us % 1000000); FBI_ASSERT(probe_timer == nullptr); probe_timer = asox_add_timer(proxy->eventBase->getLibeventBase(), delay, on_probe_timer, this); } void ProxyDestination::on_timer(const asox_timer_t timer) { // This assert checks for use-after-free FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(timer == probe_timer); asox_remove_timer(timer); probe_timer = nullptr; if (sending_probes) { // Note that the previous probe might still be in flight if (!probe_req) { auto mutReq = createMcMsgRef(); mutReq->op = mc_op_version; probe_req = folly::make_unique<McRequest>(std::move(mutReq)); ++probesSent_; auto selfPtr = selfPtr_; proxy->fiberManager.addTask([selfPtr]() mutable { auto pdstn = selfPtr.lock(); if (pdstn == nullptr) { return; } pdstn->proxy->destinationMap->markAsActive(*pdstn); McReply reply = pdstn->client_->send(*pdstn->probe_req, McOperation<mc_op_version>(), 0); pdstn->handle_tko(reply, true); pdstn->probe_req.reset(); }); } schedule_next_probe(); } } void ProxyDestination::start_sending_probes() { FBI_ASSERT(!sending_probes); sending_probes = true; probe_delay_next_ms = proxy->opts.probe_delay_initial_ms; schedule_next_probe(); } void ProxyDestination::stop_sending_probes() { probesSent_ = 0; sending_probes = false; if (probe_timer) { asox_remove_timer(probe_timer); probe_timer = nullptr; } } void ProxyDestination::unmark_tko(const McReply& reply) { FBI_ASSERT(!proxy->opts.disable_tko_tracking); shared->tko.recordSuccess(this); if (sending_probes) { onTkoEvent(TkoLogEvent::UnMarkTko, reply.result()); stop_sending_probes(); } } void ProxyDestination::handle_tko(const McReply& reply, bool is_probe_req) { if (resetting || proxy->opts.disable_tko_tracking) { return; } bool responsible = false; if (reply.isError()) { if (reply.isHardTkoError()) { responsible = shared->tko.recordHardFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkHardTko, reply.result()); } } else if (reply.isSoftTkoError()) { responsible = shared->tko.recordSoftFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkSoftTko, reply.result()); } } } else if (!sending_probes || is_probe_req) { /* If we're sending probes, only a probe request should be considered successful to avoid outstanding requests from unmarking the box */ unmark_tko(reply); } if (responsible) { start_sending_probes(); } } void ProxyDestination::onReply(const McReply& reply, DestinationRequestCtx& destreqCtx) { FBI_ASSERT(proxy->magic == proxy_magic); handle_tko(reply, false); stats_.results[reply.result()]++; destreqCtx.endTime = nowUs(); /* For code simplicity we look at latency for making TKO decisions with a 1 request delay */ int64_t latency = destreqCtx.endTime - destreqCtx.startTime; stats_.avgLatency.insertSample(latency); stat_decr(proxy->stats, sum_server_queue_length_stat, 1); } void ProxyDestination::on_up() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(state() != ProxyDestinationState::kUp); stat_incr(proxy->stats, server_up_events_stat, 1); setState(ProxyDestinationState::kUp); VLOG(1) << "server " << pdstnKey << " up (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; } void ProxyDestination::on_down() { FBI_ASSERT(proxy->magic == proxy_magic); if (resetting) { VLOG(1) << "server " << pdstnKey << " inactive (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kClosed); } else { VLOG(1) << "server " << pdstnKey << " down (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kTko); handle_tko(McReply(mc_res_connect_error), /* is_probe_req= */ false); } } size_t ProxyDestination::getPendingRequestCount() const { return client_->getPendingRequestCount(); } size_t ProxyDestination::getInflightRequestCount() const { return client_->getInflightRequestCount(); } std::pair<uint64_t, uint64_t> ProxyDestination::getBatchingStat() const { return client_->getBatchingStat(); } std::shared_ptr<ProxyDestination> ProxyDestination::create( proxy_t* proxy, const ProxyClientCommon& ro, std::string pdstnKey) { auto ptr = std::shared_ptr<ProxyDestination>( new ProxyDestination(proxy, ro, std::move(pdstnKey))); ptr->selfPtr_ = ptr; ptr->client_ = folly::make_unique<DestinationMcClient>(*ptr); return ptr; } ProxyDestination::~ProxyDestination() { shared->removeDestination(this); if (proxy->destinationMap) { proxy->destinationMap->removeDestination(*this); } // should not call 'handle_tko' resetting = 1; client_.reset(); if (sending_probes) { onTkoEvent(TkoLogEvent::RemoveFromConfig, mc_res_ok); stop_sending_probes(); } magic = kDeadBeef; } ProxyDestination::ProxyDestination(proxy_t* proxy_, const ProxyClientCommon& ro_, std::string pdstnKey_) : proxy(proxy_), accessPoint(ro_.ap), destinationKey(ro_.destination_key), server_timeout(ro_.server_timeout), pdstnKey(std::move(pdstnKey_)), proxy_magic(proxy->magic), use_ssl(ro_.useSsl), qos(ro_.qos), stats_(proxy_->opts) { static uint64_t next_magic = 0x12345678900000LL; magic = __sync_fetch_and_add(&next_magic, 1); stat_incr(proxy->stats, num_servers_new_stat, 1); } ProxyDestinationState ProxyDestination::state() const { if (shared->tko.isTko()) { return ProxyDestinationState::kTko; } return stats_.state; } const ProxyDestinationStats& ProxyDestination::stats() const { return stats_; } bool ProxyDestination::may_send() { FBI_ASSERT(proxy->magic == proxy_magic); return state() != ProxyDestinationState::kTko; } void ProxyDestination::resetInactive() { FBI_ASSERT(proxy->magic == proxy_magic); resetting = 1; client_->resetInactive(); resetting = 0; } void ProxyDestination::onTkoEvent(TkoLogEvent event, mc_res_t result) const { auto logUtil = [this, result](folly::StringPiece eventStr) { VLOG(1) << shared->key << " " << eventStr << ". Total hard TKOs: " << shared->tko.globalTkos().hardTkos << "; soft TKOs: " << shared->tko.globalTkos().softTkos << ". Reply: " << mc_res_to_string(result); }; switch (event) { case TkoLogEvent::MarkHardTko: logUtil("marked hard TKO"); break; case TkoLogEvent::MarkSoftTko: logUtil("marked soft TKO"); break; case TkoLogEvent::UnMarkTko: logUtil("unmarked TKO"); break; case TkoLogEvent::RemoveFromConfig: logUtil("was TKO, removed from config"); break; } TkoLog tkoLog(accessPoint, shared->tko.globalTkos()); tkoLog.event = event; tkoLog.isHardTko = shared->tko.isHardTko(); tkoLog.isSoftTko = shared->tko.isSoftTko(); tkoLog.avgLatency = stats_.avgLatency.value(); tkoLog.probesSent = probesSent_; tkoLog.result = result; logTkoEvent(proxy, tkoLog); } void ProxyDestination::setState(ProxyDestinationState new_st) { auto old_st = state(); if (old_st != new_st) { auto getStatName = [](ProxyDestinationState st) { switch (st) { case ProxyDestinationState::kNew: return num_servers_new_stat; case ProxyDestinationState::kUp: return num_servers_up_stat; case ProxyDestinationState::kClosed: return num_servers_closed_stat; case ProxyDestinationState::kTko: return num_servers_down_stat; default: CHECK(false); return num_stats; // shouldnt reach here } }; auto old_name = getStatName(old_st); auto new_name = getStatName(new_st); stat_decr(proxy->stats, old_name, 1); stat_incr(proxy->stats, new_name, 1); stats_.state = new_st; } } ProxyDestinationStats::ProxyDestinationStats(const McrouterOptions& opts) : avgLatency(1.0 / opts.latency_window_size) { } }}} // facebook::memcache::mcrouter <commit_msg>fix crash due to incorrect state setting<commit_after>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "ProxyDestination.h" #include <folly/Conv.h> #include <folly/Memory.h> #include "mcrouter/config-impl.h" #include "mcrouter/config.h" #include "mcrouter/lib/fbi/asox_timer.h" #include "mcrouter/lib/fbi/nstring.h" #include "mcrouter/lib/fbi/timer.h" #include "mcrouter/lib/fbi/util.h" #include "mcrouter/lib/fibers/Fiber.h" #include "mcrouter/lib/network/AsyncMcClient.h" #include "mcrouter/pclient.h" #include "mcrouter/ProxyClientCommon.h" #include "mcrouter/routes/DestinationRoute.h" #include "mcrouter/stats.h" #include "mcrouter/TkoTracker.h" namespace facebook { namespace memcache { namespace mcrouter { namespace { constexpr double kProbeExponentialFactor = 1.5; constexpr double kProbeJitterMin = 0.05; constexpr double kProbeJitterMax = 0.5; constexpr double kProbeJitterDelta = kProbeJitterMax - kProbeJitterMin; static_assert(kProbeJitterMax >= kProbeJitterMin, "ProbeJitterMax should be greater or equal tham ProbeJitterMin"); void on_probe_timer(const asox_timer_t timer, void* arg) { ProxyDestination* pdstn = (ProxyDestination*)arg; pdstn->on_timer(timer); } } // anonymous namespace void ProxyDestination::schedule_next_probe() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(!proxy->opts.disable_tko_tracking); int delay_ms = probe_delay_next_ms; if (probe_delay_next_ms < 2) { // int(1 * 1.5) == 1, so advance it to 2 first probe_delay_next_ms = 2; } else { probe_delay_next_ms *= kProbeExponentialFactor; } if (probe_delay_next_ms > proxy->opts.probe_delay_max_ms) { probe_delay_next_ms = proxy->opts.probe_delay_max_ms; } // Calculate random jitter double r = (double)rand() / (double)RAND_MAX; double tmo_jitter_pct = r * kProbeJitterDelta + kProbeJitterMin; uint64_t delay_us = (double)delay_ms * 1000 * (1.0 + tmo_jitter_pct); FBI_ASSERT(delay_us > 0); timeval_t delay; delay.tv_sec = (delay_us / 1000000); delay.tv_usec = (delay_us % 1000000); FBI_ASSERT(probe_timer == nullptr); probe_timer = asox_add_timer(proxy->eventBase->getLibeventBase(), delay, on_probe_timer, this); } void ProxyDestination::on_timer(const asox_timer_t timer) { // This assert checks for use-after-free FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(timer == probe_timer); asox_remove_timer(timer); probe_timer = nullptr; if (sending_probes) { // Note that the previous probe might still be in flight if (!probe_req) { auto mutReq = createMcMsgRef(); mutReq->op = mc_op_version; probe_req = folly::make_unique<McRequest>(std::move(mutReq)); ++probesSent_; auto selfPtr = selfPtr_; proxy->fiberManager.addTask([selfPtr]() mutable { auto pdstn = selfPtr.lock(); if (pdstn == nullptr) { return; } pdstn->proxy->destinationMap->markAsActive(*pdstn); McReply reply = pdstn->client_->send(*pdstn->probe_req, McOperation<mc_op_version>(), 0); pdstn->handle_tko(reply, true); pdstn->probe_req.reset(); }); } schedule_next_probe(); } } void ProxyDestination::start_sending_probes() { FBI_ASSERT(!sending_probes); sending_probes = true; probe_delay_next_ms = proxy->opts.probe_delay_initial_ms; schedule_next_probe(); } void ProxyDestination::stop_sending_probes() { probesSent_ = 0; sending_probes = false; if (probe_timer) { asox_remove_timer(probe_timer); probe_timer = nullptr; } } void ProxyDestination::unmark_tko(const McReply& reply) { FBI_ASSERT(!proxy->opts.disable_tko_tracking); shared->tko.recordSuccess(this); if (sending_probes) { onTkoEvent(TkoLogEvent::UnMarkTko, reply.result()); stop_sending_probes(); } } void ProxyDestination::handle_tko(const McReply& reply, bool is_probe_req) { if (resetting || proxy->opts.disable_tko_tracking) { return; } bool responsible = false; if (reply.isError()) { if (reply.isHardTkoError()) { responsible = shared->tko.recordHardFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkHardTko, reply.result()); } } else if (reply.isSoftTkoError()) { responsible = shared->tko.recordSoftFailure(this); if (responsible) { onTkoEvent(TkoLogEvent::MarkSoftTko, reply.result()); } } } else if (!sending_probes || is_probe_req) { /* If we're sending probes, only a probe request should be considered successful to avoid outstanding requests from unmarking the box */ unmark_tko(reply); } if (responsible) { start_sending_probes(); } } void ProxyDestination::onReply(const McReply& reply, DestinationRequestCtx& destreqCtx) { FBI_ASSERT(proxy->magic == proxy_magic); handle_tko(reply, false); stats_.results[reply.result()]++; destreqCtx.endTime = nowUs(); /* For code simplicity we look at latency for making TKO decisions with a 1 request delay */ int64_t latency = destreqCtx.endTime - destreqCtx.startTime; stats_.avgLatency.insertSample(latency); stat_decr(proxy->stats, sum_server_queue_length_stat, 1); } void ProxyDestination::on_up() { FBI_ASSERT(proxy->magic == proxy_magic); FBI_ASSERT(stats_.state != ProxyDestinationState::kUp); stat_incr(proxy->stats, server_up_events_stat, 1); setState(ProxyDestinationState::kUp); VLOG(1) << "server " << pdstnKey << " up (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; } void ProxyDestination::on_down() { FBI_ASSERT(proxy->magic == proxy_magic); if (resetting) { VLOG(1) << "server " << pdstnKey << " inactive (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kClosed); } else { VLOG(1) << "server " << pdstnKey << " down (" << stat_get_uint64(proxy->stats, num_servers_up_stat) << " of " << stat_get_uint64(proxy->stats, num_servers_stat) << ")"; setState(ProxyDestinationState::kTko); handle_tko(McReply(mc_res_connect_error), /* is_probe_req= */ false); } } size_t ProxyDestination::getPendingRequestCount() const { return client_->getPendingRequestCount(); } size_t ProxyDestination::getInflightRequestCount() const { return client_->getInflightRequestCount(); } std::pair<uint64_t, uint64_t> ProxyDestination::getBatchingStat() const { return client_->getBatchingStat(); } std::shared_ptr<ProxyDestination> ProxyDestination::create( proxy_t* proxy, const ProxyClientCommon& ro, std::string pdstnKey) { auto ptr = std::shared_ptr<ProxyDestination>( new ProxyDestination(proxy, ro, std::move(pdstnKey))); ptr->selfPtr_ = ptr; ptr->client_ = folly::make_unique<DestinationMcClient>(*ptr); return ptr; } ProxyDestination::~ProxyDestination() { shared->removeDestination(this); if (proxy->destinationMap) { proxy->destinationMap->removeDestination(*this); } // should not call 'handle_tko' resetting = 1; client_.reset(); if (sending_probes) { onTkoEvent(TkoLogEvent::RemoveFromConfig, mc_res_ok); stop_sending_probes(); } magic = kDeadBeef; } ProxyDestination::ProxyDestination(proxy_t* proxy_, const ProxyClientCommon& ro_, std::string pdstnKey_) : proxy(proxy_), accessPoint(ro_.ap), destinationKey(ro_.destination_key), server_timeout(ro_.server_timeout), pdstnKey(std::move(pdstnKey_)), proxy_magic(proxy->magic), use_ssl(ro_.useSsl), qos(ro_.qos), stats_(proxy_->opts) { static uint64_t next_magic = 0x12345678900000LL; magic = __sync_fetch_and_add(&next_magic, 1); stat_incr(proxy->stats, num_servers_new_stat, 1); } ProxyDestinationState ProxyDestination::state() const { if (shared->tko.isTko()) { return ProxyDestinationState::kTko; } return stats_.state; } const ProxyDestinationStats& ProxyDestination::stats() const { return stats_; } bool ProxyDestination::may_send() { FBI_ASSERT(proxy->magic == proxy_magic); return state() != ProxyDestinationState::kTko; } void ProxyDestination::resetInactive() { FBI_ASSERT(proxy->magic == proxy_magic); resetting = 1; client_->resetInactive(); resetting = 0; } void ProxyDestination::onTkoEvent(TkoLogEvent event, mc_res_t result) const { auto logUtil = [this, result](folly::StringPiece eventStr) { VLOG(1) << shared->key << " " << eventStr << ". Total hard TKOs: " << shared->tko.globalTkos().hardTkos << "; soft TKOs: " << shared->tko.globalTkos().softTkos << ". Reply: " << mc_res_to_string(result); }; switch (event) { case TkoLogEvent::MarkHardTko: logUtil("marked hard TKO"); break; case TkoLogEvent::MarkSoftTko: logUtil("marked soft TKO"); break; case TkoLogEvent::UnMarkTko: logUtil("unmarked TKO"); break; case TkoLogEvent::RemoveFromConfig: logUtil("was TKO, removed from config"); break; } TkoLog tkoLog(accessPoint, shared->tko.globalTkos()); tkoLog.event = event; tkoLog.isHardTko = shared->tko.isHardTko(); tkoLog.isSoftTko = shared->tko.isSoftTko(); tkoLog.avgLatency = stats_.avgLatency.value(); tkoLog.probesSent = probesSent_; tkoLog.result = result; logTkoEvent(proxy, tkoLog); } void ProxyDestination::setState(ProxyDestinationState new_st) { auto old_st = stats_.state; if (old_st != new_st) { auto getStatName = [](ProxyDestinationState st) { switch (st) { case ProxyDestinationState::kNew: return num_servers_new_stat; case ProxyDestinationState::kUp: return num_servers_up_stat; case ProxyDestinationState::kClosed: return num_servers_closed_stat; case ProxyDestinationState::kTko: return num_servers_down_stat; default: CHECK(false); return num_stats; // shouldnt reach here } }; auto old_name = getStatName(old_st); auto new_name = getStatName(new_st); stat_decr(proxy->stats, old_name, 1); stat_incr(proxy->stats, new_name, 1); stats_.state = new_st; } } ProxyDestinationStats::ProxyDestinationStats(const McrouterOptions& opts) : avgLatency(1.0 / opts.latency_window_size) { } }}} // facebook::memcache::mcrouter <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/channel_proxy.h" #include <utility> #include "webrtc/api/call/audio_sink.h" #include "webrtc/base/checks.h" #include "webrtc/voice_engine/channel.h" namespace webrtc { namespace voe { ChannelProxy::ChannelProxy() : channel_owner_(nullptr) {} ChannelProxy::ChannelProxy(const ChannelOwner& channel_owner) : channel_owner_(channel_owner) { RTC_CHECK(channel_owner_.channel()); module_process_thread_checker_.DetachFromThread(); } ChannelProxy::~ChannelProxy() {} void ChannelProxy::SetRTCPStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRTCPStatus(enable); } void ChannelProxy::SetLocalSSRC(uint32_t ssrc) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetLocalSSRC(ssrc); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetRTCP_CNAME(const std::string& c_name) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Note: VoERTP_RTCP::SetRTCP_CNAME() accepts a char[256] array. std::string c_name_limited = c_name.substr(0, 255); int error = channel()->SetRTCP_CNAME(c_name_limited.c_str()); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetNACKStatus(bool enable, int max_packets) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetNACKStatus(enable, max_packets); } void ChannelProxy::SetSendAudioLevelIndicationStatus(bool enable, int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetSendAudioLevelIndicationStatus(enable, id); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetReceiveAudioLevelIndicationStatus(bool enable, int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetReceiveAudioLevelIndicationStatus(enable, id); RTC_DCHECK_EQ(0, error); } void ChannelProxy::EnableSendTransportSequenceNumber(int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->EnableSendTransportSequenceNumber(id); } void ChannelProxy::EnableReceiveTransportSequenceNumber(int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->EnableReceiveTransportSequenceNumber(id); } void ChannelProxy::RegisterSenderCongestionControlObjects( RtpPacketSender* rtp_packet_sender, TransportFeedbackObserver* transport_feedback_observer, PacketRouter* packet_router, RtcpBandwidthObserver* bandwidth_observer) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->RegisterSenderCongestionControlObjects( rtp_packet_sender, transport_feedback_observer, packet_router, bandwidth_observer); } void ChannelProxy::RegisterReceiverCongestionControlObjects( PacketRouter* packet_router) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->RegisterReceiverCongestionControlObjects(packet_router); } void ChannelProxy::ResetCongestionControlObjects() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->ResetCongestionControlObjects(); } CallStatistics ChannelProxy::GetRTCPStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); CallStatistics stats = {0}; int error = channel()->GetRTPStatistics(stats); RTC_DCHECK_EQ(0, error); return stats; } std::vector<ReportBlock> ChannelProxy::GetRemoteRTCPReportBlocks() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); std::vector<webrtc::ReportBlock> blocks; int error = channel()->GetRemoteRTCPReportBlocks(&blocks); RTC_DCHECK_EQ(0, error); return blocks; } NetworkStatistics ChannelProxy::GetNetworkStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); NetworkStatistics stats = {0}; int error = channel()->GetNetworkStatistics(stats); RTC_DCHECK_EQ(0, error); return stats; } AudioDecodingCallStats ChannelProxy::GetDecodingCallStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); AudioDecodingCallStats stats; channel()->GetDecodingCallStatistics(&stats); return stats; } int32_t ChannelProxy::GetSpeechOutputLevelFullRange() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); uint32_t level = 0; int error = channel()->GetSpeechOutputLevelFullRange(level); RTC_DCHECK_EQ(0, error); return static_cast<int32_t>(level); } uint32_t ChannelProxy::GetDelayEstimate() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() || module_process_thread_checker_.CalledOnValidThread()); return channel()->GetDelayEstimate(); } bool ChannelProxy::SetSendTelephoneEventPayloadType(int payload_type, int payload_frequency) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetSendTelephoneEventPayloadType(payload_type, payload_frequency) == 0; } bool ChannelProxy::SendTelephoneEventOutband(int event, int duration_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SendTelephoneEventOutband(event, duration_ms) == 0; } void ChannelProxy::SetBitrate(int bitrate_bps, int64_t probing_interval_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() || module_process_thread_checker_.CalledOnValidThread()); channel()->SetBitRate(bitrate_bps, probing_interval_ms); } void ChannelProxy::SetRecPayloadType(int payload_type, const SdpAudioFormat& format) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); const int result = channel()->SetRecPayloadType(payload_type, format); RTC_DCHECK_EQ(0, result); } void ChannelProxy::SetSink(std::unique_ptr<AudioSinkInterface> sink) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetSink(std::move(sink)); } void ChannelProxy::SetInputMute(bool muted) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetInputMute(muted); RTC_DCHECK_EQ(0, error); } void ChannelProxy::RegisterExternalTransport(Transport* transport) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->RegisterExternalTransport(transport); RTC_DCHECK_EQ(0, error); } void ChannelProxy::DeRegisterExternalTransport() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->DeRegisterExternalTransport(); } void ChannelProxy::OnRtpPacket(const RtpPacketReceived& packet) { // May be called on either worker thread or network thread. channel()->OnRtpPacket(packet); } bool ChannelProxy::ReceivedRTCPPacket(const uint8_t* packet, size_t length) { // May be called on either worker thread or network thread. return channel()->ReceivedRTCPPacket(packet, length) == 0; } const rtc::scoped_refptr<AudioDecoderFactory>& ChannelProxy::GetAudioDecoderFactory() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetAudioDecoderFactory(); } void ChannelProxy::SetChannelOutputVolumeScaling(float scaling) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetChannelOutputVolumeScaling(scaling); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetRtcEventLog(RtcEventLog* event_log) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRtcEventLog(event_log); } void ChannelProxy::EnableAudioNetworkAdaptor(const std::string& config_string) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); bool ret = channel()->EnableAudioNetworkAdaptor(config_string); RTC_DCHECK(ret); ;} void ChannelProxy::DisableAudioNetworkAdaptor() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->DisableAudioNetworkAdaptor(); } void ChannelProxy::SetReceiverFrameLengthRange(int min_frame_length_ms, int max_frame_length_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetReceiverFrameLengthRange(min_frame_length_ms, max_frame_length_ms); } AudioMixer::Source::AudioFrameInfo ChannelProxy::GetAudioFrameWithInfo( int sample_rate_hz, AudioFrame* audio_frame) { RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); return channel()->GetAudioFrameWithInfo(sample_rate_hz, audio_frame); } int ChannelProxy::NeededFrequency() const { RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); return static_cast<int>(channel()->NeededFrequency(-1)); } void ChannelProxy::SetTransportOverhead(int transport_overhead_per_packet) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetTransportOverhead(transport_overhead_per_packet); } void ChannelProxy::AssociateSendChannel( const ChannelProxy& send_channel_proxy) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->set_associate_send_channel(send_channel_proxy.channel_owner_); } void ChannelProxy::DisassociateSendChannel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->set_associate_send_channel(ChannelOwner(nullptr)); } void ChannelProxy::GetRtpRtcp(RtpRtcp** rtp_rtcp, RtpReceiver** rtp_receiver) const { RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread()); RTC_DCHECK(rtp_rtcp); RTC_DCHECK(rtp_receiver); int error = channel()->GetRtpRtcp(rtp_rtcp, rtp_receiver); RTC_DCHECK_EQ(0, error); } uint32_t ChannelProxy::GetPlayoutTimestamp() const { RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_); unsigned int timestamp = 0; int error = channel()->GetPlayoutTimestamp(timestamp); RTC_DCHECK(!error || timestamp == 0); return timestamp; } void ChannelProxy::SetMinimumPlayoutDelay(int delay_ms) { RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread()); // Limit to range accepted by both VoE and ACM, so we're at least getting as // close as possible, instead of failing. delay_ms = std::max(0, std::min(delay_ms, 10000)); int error = channel()->SetMinimumPlayoutDelay(delay_ms); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRtcpRttStats(rtcp_rtt_stats); } bool ChannelProxy::GetRecCodec(CodecInst* codec_inst) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetRecCodec(*codec_inst) == 0; } bool ChannelProxy::GetSendCodec(CodecInst* codec_inst) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetSendCodec(*codec_inst) == 0; } bool ChannelProxy::SetVADStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetVADStatus(enable, VADNormal, false) == 0; } bool ChannelProxy::SetCodecFECStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetCodecFECStatus(enable) == 0; } bool ChannelProxy::SetOpusDtx(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetOpusDtx(enable) == 0; } bool ChannelProxy::SetOpusMaxPlaybackRate(int frequency_hz) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetOpusMaxPlaybackRate(frequency_hz) == 0; } bool ChannelProxy::SetSendCodec(const CodecInst& codec_inst) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Validation code copied from VoECodecImpl::SetSendCodec(). if ((STR_CASE_CMP(codec_inst.plname, "L16") == 0) && (codec_inst.pacsize >= 960)) { return false; } if (!STR_CASE_CMP(codec_inst.plname, "CN") || !STR_CASE_CMP(codec_inst.plname, "TELEPHONE-EVENT") || !STR_CASE_CMP(codec_inst.plname, "RED")) { return false; } if ((codec_inst.channels != 1) && (codec_inst.channels != 2)) { return false; } if (!AudioCodingModule::IsCodecValid(codec_inst)) { return false; } return channel()->SetSendCodec(codec_inst) == 0; } bool ChannelProxy::SetSendCNPayloadType(int type, PayloadFrequencies frequency) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Validation code copied from VoECodecImpl::SetSendCNPayloadType(). if (type < 96 || type > 127) { // Only allow dynamic range: 96 to 127 return false; } if ((frequency != kFreq16000Hz) && (frequency != kFreq32000Hz)) { // It is not possible to modify the payload type for CN/8000. // We only allow modification of the CN payload type for CN/16000 // and CN/32000. return false; } return channel()->SetSendCNPayloadType(type, frequency) == 0; } Channel* ChannelProxy::channel() const { RTC_DCHECK(channel_owner_.channel()); return channel_owner_.channel(); } } // namespace voe } // namespace webrtc <commit_msg>Fix flaky test WebRtcMediaRecorderTest.PeerConnection<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/channel_proxy.h" #include <utility> #include "webrtc/api/call/audio_sink.h" #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" #include "webrtc/voice_engine/channel.h" namespace webrtc { namespace voe { ChannelProxy::ChannelProxy() : channel_owner_(nullptr) {} ChannelProxy::ChannelProxy(const ChannelOwner& channel_owner) : channel_owner_(channel_owner) { RTC_CHECK(channel_owner_.channel()); module_process_thread_checker_.DetachFromThread(); } ChannelProxy::~ChannelProxy() {} void ChannelProxy::SetRTCPStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRTCPStatus(enable); } void ChannelProxy::SetLocalSSRC(uint32_t ssrc) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetLocalSSRC(ssrc); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetRTCP_CNAME(const std::string& c_name) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Note: VoERTP_RTCP::SetRTCP_CNAME() accepts a char[256] array. std::string c_name_limited = c_name.substr(0, 255); int error = channel()->SetRTCP_CNAME(c_name_limited.c_str()); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetNACKStatus(bool enable, int max_packets) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetNACKStatus(enable, max_packets); } void ChannelProxy::SetSendAudioLevelIndicationStatus(bool enable, int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetSendAudioLevelIndicationStatus(enable, id); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetReceiveAudioLevelIndicationStatus(bool enable, int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetReceiveAudioLevelIndicationStatus(enable, id); RTC_DCHECK_EQ(0, error); } void ChannelProxy::EnableSendTransportSequenceNumber(int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->EnableSendTransportSequenceNumber(id); } void ChannelProxy::EnableReceiveTransportSequenceNumber(int id) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->EnableReceiveTransportSequenceNumber(id); } void ChannelProxy::RegisterSenderCongestionControlObjects( RtpPacketSender* rtp_packet_sender, TransportFeedbackObserver* transport_feedback_observer, PacketRouter* packet_router, RtcpBandwidthObserver* bandwidth_observer) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->RegisterSenderCongestionControlObjects( rtp_packet_sender, transport_feedback_observer, packet_router, bandwidth_observer); } void ChannelProxy::RegisterReceiverCongestionControlObjects( PacketRouter* packet_router) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->RegisterReceiverCongestionControlObjects(packet_router); } void ChannelProxy::ResetCongestionControlObjects() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->ResetCongestionControlObjects(); } CallStatistics ChannelProxy::GetRTCPStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); CallStatistics stats = {0}; int error = channel()->GetRTPStatistics(stats); RTC_DCHECK_EQ(0, error); return stats; } std::vector<ReportBlock> ChannelProxy::GetRemoteRTCPReportBlocks() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); std::vector<webrtc::ReportBlock> blocks; int error = channel()->GetRemoteRTCPReportBlocks(&blocks); RTC_DCHECK_EQ(0, error); return blocks; } NetworkStatistics ChannelProxy::GetNetworkStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); NetworkStatistics stats = {0}; int error = channel()->GetNetworkStatistics(stats); RTC_DCHECK_EQ(0, error); return stats; } AudioDecodingCallStats ChannelProxy::GetDecodingCallStatistics() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); AudioDecodingCallStats stats; channel()->GetDecodingCallStatistics(&stats); return stats; } int32_t ChannelProxy::GetSpeechOutputLevelFullRange() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); uint32_t level = 0; int error = channel()->GetSpeechOutputLevelFullRange(level); RTC_DCHECK_EQ(0, error); return static_cast<int32_t>(level); } uint32_t ChannelProxy::GetDelayEstimate() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() || module_process_thread_checker_.CalledOnValidThread()); return channel()->GetDelayEstimate(); } bool ChannelProxy::SetSendTelephoneEventPayloadType(int payload_type, int payload_frequency) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetSendTelephoneEventPayloadType(payload_type, payload_frequency) == 0; } bool ChannelProxy::SendTelephoneEventOutband(int event, int duration_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SendTelephoneEventOutband(event, duration_ms) == 0; } void ChannelProxy::SetBitrate(int bitrate_bps, int64_t probing_interval_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread() || module_process_thread_checker_.CalledOnValidThread()); channel()->SetBitRate(bitrate_bps, probing_interval_ms); } void ChannelProxy::SetRecPayloadType(int payload_type, const SdpAudioFormat& format) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); const int result = channel()->SetRecPayloadType(payload_type, format); RTC_DCHECK_EQ(0, result); } void ChannelProxy::SetSink(std::unique_ptr<AudioSinkInterface> sink) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetSink(std::move(sink)); } void ChannelProxy::SetInputMute(bool muted) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetInputMute(muted); RTC_DCHECK_EQ(0, error); } void ChannelProxy::RegisterExternalTransport(Transport* transport) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->RegisterExternalTransport(transport); RTC_DCHECK_EQ(0, error); } void ChannelProxy::DeRegisterExternalTransport() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->DeRegisterExternalTransport(); } void ChannelProxy::OnRtpPacket(const RtpPacketReceived& packet) { // May be called on either worker thread or network thread. channel()->OnRtpPacket(packet); } bool ChannelProxy::ReceivedRTCPPacket(const uint8_t* packet, size_t length) { // May be called on either worker thread or network thread. return channel()->ReceivedRTCPPacket(packet, length) == 0; } const rtc::scoped_refptr<AudioDecoderFactory>& ChannelProxy::GetAudioDecoderFactory() const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetAudioDecoderFactory(); } void ChannelProxy::SetChannelOutputVolumeScaling(float scaling) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); int error = channel()->SetChannelOutputVolumeScaling(scaling); RTC_DCHECK_EQ(0, error); } void ChannelProxy::SetRtcEventLog(RtcEventLog* event_log) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRtcEventLog(event_log); } void ChannelProxy::EnableAudioNetworkAdaptor(const std::string& config_string) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); bool ret = channel()->EnableAudioNetworkAdaptor(config_string); RTC_DCHECK(ret); ;} void ChannelProxy::DisableAudioNetworkAdaptor() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->DisableAudioNetworkAdaptor(); } void ChannelProxy::SetReceiverFrameLengthRange(int min_frame_length_ms, int max_frame_length_ms) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetReceiverFrameLengthRange(min_frame_length_ms, max_frame_length_ms); } AudioMixer::Source::AudioFrameInfo ChannelProxy::GetAudioFrameWithInfo( int sample_rate_hz, AudioFrame* audio_frame) { RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); return channel()->GetAudioFrameWithInfo(sample_rate_hz, audio_frame); } int ChannelProxy::NeededFrequency() const { RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); return static_cast<int>(channel()->NeededFrequency(-1)); } void ChannelProxy::SetTransportOverhead(int transport_overhead_per_packet) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetTransportOverhead(transport_overhead_per_packet); } void ChannelProxy::AssociateSendChannel( const ChannelProxy& send_channel_proxy) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->set_associate_send_channel(send_channel_proxy.channel_owner_); } void ChannelProxy::DisassociateSendChannel() { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->set_associate_send_channel(ChannelOwner(nullptr)); } void ChannelProxy::GetRtpRtcp(RtpRtcp** rtp_rtcp, RtpReceiver** rtp_receiver) const { RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread()); RTC_DCHECK(rtp_rtcp); RTC_DCHECK(rtp_receiver); int error = channel()->GetRtpRtcp(rtp_rtcp, rtp_receiver); RTC_DCHECK_EQ(0, error); } uint32_t ChannelProxy::GetPlayoutTimestamp() const { RTC_DCHECK_RUNS_SERIALIZED(&video_capture_thread_race_checker_); unsigned int timestamp = 0; int error = channel()->GetPlayoutTimestamp(timestamp); RTC_DCHECK(!error || timestamp == 0); return timestamp; } void ChannelProxy::SetMinimumPlayoutDelay(int delay_ms) { RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread()); // Limit to range accepted by both VoE and ACM, so we're at least getting as // close as possible, instead of failing. delay_ms = std::max(0, std::min(delay_ms, 10000)); int error = channel()->SetMinimumPlayoutDelay(delay_ms); if (0 != error) { LOG(LS_WARNING) << "Error setting minimum playout delay."; } } void ChannelProxy::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); channel()->SetRtcpRttStats(rtcp_rtt_stats); } bool ChannelProxy::GetRecCodec(CodecInst* codec_inst) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetRecCodec(*codec_inst) == 0; } bool ChannelProxy::GetSendCodec(CodecInst* codec_inst) const { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->GetSendCodec(*codec_inst) == 0; } bool ChannelProxy::SetVADStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetVADStatus(enable, VADNormal, false) == 0; } bool ChannelProxy::SetCodecFECStatus(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetCodecFECStatus(enable) == 0; } bool ChannelProxy::SetOpusDtx(bool enable) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetOpusDtx(enable) == 0; } bool ChannelProxy::SetOpusMaxPlaybackRate(int frequency_hz) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); return channel()->SetOpusMaxPlaybackRate(frequency_hz) == 0; } bool ChannelProxy::SetSendCodec(const CodecInst& codec_inst) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Validation code copied from VoECodecImpl::SetSendCodec(). if ((STR_CASE_CMP(codec_inst.plname, "L16") == 0) && (codec_inst.pacsize >= 960)) { return false; } if (!STR_CASE_CMP(codec_inst.plname, "CN") || !STR_CASE_CMP(codec_inst.plname, "TELEPHONE-EVENT") || !STR_CASE_CMP(codec_inst.plname, "RED")) { return false; } if ((codec_inst.channels != 1) && (codec_inst.channels != 2)) { return false; } if (!AudioCodingModule::IsCodecValid(codec_inst)) { return false; } return channel()->SetSendCodec(codec_inst) == 0; } bool ChannelProxy::SetSendCNPayloadType(int type, PayloadFrequencies frequency) { RTC_DCHECK(worker_thread_checker_.CalledOnValidThread()); // Validation code copied from VoECodecImpl::SetSendCNPayloadType(). if (type < 96 || type > 127) { // Only allow dynamic range: 96 to 127 return false; } if ((frequency != kFreq16000Hz) && (frequency != kFreq32000Hz)) { // It is not possible to modify the payload type for CN/8000. // We only allow modification of the CN payload type for CN/16000 // and CN/32000. return false; } return channel()->SetSendCNPayloadType(type, frequency) == 0; } Channel* ChannelProxy::channel() const { RTC_DCHECK(channel_owner_.channel()); return channel_owner_.channel(); } } // namespace voe } // namespace webrtc <|endoftext|>
<commit_before>#include <Empathy/Empathy/Empathy.h> #include <Empathy/empathy-linear/linear_empathy.h> #include <irrKlang.h> #include <GLFW/glfw3.h> #include <muParser.h> #include <Empathy/Brain/CustomLogic/Calming_1.h> #define FULL_SCREEN false #if FULL_SCREEN #define RENDER_SIZE 768 #define SC_SIZE_X 1366 #define SC_SIZE_Y 768 #else #define RENDER_SIZE 690 #define SC_SIZE_X 700 #define SC_SIZE_Y 700 #endif using namespace std; static GLFWwindow * window; static GLfloat mouseX,mouseY; irrklang::ISoundEngine* engine; static GLdouble lastPressTime; static GLdouble thresholdTime=0.2; static GLboolean mousePressed=GL_FALSE; void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){ empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE); if(button==GLFW_MOUSE_BUTTON_LEFT ){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS); }else if(button==GLFW_MOUSE_BUTTON_RIGHT){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS); } event.putDouble(EMPATHY_MOUSE_XPOS,mouseX); event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY); empathy::radio::BroadcastStation::emit(event); } void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) { if(action==GLFW_PRESS){ createClickEvent(button); lastPressTime=glfwGetTime(); mousePressed=GL_TRUE; }else if(action==GLFW_RELEASE){ lastPressTime=0; mousePressed=GL_FALSE; } } void character_callback(GLFWwindow* window, unsigned int codepoint){ std::string myAction=EMPATHY_EVENT_INPUT_KEY_PRESS; empathy::radio::Event event(myAction); event.putInt(EMPATHY_EVENT_INPUT_KEY, codepoint); empathy::radio::BroadcastStation::emit(event); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // When a user presses the escape key, we set the WindowShouldClose property to true, // closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ // glfwSetWindowShouldClose(instance->window, GL_TRUE); empathy_linear::makeReadyToClose(); return; } else if(action == GLFW_PRESS || action == GLFW_REPEAT ) { if (key == GLFW_KEY_ENTER) { empathy::radio::Event event(EMPATHY_EVENT_INPUT_KEY_PRESS); event.putInt(EMPATHY_EVENT_INPUT_KEY, key); empathy::radio::BroadcastStation::emit(event); } else if (key == GLFW_KEY_BACKSPACE) { empathy::radio::Event event(EMPATHY_EVENT_INPUT_KEY_PRESS); event.putInt(EMPATHY_EVENT_INPUT_KEY, key); empathy::radio::BroadcastStation::emit(event); } } } void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) { mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;; mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2; } void initGlfw() { // cout<<"glfwInit"<<endl; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Create a GLFW window window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3", FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetCharCallback(window, character_callback); //set event receiver call backs. glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window,mouse_input_callback); glfwSetCursorPosCallback(window,mouse_position_callback); } void init(){ initGlfw(); empathy_linear::init(); empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2); empathy_linear::setScreenSize(RENDER_SIZE); // empathy_linear::addJsonBrain("brains/Calming_1.json"); empathy_linear::addBrain(new empathy::brain::Calming_1()); // empathy_linear::addJsonBrain("brains/CanonInD.json"); // empathy_linear::addEmotionBrain(); empathy_linear::addDummyTouchBrain(); engine = irrklang::createIrrKlangDevice(); if (!engine) { printf("Could not startup engine\n"); exit(EXIT_FAILURE); } engine->setSoundVolume(0.4f); } void loop(){ while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){ std::stack<empathy::moonlight::BasicNote> audioEvents= empathy_linear::getMusicalKeyboardEvents(); while(! audioEvents.empty()){ empathy::moonlight::BasicNote playableItem=audioEvents.top(); std::string fileName=playableItem.getNote(); fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1); if(playableItem.isSharp()){ fileName="#"+fileName; } std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3"); try{ // cout<<"Playing audio "<<fileName<<endl; engine->play2D(path.c_str()); }catch (int i){ cout<<"Could not play "<<path<<endl; continue; } audioEvents.pop(); } if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){ createClickEvent(); } glfwPollEvents(); empathy_linear::loop(); empathy_linear::setTime((GLfloat ) glfwGetTime()); glfwSwapBuffers(window); } } void flush(){ engine->drop(); empathy_linear::flush(); if(window!= nullptr) glfwSetWindowShouldClose(window,true); glfwTerminate(); } int main() { init(); loop(); flush(); } <commit_msg>Can play audio files directly<commit_after>#include <Empathy/Empathy/Empathy.h> #include <Empathy/empathy-linear/linear_empathy.h> #include <irrKlang.h> #include <GLFW/glfw3.h> #include <muParser.h> #include <Empathy/Brain/CustomLogic/Calming_1.h> #define FULL_SCREEN false #if FULL_SCREEN #define RENDER_SIZE 768 #define SC_SIZE_X 1366 #define SC_SIZE_Y 768 #else #define RENDER_SIZE 690 #define SC_SIZE_X 700 #define SC_SIZE_Y 700 #endif using namespace std; static GLFWwindow * window; static GLfloat mouseX,mouseY; irrklang::ISoundEngine* engine; static GLdouble lastPressTime; static GLdouble thresholdTime=0.2; static GLboolean mousePressed=GL_FALSE; void createClickEvent(int button=GLFW_MOUSE_BUTTON_LEFT){ empathy::radio::Event event(EMPATHY_EVENT_ACTION_NONE); if(button==GLFW_MOUSE_BUTTON_LEFT ){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_LEFT_KEY_PRESS); }else if(button==GLFW_MOUSE_BUTTON_RIGHT){ event=empathy::radio::Event(EMPATHY_EVENT_INPUT_MOUSE_RIGHT_KEY_PRESS); } event.putDouble(EMPATHY_MOUSE_XPOS,mouseX); event.putDouble(EMPATHY_MOUSE_YPOS,RENDER_SIZE-mouseY); empathy::radio::BroadcastStation::emit(event); } void mouse_input_callback(GLFWwindow *window, int button, int action, int mods) { if(action==GLFW_PRESS){ createClickEvent(button); lastPressTime=glfwGetTime(); mousePressed=GL_TRUE; }else if(action==GLFW_RELEASE){ lastPressTime=0; mousePressed=GL_FALSE; } } void character_callback(GLFWwindow* window, unsigned int codepoint){ std::string myAction=EMPATHY_EVENT_INPUT_KEY_PRESS; empathy::radio::Event event(myAction); event.putInt(EMPATHY_EVENT_INPUT_KEY, codepoint); empathy::radio::BroadcastStation::emit(event); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // When a user presses the escape key, we set the WindowShouldClose property to true, // closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ // glfwSetWindowShouldClose(instance->window, GL_TRUE); empathy_linear::makeReadyToClose(); return; } else if(action == GLFW_PRESS || action == GLFW_REPEAT ) { if (key == GLFW_KEY_ENTER) { empathy::radio::Event event(EMPATHY_EVENT_INPUT_KEY_PRESS); event.putInt(EMPATHY_EVENT_INPUT_KEY, key); empathy::radio::BroadcastStation::emit(event); } else if (key == GLFW_KEY_BACKSPACE) { empathy::radio::Event event(EMPATHY_EVENT_INPUT_KEY_PRESS); event.putInt(EMPATHY_EVENT_INPUT_KEY, key); empathy::radio::BroadcastStation::emit(event); } } } void mouse_position_callback(GLFWwindow *window, double xpos, double ypos) { mouseX= xpos -(SC_SIZE_X-RENDER_SIZE)/2;; mouseY = ypos - (SC_SIZE_Y-RENDER_SIZE)/2; } void initGlfw() { // cout<<"glfwInit"<<endl; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Create a GLFW window window = glfwCreateWindow((GLuint)SC_SIZE_X, (GLuint)SC_SIZE_Y, "Empathy | <3", FULL_SCREEN ? glfwGetPrimaryMonitor(): nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetCharCallback(window, character_callback); //set event receiver call backs. glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window,mouse_input_callback); glfwSetCursorPosCallback(window,mouse_position_callback); } void init(){ initGlfw(); empathy_linear::init(); empathy_linear::setScreenMargins( (SC_SIZE_X-RENDER_SIZE)/2 , (SC_SIZE_Y-RENDER_SIZE)/2); empathy_linear::setScreenSize(RENDER_SIZE); // empathy_linear::addJsonBrain("brains/Calming_1.json"); empathy_linear::addBrain(new empathy::brain::Calming_1()); // empathy_linear::addJsonBrain("brains/CanonInD.json"); // empathy_linear::addEmotionBrain(); empathy_linear::addDummyTouchBrain(); engine = irrklang::createIrrKlangDevice(); if (!engine) { printf("Could not startup engine\n"); exit(EXIT_FAILURE); } engine->setSoundVolume(0.4f); } void checkAudioEvents(){ std::stack<empathy::moonlight::BasicNote> keyboardAudioEvents= empathy_linear::getMusicalKeyboardEvents(); while(! keyboardAudioEvents.empty()){ empathy::moonlight::BasicNote playableItem=keyboardAudioEvents.top(); std::string fileName=playableItem.getNote(); fileName += playableItem.getOctave()<=1?"":std::to_string(playableItem.getOctave()-1); if(playableItem.isSharp()){ fileName="#"+fileName; } std::string path=empathy::getAssetPath("audio/keyboard/music/"+fileName+".mp3"); try{ // cout<<"Playing audio "<<fileName<<endl; engine->play2D(path.c_str()); }catch (int i){ cout<<"Could not play "<<path<<endl; continue; } keyboardAudioEvents.pop(); } std::stack<std::string> audioEvents = empathy_linear::getMusicalEvents(); while(! audioEvents.empty()){ std::string fileName=audioEvents.top(); std::string path=empathy::getAssetPath("audio/"+fileName); try{ engine->play2D(path.c_str()); }catch (int i){ cout<<"Could not play "<<path<<endl; } audioEvents.pop(); } } void loop(){ while(! empathy_linear::shouldClose() && !glfwWindowShouldClose(window)){ checkAudioEvents(); if(mousePressed && glfwGetTime()-lastPressTime>thresholdTime){ createClickEvent(); } glfwPollEvents(); empathy_linear::loop(); empathy_linear::setTime((GLfloat ) glfwGetTime()); glfwSwapBuffers(window); } } void flush(){ engine->drop(); empathy_linear::flush(); if(window!= nullptr) glfwSetWindowShouldClose(window,true); glfwTerminate(); } int main() { init(); loop(); flush(); } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2021 gary@drinkingtea.net * * 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/. */ #pragma once #ifdef OX_USE_STDLIB #include <array> #endif #include "bstring.hpp" #include "fmt.hpp" #include "hashmap.hpp" extern "C" { void oxTraceInitHook(); void oxTraceHook(const char *file, int line, const char *ch, const char *msg); } namespace ox::trace { struct TraceMsg { const char *file = ""; int line = 0; uint64_t time = 0; const char *ch = ""; ox::BString<100> msg; }; template<typename T> Error model(T *io, ox::trace::TraceMsg *obj) { auto err = OxError(0); io->setTypeInfo("ox::trace::TraceMsg", 5); oxReturnError(io->field("file", &obj->file)); oxReturnError(io->field("line", &obj->line)); oxReturnError(io->field("time", &obj->time)); oxReturnError(io->field("msg", &obj->msg)); return err; } class OutStream { protected: const char *m_delimiter = " "; TraceMsg m_msg; public: constexpr OutStream(const char *file, int line, const char *ch, const char *msg = "") { m_msg.file = file; m_msg.line = line; m_msg.ch = ch; m_msg.msg = msg; } #ifdef OX_USE_STDLIB template<std::size_t fmtSegmentCnt, typename ...Args> constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, std::array<detail::FmtArg, fmtSegmentCnt - 1> elements) { //static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format."); m_msg.file = file; m_msg.line = line; m_msg.ch = ch; const auto &firstSegment = fmtSegments.segments[0]; m_msg.msg.append(firstSegment.str, firstSegment.length); //const detail::FmtArg elements[sizeof...(args)] = {args...}; for (auto i = 0u; i < fmtSegments.size - 1; ++i) { m_msg.msg += elements[i].out; const auto &s = fmtSegments.segments[i + 1]; m_msg.msg.append(s.str, s.length); } } #else template<std::size_t fmtSegmentCnt, typename ...Args> constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, Args... args) { //static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format."); m_msg.file = file; m_msg.line = line; m_msg.ch = ch; const auto &firstSegment = fmtSegments.segments[0]; m_msg.msg.append(firstSegment.str, firstSegment.length); const detail::FmtArg elements[sizeof...(args)] = {args...}; for (auto i = 0u; i < fmtSegments.size - 1; ++i) { m_msg.msg += elements[i].out; const auto &s = fmtSegments.segments[i + 1]; m_msg.msg.append(s.str, s.length); } } #endif inline ~OutStream() { oxTraceHook(m_msg.file, m_msg.line, m_msg.ch, m_msg.msg.c_str()); } template<typename T> constexpr OutStream &operator<<(const T &v) { if (m_msg.msg.len()) { m_msg.msg += m_delimiter; } m_msg.msg += v; return *this; } constexpr OutStream &operator<<(Error err) { if (m_msg.msg.len()) { m_msg.msg += m_delimiter; } m_msg.msg += static_cast<int64_t>(err); return *this; } /** * del sets the delimiter between log segments. */ constexpr OutStream &del(const char *delimiter) { m_delimiter = delimiter; return *this; } }; class NullStream { public: constexpr NullStream(const char*, int, const char*, const char* = "") { } #ifdef OX_USE_STDLIB template<std::size_t fmtSegmentCnt, typename ...Args> constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, std::array<detail::FmtArg, fmtSegmentCnt - 1>) { } #else template<std::size_t fmtSegmentCnt, typename ...Args> constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, Args...) { } #endif template<typename T> constexpr NullStream &operator<<(const T&) { return *this; } constexpr NullStream &del(const char*) { return *this; } }; #ifdef DEBUG using TraceStream = OutStream; #else using TraceStream = NullStream; #endif void logError(const char *file, int line, const Error &err); void init(); } #define oxLogError(err) ox::trace::logError(__FILE__, __LINE__, err) #define oxTrace(...) ox::trace::TraceStream(__FILE__, __LINE__, __VA_ARGS__) #define oxOut(...) ox::trace::TraceStream(__FILE__, __LINE__, "stdout", __VA_ARGS__) #define oxErr(...) ox::trace::TraceStream(__FILE__, __LINE__, "stderr", __VA_ARGS__) #ifdef OX_USE_STDLIB // Non-GCC compilers don't like ##__VA_ARGS__, so use initializer list, which relies on std lib #define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #else #define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #endif #define oxInfo(...) oxTrace("info", __VA_ARGS__) #define oxInfof(...) oxTracef("info", __VA_ARGS__) #define oxError(...) oxTrace("error", __VA_ARGS__) #define oxErrorf(...) oxTracef("error", __VA_ARGS__) #ifndef OX_NODEBUG #define oxDebug(...) oxTrace("debug", __VA_ARGS__) #define oxDebugf(...) oxTracef("debug", __VA_ARGS__) #else #define oxDebug(...) static_assert(false, "Debug prints were checked in."); oxTrace("debug", __VA_ARGS__) #define oxDebugf(...) static_assert(false, "Debug prints were checked in."); oxTracef("debug", __VA_ARGS__) #endif <commit_msg>[ox/std] Fix oxOut and oxErr to explicitly use OutStream over TraceStream<commit_after>/* * Copyright 2015 - 2021 gary@drinkingtea.net * * 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/. */ #pragma once #ifdef OX_USE_STDLIB #include <array> #endif #include "bstring.hpp" #include "fmt.hpp" #include "hashmap.hpp" extern "C" { void oxTraceInitHook(); void oxTraceHook(const char *file, int line, const char *ch, const char *msg); } namespace ox::trace { struct TraceMsg { const char *file = ""; int line = 0; uint64_t time = 0; const char *ch = ""; ox::BString<100> msg; }; template<typename T> Error model(T *io, ox::trace::TraceMsg *obj) { auto err = OxError(0); io->setTypeInfo("ox::trace::TraceMsg", 5); oxReturnError(io->field("file", &obj->file)); oxReturnError(io->field("line", &obj->line)); oxReturnError(io->field("time", &obj->time)); oxReturnError(io->field("msg", &obj->msg)); return err; } class OutStream { protected: const char *m_delimiter = " "; TraceMsg m_msg; public: constexpr OutStream(const char *file, int line, const char *ch, const char *msg = "") { m_msg.file = file; m_msg.line = line; m_msg.ch = ch; m_msg.msg = msg; } #ifdef OX_USE_STDLIB template<std::size_t fmtSegmentCnt, typename ...Args> constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, std::array<detail::FmtArg, fmtSegmentCnt - 1> elements) { //static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format."); m_msg.file = file; m_msg.line = line; m_msg.ch = ch; const auto &firstSegment = fmtSegments.segments[0]; m_msg.msg.append(firstSegment.str, firstSegment.length); //const detail::FmtArg elements[sizeof...(args)] = {args...}; for (auto i = 0u; i < fmtSegments.size - 1; ++i) { m_msg.msg += elements[i].out; const auto &s = fmtSegments.segments[i + 1]; m_msg.msg.append(s.str, s.length); } } #else template<std::size_t fmtSegmentCnt, typename ...Args> constexpr OutStream(const char *file, int line, const char *ch, detail::Fmt<fmtSegmentCnt> fmtSegments, Args... args) { //static_assert(sizeof...(args) == fmtSegmentCnt - 1, "Wrong number of trace arguments for format."); m_msg.file = file; m_msg.line = line; m_msg.ch = ch; const auto &firstSegment = fmtSegments.segments[0]; m_msg.msg.append(firstSegment.str, firstSegment.length); const detail::FmtArg elements[sizeof...(args)] = {args...}; for (auto i = 0u; i < fmtSegments.size - 1; ++i) { m_msg.msg += elements[i].out; const auto &s = fmtSegments.segments[i + 1]; m_msg.msg.append(s.str, s.length); } } #endif inline ~OutStream() { oxTraceHook(m_msg.file, m_msg.line, m_msg.ch, m_msg.msg.c_str()); } template<typename T> constexpr OutStream &operator<<(const T &v) { if (m_msg.msg.len()) { m_msg.msg += m_delimiter; } m_msg.msg += v; return *this; } constexpr OutStream &operator<<(Error err) { if (m_msg.msg.len()) { m_msg.msg += m_delimiter; } m_msg.msg += static_cast<int64_t>(err); return *this; } /** * del sets the delimiter between log segments. */ constexpr OutStream &del(const char *delimiter) { m_delimiter = delimiter; return *this; } }; class NullStream { public: constexpr NullStream(const char*, int, const char*, const char* = "") { } #ifdef OX_USE_STDLIB template<std::size_t fmtSegmentCnt, typename ...Args> constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, std::array<detail::FmtArg, fmtSegmentCnt - 1>) { } #else template<std::size_t fmtSegmentCnt, typename ...Args> constexpr NullStream(const char*, int, const char*, detail::Fmt<fmtSegmentCnt>, Args...) { } #endif template<typename T> constexpr NullStream &operator<<(const T&) { return *this; } constexpr NullStream &del(const char*) { return *this; } }; #ifdef DEBUG using TraceStream = OutStream; #else using TraceStream = NullStream; #endif void logError(const char *file, int line, const Error &err); void init(); } #define oxLogError(err) ox::trace::logError(__FILE__, __LINE__, err) #define oxTrace(...) ox::trace::TraceStream(__FILE__, __LINE__, __VA_ARGS__) #define oxOut(...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", __VA_ARGS__) #define oxErr(...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", __VA_ARGS__) #ifdef OX_USE_STDLIB // Non-GCC compilers don't like ##__VA_ARGS__, so use initializer list, which relies on std lib #define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), {__VA_ARGS__}) #else #define oxTracef(ch, fmt, ...) ox::trace::TraceStream(__FILE__, __LINE__, ch, ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #define oxOutf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stdout", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #define oxErrf(fmt, ...) ox::trace::OutStream(__FILE__, __LINE__, "stderr", ox::detail::fmtSegments<ox::detail::argCount(fmt)+1>(fmt), ##__VA_ARGS__) #endif #define oxInfo(...) oxTrace("info", __VA_ARGS__) #define oxInfof(...) oxTracef("info", __VA_ARGS__) #define oxError(...) oxTrace("error", __VA_ARGS__) #define oxErrorf(...) oxTracef("error", __VA_ARGS__) #ifndef OX_NODEBUG #define oxDebug(...) oxTrace("debug", __VA_ARGS__) #define oxDebugf(...) oxTracef("debug", __VA_ARGS__) #else #define oxDebug(...) static_assert(false, "Debug prints were checked in."); oxTrace("debug", __VA_ARGS__) #define oxDebugf(...) static_assert(false, "Debug prints were checked in."); oxTracef("debug", __VA_ARGS__) #endif <|endoftext|>
<commit_before>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include <string> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include "math.h" #include <algorithm> /** Declare PrintHelp. */ void PrintHelp(void); //------------------------------------------------------------------------------------- int main( int argc, char *argv[] ) { /** Check arguments for help. */ if ( argc < 3 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::string inputTextFile = ""; bool retin = parser->GetCommandLineArgument( "-in", inputTextFile ); std::string whichMean = "arithmetic"; bool retm = parser->GetCommandLineArgument( "-m", whichMean ); unsigned int skiprow = 0; bool retsr = parser->GetCommandLineArgument( "-sr", skiprow ); unsigned int skipcolumn = 0; bool retsc = parser->GetCommandLineArgument( "-sc", skipcolumn ); unsigned int column = 0; bool retc = parser->GetCommandLineArgument( "-c", column ); unsigned int precision = 6; bool retp = parser->GetCommandLineArgument( "-p", precision ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } if ( whichMean != "arithmetic" && whichMean != "geometric" && whichMean != "median" ) { std::cerr << "ERROR: \"-m\" should be one of { arithmetic, geometric }." << std::endl; return 1; } /** Create file stream. */ std::ifstream fileIn( inputTextFile.c_str() ); /** tmp variables. */ std::vector<double> values; std::string tmpString, line; /** Read the values. */ if ( fileIn.is_open() ) { unsigned int l = 0; /** Skip some lines. */ for ( unsigned int i = 0; i < skiprow; i++ ) { std::getline( fileIn, line ); } /** Read the file line by line. */ while ( !fileIn.eof() ) { std::vector<double> tmp; std::getline( fileIn, line ); std::istringstream lineSS( line.c_str() ); for ( unsigned int i = 0; i < skipcolumn; i++ ) { lineSS >> tmpString; } bool endOfLine = false; while ( !endOfLine ) { double tmpd = -1.0; lineSS >> tmpd; if ( tmpd == -1.0 ) endOfLine = true; else tmp.push_back( tmpd ); } /** Fill values. */ if ( column < tmp.size() && tmp.size() != 0 ) { values.push_back( tmp[ column ] ); } else if ( column >= tmp.size() && tmp.size() != 0 ) { std::cerr << "ERROR: There is no column nr. " << column << "." << std::endl; return 1; } } // end while over file } // end if else { std::cerr << "ERROR: The file \"" << inputTextFile << "\" could not be opened." << std::endl; return 1; } /** Close the file stream. */ fileIn.close(); /** Calculate mean and standard deviation. */ double mean = 0.0, std = 0.0, median = 0.0, firstquartile = 0.0, thirdquartile = 0.0, minimum = 0.0, maximum = 0.0; std::string meanString = "", stdString = ""; if ( whichMean == "arithmetic" ) { /** The arithmetic version. */ meanString = "Arithmetic mean: "; stdString = "Arithmetic std : "; for ( unsigned int i = 0; i < values.size(); i++ ) { mean += values[ i ]; } mean /= values.size(); for ( unsigned int i = 0; i < values.size(); i++ ) { std += ( values[ i ] - mean ) * ( values[ i ] - mean ); } std = sqrt( std / ( values.size() - 1.0 ) ); } // end if arithmetic else if ( whichMean == "geometric" ) { /** The geometic version. */ meanString = "Geometric mean: "; stdString = "Geometric std : "; for ( unsigned int i = 0; i < values.size(); i++ ) { mean += log( values[ i ] ); } mean /= values.size(); for ( unsigned int i = 0; i < values.size(); i++ ) { std += ( log( values[ i ] ) - mean ) * ( log( values[ i ] ) - mean ); } mean = exp( mean ); std = exp( sqrt( std / values.size() ) ); } // end if geometric else if ( whichMean == "median" ) { sort( values.begin(), values.end() ); if ( values.size() % 2 ) { /** size() is odd. */ median = values[ ( values.size() + 1 ) / 2 - 1 ]; } else { /** size() is even. */ median = ( values[ values.size() / 2 - 1 ] + values[ values.size() / 2 ] ) / 2.0; } /** Determine first (Q1) and third quartile (Q3), and minimum and maximum. * Use the value at position: round( ( n + 1 ) / 4 ) for Q1 * Use the value at position: round( ( 3n + 3 ) / 4 ) for Q3 * Subtract 1 for the index, since this is c++. */ unsigned int ind1 = ( values.size() + 1.0 ) / 4.0 + 0.5; unsigned int ind3 = ( 3.0 * values.size() + 3.0 ) / 4.0 + 0.5; minimum = values[ 0 ]; maximum = values[ values.size() - 1 ]; firstquartile = values[ ind1 - 1 ]; thirdquartile = values[ ind3 - 1 ]; } // end if median /** Setup the output format. */ std::cout << std::fixed; std::cout << std::showpoint; std::cout << std::setprecision( precision ); /** Print output to screen. */ if ( whichMean == "arithmetic" || whichMean == "geometric" ) { std::cout << meanString << mean << std::endl; std::cout << stdString << std << std::endl; } else if ( whichMean == "median" ) { std::cout << minimum << " " << firstquartile << " " << median << " " << thirdquartile << " " << maximum << std::endl; } /** Return a value. */ return 0; } // end main /** * ******************* PrintHelp ******************* */ void PrintHelp() { std::cout << "Usage:" << std::endl << "pxcomputemean" << std::endl; std::cout << "\t-in\tinput text file" << std::endl; std::cout << "\t[-m]\twhat kind of mean" << std::endl; std::cout << "\t[-c]\tcolumn of which the mean is taken" << std::endl; std::cout << "\t[-s]\tskip: how many rows are skipped" << std::endl; std::cout << "\t[-p]\toutput precision" << std::endl; std::cout << "-m should be \"arithmetic\", \"geometric\" or \"median\", the default is \"arithmetic\"." << std::endl; std::cout << "The default output precision is 6." << std::endl; std::cout << "The output for median is: minimum, first quartile, median, third quartile, maximum." << std::endl; } // end PrintHelp <commit_msg>MS:<commit_after>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include <string> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include "math.h" #include <algorithm> /** Declare PrintHelp. */ void PrintHelp(void); //------------------------------------------------------------------------------------- int main( int argc, char *argv[] ) { /** Check arguments for help. */ if ( argc < 3 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::string inputTextFile = ""; bool retin = parser->GetCommandLineArgument( "-in", inputTextFile ); std::string whichMean = "arithmetic"; bool retm = parser->GetCommandLineArgument( "-m", whichMean ); unsigned int skiprow = 0; bool retsr = parser->GetCommandLineArgument( "-sr", skiprow ); unsigned int skipcolumn = 0; bool retsc = parser->GetCommandLineArgument( "-sc", skipcolumn ); unsigned int column = 0; bool retc = parser->GetCommandLineArgument( "-c", column ); unsigned int precision = 6; bool retp = parser->GetCommandLineArgument( "-p", precision ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } if ( whichMean != "arithmetic" && whichMean != "geometric" && whichMean != "median" ) { std::cerr << "ERROR: \"-m\" should be one of { arithmetic, geometric }." << std::endl; return 1; } /** Create file stream. */ std::ifstream fileIn( inputTextFile.c_str() ); /** tmp variables. */ std::vector<double> values; std::string tmpString, line; /** Read the values. */ if ( fileIn.is_open() ) { unsigned int l = 0; /** Skip some lines. */ for ( unsigned int i = 0; i < skiprow; i++ ) { std::getline( fileIn, line ); } /** Read the file line by line. */ while ( !fileIn.eof() ) { std::vector<double> tmp; std::getline( fileIn, line ); std::istringstream lineSS( line.c_str() ); for ( unsigned int i = 0; i < skipcolumn; i++ ) { lineSS >> tmpString; } bool endOfLine = false; while ( !endOfLine ) { double tmpd = -1.0; lineSS >> tmpd; if ( tmpd == -1.0 ) endOfLine = true; else tmp.push_back( tmpd ); } /** Fill values. */ if ( column < tmp.size() && tmp.size() != 0 ) { values.push_back( tmp[ column ] ); } else if ( column >= tmp.size() && tmp.size() != 0 ) { std::cerr << "ERROR: There is no column nr. " << column << "." << std::endl; return 1; } } // end while over file } // end if else { std::cerr << "ERROR: The file \"" << inputTextFile << "\" could not be opened." << std::endl; return 1; } /** Close the file stream. */ fileIn.close(); /** Calculate mean and standard deviation. */ double mean = 0.0, std = 0.0, median = 0.0, firstquartile = 0.0, thirdquartile = 0.0, minimum = 0.0, maximum = 0.0; std::string meanString = "", stdString = ""; if ( whichMean == "arithmetic" ) { /** The arithmetic version. */ meanString = "Arithmetic mean: "; stdString = "Arithmetic std : "; for ( unsigned int i = 0; i < values.size(); i++ ) { mean += values[ i ]; } mean /= values.size(); for ( unsigned int i = 0; i < values.size(); i++ ) { std += ( values[ i ] - mean ) * ( values[ i ] - mean ); } std = sqrt( std / ( values.size() - 1.0 ) ); } // end if arithmetic else if ( whichMean == "geometric" ) { /** The geometic version. */ meanString = "Geometric mean: "; stdString = "Geometric std : "; for ( unsigned int i = 0; i < values.size(); i++ ) { mean += log( values[ i ] ); } mean /= values.size(); for ( unsigned int i = 0; i < values.size(); i++ ) { std += ( log( values[ i ] ) - mean ) * ( log( values[ i ] ) - mean ); } mean = exp( mean ); std = exp( sqrt( std / values.size() ) ); } // end if geometric else if ( whichMean == "median" ) { sort( values.begin(), values.end() ); if ( values.size() % 2 ) { /** size() is odd. */ median = values[ ( values.size() + 1 ) / 2 - 1 ]; } else { /** size() is even. */ median = ( values[ values.size() / 2 - 1 ] + values[ values.size() / 2 ] ) / 2.0; } /** Determine first (Q1) and third quartile (Q3), and minimum and maximum. * Use the value at position: round( ( n + 1 ) / 4 ) for Q1 * Use the value at position: round( ( 3n + 3 ) / 4 ) for Q3 * Subtract 1 for the index, since this is c++. */ unsigned int ind1 = static_cast<unsigned int>( ( values.size() + 1.0 ) / 4.0 + 0.5 ); unsigned int ind3 = static_cast<unsigned int>( ( 3.0 * values.size() + 3.0 ) / 4.0 + 0.5 ); minimum = values[ 0 ]; maximum = values[ values.size() - 1 ]; firstquartile = values[ ind1 - 1 ]; thirdquartile = values[ ind3 - 1 ]; } // end if median /** Setup the output format. */ std::cout << std::fixed; std::cout << std::showpoint; std::cout << std::setprecision( precision ); /** Print output to screen. */ if ( whichMean == "arithmetic" || whichMean == "geometric" ) { std::cout << meanString << mean << std::endl; std::cout << stdString << std << std::endl; } else if ( whichMean == "median" ) { std::cout << minimum << " " << firstquartile << " " << median << " " << thirdquartile << " " << maximum << std::endl; } /** Return a value. */ return 0; } // end main /** * ******************* PrintHelp ******************* */ void PrintHelp() { std::cout << "Usage:" << std::endl << "pxcomputemean" << std::endl; std::cout << "\t-in\tinput text file" << std::endl; std::cout << "\t[-m]\twhat kind of mean" << std::endl; std::cout << "\t[-c]\tcolumn of which the mean is taken" << std::endl; std::cout << "\t[-s]\tskip: how many rows are skipped" << std::endl; std::cout << "\t[-p]\toutput precision" << std::endl; std::cout << "-m should be \"arithmetic\", \"geometric\" or \"median\", the default is \"arithmetic\"." << std::endl; std::cout << "The default output precision is 6." << std::endl; std::cout << "The output for median is: minimum, first quartile, median, third quartile, maximum." << std::endl; } // end PrintHelp <|endoftext|>
<commit_before>/**\file * \brief "Hello World" HTTP Server * * This is an example HTTP server that serves a simple "Hello World!" on /, and * a 404 on all other resources. * * Call it like this: * \code * $ ./http-hello localhost 8080 * \endcode * * With localhost and 8080 being a host name and port of your choosing. Then, * while the programme is running, open a browser and go to * http://localhost:8080/ and you should see the familiar greeting. * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: http://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/http.h> #include <iostream> using namespace efgy; using asio::ip::tcp; /**\brief Hello World request handler * * This function serves the familiar "Hello World!" when called. * * \param[out] session The HTTP session to answer on. * * \returns true (always, as we always reply). */ static bool hello(typename net::http::server<tcp>::session &session, std::smatch &) { session.reply(200, "Hello World!"); return true; } /**\brief Hello World request handler for /quit * * When this handler is invoked, it stops the ASIO IO handler (after replying, * maybe...). * * \note Having this on your production server in this exact way is PROBABLY a * really bad idea, unless you gate it in an upstream forward proxy. Or * you have some way of automatically respawning your server. Or both. * * \param[out] session The HTTP session to answer on. * * \returns true (always, as we always reply). */ static bool quit(typename net::http::server<tcp>::session &session, std::smatch &) { session.reply(200, "Good-Bye, Cruel World!"); session.server.io.stop(); return true; } /**\brief Main function for the HTTP demo * * This is the main function for the HTTP Hello World demo. * * \param[in] argc Process argument count. * \param[in] argv Process argument vector * * \returns 0 when nothing bad happened, 1 otherwise. */ int main(int argc, char *argv[]) { try { if (argc != 3) { std::cerr << "Usage: http-hello <host> <port>\n"; return 1; } asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; if (endpoint_iterator != end) { tcp::endpoint endpoint = *endpoint_iterator; net::http::server<tcp> s(io_service, endpoint, std::cout); s.processor.add("^/$", hello); s.processor.add("^/quit$", quit); io_service.run(); } return 0; } catch (std::exception & e) { std::cerr << "Exception: " << e.what() << "\n"; } catch (std::system_error & e) { std::cerr << "System Error: " << e.what() << "\n"; } return 1; } <commit_msg>forgot to add anappropriate group tag<commit_after>/**\file * \ingroup example-programmes * \brief "Hello World" HTTP Server * * This is an example HTTP server that serves a simple "Hello World!" on /, and * a 404 on all other resources. * * Call it like this: * \code * $ ./http-hello localhost 8080 * \endcode * * With localhost and 8080 being a host name and port of your choosing. Then, * while the programme is running, open a browser and go to * http://localhost:8080/ and you should see the familiar greeting. * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: http://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/http.h> #include <iostream> using namespace efgy; using asio::ip::tcp; /**\brief Hello World request handler * * This function serves the familiar "Hello World!" when called. * * \param[out] session The HTTP session to answer on. * * \returns true (always, as we always reply). */ static bool hello(typename net::http::server<tcp>::session &session, std::smatch &) { session.reply(200, "Hello World!"); return true; } /**\brief Hello World request handler for /quit * * When this handler is invoked, it stops the ASIO IO handler (after replying, * maybe...). * * \note Having this on your production server in this exact way is PROBABLY a * really bad idea, unless you gate it in an upstream forward proxy. Or * you have some way of automatically respawning your server. Or both. * * \param[out] session The HTTP session to answer on. * * \returns true (always, as we always reply). */ static bool quit(typename net::http::server<tcp>::session &session, std::smatch &) { session.reply(200, "Good-Bye, Cruel World!"); session.server.io.stop(); return true; } /**\brief Main function for the HTTP demo * * This is the main function for the HTTP Hello World demo. * * \param[in] argc Process argument count. * \param[in] argv Process argument vector * * \returns 0 when nothing bad happened, 1 otherwise. */ int main(int argc, char *argv[]) { try { if (argc != 3) { std::cerr << "Usage: http-hello <host> <port>\n"; return 1; } asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; if (endpoint_iterator != end) { tcp::endpoint endpoint = *endpoint_iterator; net::http::server<tcp> s(io_service, endpoint, std::cout); s.processor.add("^/$", hello); s.processor.add("^/quit$", quit); io_service.run(); } return 0; } catch (std::exception & e) { std::cerr << "Exception: " << e.what() << "\n"; } catch (std::system_error & e) { std::cerr << "System Error: " << e.what() << "\n"; } return 1; } <|endoftext|>
<commit_before>//============================================================================// // File: qcan_frame.hpp // // Description: QCAN classes - CAN frame // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'LICENSE' file. // // // //============================================================================// #ifndef QCAN_FRAME_HPP_ #define QCAN_FRAME_HPP_ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #include <QByteArray> #include <QDataStream> #include <QString> //----------------------------------------------------------------------------- /*! ** \file qcan_frame.hpp ** \brief CAN frame ** ** This file ... ** */ typedef struct QCanTimestamp_s { uint32_t ulSeconds; uint32_t ulNanoSeconds; } QCanTimestamp_ts; #define CAN_FRAME_DATA_MAX 64 #define QCAN_FRAME_ARRAY_SIZE 96 //----------------------------------------------------------------------------- /*! ** \class QCanFrame ** \brief CAN frame ** */ class QCanFrame { public: enum Type_e { /*! Classic CAN, Standard frame format */ eTYPE_CAN_STD = 0, /*! Classic CAN, Extended frame format */ eTYPE_CAN_EXT, /*! ISO CAN FD, Standard frame format */ eTYPE_FD_STD, /*! ISO CAN FD, Extended frame format */ eTYPE_FD_EXT, /*! QCan error frame, \see QCanFrameError */ eTYPE_QCAN_ERR = 0x10, /*! QCan API frame, \see QCanFrameApi */ eTYPE_QCAN_API = 0x20 }; /*! ** Constructs an empty classic standard CAN frame (type eTYPE_CAN_STD) ** with a DLC value of 0. */ QCanFrame(); /*! ** Constructs a CAN frame of type \c ubTypeR with an identifier value ** of \c ulIdentifierR and a DLC value of \c ubDlcR. */ QCanFrame(const Type_e & ubTypeR, const uint32_t & ulIdentifierR = 0, const uint8_t & ubDlcR = 0); virtual ~QCanFrame(); uint8_t data(const uint8_t & ubPosR) const; QByteArray data(void) const; uint8_t dataSize(void) const; uint16_t dataUInt16(const uint8_t & ubPosR, const bool & btMsbFirstR = 0) const; uint32_t dataUInt32(const uint8_t & ubPosR, const bool & btMsbFirstR = 0) const; uint8_t dlc(void) const; Type_e frameType(void) const; bool fromByteArray(const QByteArray & clByteArrayR); /*! ** \brief Identifier value ** \return Identifier of CAN frame ** \see setExtId(), setStdId() ** */ uint32_t identifier(void) const; bool isExtended(void) const; bool isRemote(void) const; /*! ** \brief Set Data ** \see data() ** ** This function sets the data in a CAN message. The parameter ** \c ubPosR must be within the range 0 .. 7 for classic frames and ** 0 .. 63 for FD frames. */ void setData(const uint8_t & ubPosR, const uint8_t & ubValueR); void setData(const QByteArray &clDataR); void setDataSize(uint8_t &ubSizeR); void setDataUInt16(const uint8_t & ubPosR, const uint16_t & uwValueR, const bool & btMsbFirstR = 0); void setDataUInt32(const uint8_t & ubPosR, const uint32_t & ulValueR, const bool & btMsbFirstR = 0); void setDlc(uint8_t ubDlcV); void setExtId(uint32_t ulIdentifierV); void setFrameType(const Type_e &ubTypeR); void setMarker(const uint32_t & ulMarkerValueR); void setRemote(const bool & btRtrR = true); void setStdId(uint16_t uwIdentifierV); void setUser(const uint32_t & ulUserValueR); virtual QByteArray toByteArray() const; virtual QString toString(const bool & btShowTimeR = false); bool operator==(const QCanFrame & clCanFrameR); bool operator!=(const QCanFrame & clCanFrameR); friend QDataStream & operator<< (QDataStream & clStreamR, const QCanFrame & clCanFrameR); friend QDataStream & operator>> (QDataStream & clStreamR, QCanFrame & clCanFrameR); private: /*! ** The identifier field may have 11 bits for standard frames ** (CAN specification 2.0A) or 29 bits for extended frames ** (CAN specification 2.0B). */ uint32_t ulIdentifierP; /*! ** The data length code denotes the number of data bytes ** which are transmitted by a message. ** The possible value range for the data length code is ** from 0 to 15. */ uint8_t ubMsgDlcP; /*! ** The structure member \c ubMsgCtrlP defines the ** different frame types (2.0A / 2.0B / Classic / FD / RTR). ** <ul> ** <li>Bit 0: Std. / Ext. Frame ** <li>Bit 1: Classic CAN / CAN FD ** <li>Bit 2: Remote Frame ** <li>Bit 3: Overload Frame ** <li>Bit 4: Internal: Error frame ** <li>Bit 5: Internal: Function frame ** <li>Bit 6: ISO CAN FD: value of EDL bit ** <li>Bit 7: ISO CAN FD: value of ESI bit ** </ul> */ uint8_t ubMsgCtrlP; /*! ** The data field has up to 64 bytes of message data. ** The number of used bytes is described via the structure ** member \c ubMsgDlcP. */ uint8_t aubByteP[CAN_FRAME_DATA_MAX]; /*! ** The time stamp field defines the time when a CAN message ** was received by the CAN controller. This is an optional ** field (available if #CP_CAN_MSG_TIME is set to 1). */ QCanTimestamp_ts tsMsgTimeP; /*! ** The field user data can hold a 32 bit value, which is ** defined by the user. */ uint32_t ulMsgUserP; /*! ** The field user data can hold a 32 bit value, which is ** defined by the user. */ uint32_t ulMsgMarkerP; }; #endif // QCAN_FRAME_HPP_ <commit_msg>- add documentation - change parameter type for setDataSize()<commit_after>//============================================================================// // File: qcan_frame.hpp // // Description: QCAN classes - CAN frame // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'LICENSE' file. // // // //============================================================================// #ifndef QCAN_FRAME_HPP_ #define QCAN_FRAME_HPP_ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #include <QByteArray> #include <QDataStream> #include <QString> //----------------------------------------------------------------------------- /*! ** \file qcan_frame.hpp ** \brief CAN frame ** ** This file ... ** */ typedef struct QCanTimestamp_s { uint32_t ulSeconds; uint32_t ulNanoSeconds; } QCanTimestamp_ts; #define CAN_FRAME_DATA_MAX 64 #define QCAN_FRAME_ARRAY_SIZE 96 //----------------------------------------------------------------------------- /*! ** \class QCanFrame ** \brief CAN frame ** */ class QCanFrame { public: enum Type_e { /*! Classic CAN, Standard frame format */ eTYPE_CAN_STD = 0, /*! Classic CAN, Extended frame format */ eTYPE_CAN_EXT, /*! ISO CAN FD, Standard frame format */ eTYPE_FD_STD, /*! ISO CAN FD, Extended frame format */ eTYPE_FD_EXT, /*! QCan error frame, \see QCanFrameError */ eTYPE_QCAN_ERR = 0x10, /*! QCan API frame, \see QCanFrameApi */ eTYPE_QCAN_API = 0x20 }; /*! ** Constructs an empty classic standard CAN frame (type eTYPE_CAN_STD) ** with a DLC value of 0. */ QCanFrame(); /*! ** Constructs a CAN frame of type \c ubTypeR with an identifier value ** of \c ulIdentifierR and a DLC value of \c ubDlcR. */ QCanFrame(const Type_e & ubTypeR, const uint32_t & ulIdentifierR = 0, const uint8_t & ubDlcR = 0); virtual ~QCanFrame(); uint8_t data(const uint8_t & ubPosR) const; QByteArray data(void) const; /*! ** \see dlc() ** ** The function returns the number of bytes that are valid ** for the CAN frame. The possible value range is 0 to 8 for ** classic CAN frames and 0 to 64 for CAN FD frames. */ uint8_t dataSize(void) const; uint16_t dataUInt16(const uint8_t & ubPosR, const bool & btMsbFirstR = 0) const; uint32_t dataUInt32(const uint8_t & ubPosR, const bool & btMsbFirstR = 0) const; /*! ** \see dataSize() ** ** The function returns the DLC value (data length code) ** for the CAN frame. The possible value range is 0 to 8 for ** classic CAN frames and 0 to 15 for CAN FD frames. */ uint8_t dlc(void) const; Type_e frameType(void) const; bool fromByteArray(const QByteArray & clByteArrayR); /*! ** \brief Identifier value ** \return Identifier of CAN frame ** \see setExtId(), setStdId() ** */ uint32_t identifier(void) const; bool isExtended(void) const; bool isRemote(void) const; /*! ** \brief Set Data ** \see data() ** ** This function sets the data in a CAN message. The parameter ** \c ubPosR must be within the range 0 .. 7 for classic frames and ** 0 .. 63 for FD frames. */ void setData(const uint8_t & ubPosR, const uint8_t & ubValueR); void setData(const QByteArray &clDataR); /*! ** \see setDlc() ** ** The function sets the number of data bytes that are valid ** for the CAN frame. The possible value range is 0 to 8 for ** classic CAN frames and 0 to 64 for CAN FD frames. */ void setDataSize(uint8_t ubSizeV); void setDataUInt16(const uint8_t & ubPosR, const uint16_t & uwValueR, const bool & btMsbFirstR = 0); void setDataUInt32(const uint8_t & ubPosR, const uint32_t & ulValueR, const bool & btMsbFirstR = 0); /*! ** \see setDataSize() ** ** The function sets the DLC value (data length code) ** for the CAN frame. The possible value range is 0 to 8 for ** classic CAN frames and 0 to 15 for CAN FD frames. */ void setDlc(uint8_t ubDlcV); void setExtId(uint32_t ulIdentifierV); void setFrameType(const Type_e &ubTypeR); void setMarker(const uint32_t & ulMarkerValueR); void setRemote(const bool & btRtrR = true); void setStdId(uint16_t uwIdentifierV); void setUser(const uint32_t & ulUserValueR); virtual QByteArray toByteArray() const; virtual QString toString(const bool & btShowTimeR = false); bool operator==(const QCanFrame & clCanFrameR); bool operator!=(const QCanFrame & clCanFrameR); friend QDataStream & operator<< (QDataStream & clStreamR, const QCanFrame & clCanFrameR); friend QDataStream & operator>> (QDataStream & clStreamR, QCanFrame & clCanFrameR); private: /*! ** The identifier field may have 11 bits for standard frames ** (CAN specification 2.0A) or 29 bits for extended frames ** (CAN specification 2.0B). */ uint32_t ulIdentifierP; /*! ** The data length code denotes the number of data bytes ** which are transmitted by a message. ** The possible value range for the data length code is ** from 0 to 15. */ uint8_t ubMsgDlcP; /*! ** The structure member \c ubMsgCtrlP defines the ** different frame types (2.0A / 2.0B / Classic / FD / RTR). ** <ul> ** <li>Bit 0: Std. / Ext. Frame ** <li>Bit 1: Classic CAN / CAN FD ** <li>Bit 2: Remote Frame ** <li>Bit 3: Overload Frame ** <li>Bit 4: Internal: Error frame ** <li>Bit 5: Internal: Function frame ** <li>Bit 6: ISO CAN FD: value of EDL bit ** <li>Bit 7: ISO CAN FD: value of ESI bit ** </ul> */ uint8_t ubMsgCtrlP; /*! ** The data field has up to 64 bytes of message data. ** The number of used bytes is described via the structure ** member \c ubMsgDlcP. */ uint8_t aubByteP[CAN_FRAME_DATA_MAX]; /*! ** The time stamp field defines the time when a CAN message ** was received by the CAN controller. This is an optional ** field (available if #CP_CAN_MSG_TIME is set to 1). */ QCanTimestamp_ts tsMsgTimeP; /*! ** The field user data can hold a 32 bit value, which is ** defined by the user. */ uint32_t ulMsgUserP; /*! ** The field user data can hold a 32 bit value, which is ** defined by the user. */ uint32_t ulMsgMarkerP; }; #endif // QCAN_FRAME_HPP_ <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young 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 "angular_quadrature.hpp" #include <iomanip> #include <iostream> #include <string> #include <vector> #include "pugixml.hpp" #include "util/error.hpp" #include "util/files.hpp" #include "util/fp_utils.hpp" #include "util/string_utils.hpp" #include "util/validate_input.hpp" #include "core/angular_quadrature_user.hpp" #include "core/constants.hpp" #include "core/level_symmetric.hpp" #include "core/product_quadrature.hpp" namespace { const std::vector<std::string> recognized_attributes_ls = {"type", "order"}; const std::vector<std::string> recognized_attributes_prod = { "type", "n_azimuthal", "n_polar"}; const std::vector<std::string> recognized_attributes_user = {"type"}; } namespace mocc { const int AngularQuadrature::reflection_[3][8] = {{1, 0, 3, 2, 5, 4, 7, 6}, {3, 2, 1, 0, 7, 6, 5, 4}, {4, 5, 6, 7, 0, 1, 2, 3}}; AngularQuadrature::AngularQuadrature(const pugi::xml_node &input) { // Make sure we got input if (input.empty()) { throw EXCEPT("No input provided for angular quadrature."); } if (input.name() != std::string("ang_quad")) { std::cerr << input.name() << std::endl; throw EXCEPT("Input is not an <ang_quad/> tag"); } // extract the quadrature order, if present n_azimuthal_ = input.attribute("n_azimuthal").as_int(-1); n_polar_ = input.attribute("n_polar").as_int(-1); // Extract the quadrature type std::string type_str = input.attribute("type").value(); sanitize(type_str); if ((type_str == "ls") || (type_str == "level-symmetric")) { validate_input(input, recognized_attributes_ls); type_ = QuadratureType::LS; // extract the quadrature order int order = input.attribute("order").as_int(-1); // Generate angles for octant 1 angles_ = GenSn(order); } else if ((type_str == "cg") || (type_str == "chebyshev-gauss")) { validate_input(input, recognized_attributes_prod); if ((n_azimuthal_ < 1) || (n_polar_ < 1)) { throw EXCEPT("Number of polar or azimuthal angles is invalid"); } type_ = QuadratureType::CHEB_GAUSS; // Generate angles for octant 1 angles_ = GenProduct(GenChebyshev(n_azimuthal_), GenGauss(n_polar_)); } else if ((type_str == "cy") || (type_str == "chebyshev-yamamoto")) { validate_input(input, recognized_attributes_prod); if ((n_azimuthal_ < 1) || (n_polar_ < 1)) { throw EXCEPT("Number of polar or azimuthal angles is invalid"); } type_ = QuadratureType::CHEB_YAMAMOTO; // Generate angles for octant 1 angles_ = GenProduct(GenChebyshev(n_azimuthal_), GenYamamoto(n_polar_)); } else if (type_str == "user") { validate_input(input, recognized_attributes_user); type_ = QuadratureType::USER; angles_ = GenUserQuadrature(input); } else { std::cerr << "'" << type_str << "'" << std::endl; throw EXCEPT("Invalid angular quadrature type specified."); } // Store the number of angles per octant ndir_oct_ = angles_.size(); // Expand angles to other octants for (int ioct = 2; ioct <= 8; ioct++) { for (int iang = 0; iang < ndir_oct_; iang++) { Angle a = angles_[iang]; angles_.push_back(a.to_octant(ioct)); } } return; } AngularQuadrature::AngularQuadrature(const H5Node &input) { VecF ox; VecF oy; VecF oz; VecF weights; VecF alpha; VecF theta; VecF rsintheta; input.read("ang_quad/omega_x", ox); input.read("ang_quad/omega_y", oy); input.read("ang_quad/omega_z", oz); input.read("ang_quad/weight", weights); input.read("ang_quad/alpha", alpha); input.read("ang_quad/theta", theta); if ((ox.size() != oy.size()) || (ox.size() != oz.size()) || (ox.size() != weights.size())) { throw EXCEPT("Incompatible data sizes"); } int size = ox.size(); if (size % 8 != 0) { throw EXCEPT("Size is not evenly-divisible by 8"); } ndir_oct_ = size / 8; angles_.reserve(size); for (int iang = 0; iang < size; iang++) { angles_.emplace_back(ox[iang], oy[iang], oz[iang], weights[iang]); // This is a bit of a hack to force bit-for-bit conformance with the // values in the HDF5 file. the standard trig functions will result // in some weird precision problems angles_.back().theta = theta[iang]; angles_.back().alpha = alpha[iang]; } type_ = QuadratureType::IMPORT; return; } void AngularQuadrature::modify_angle(int iang, Angle ang) { assert(iang < ndir_oct_); angles_[iang] = ang; for (int ioct = 1; ioct < 8; ioct++) { angles_[iang + ioct * ndir_oct_] = ang.to_octant(ioct + 1); } } std::ostream &operator<<(std::ostream &os, const AngularQuadrature &angquad) { const int w = 12; os << std::setw(w) << "Alpha" << std::setw(w) << "Theta" << std::setw(w) << "omega x" << std::setw(w) << "omega y" << std::setw(w) << "omega z" << std::setw(w) << "weight" << std::setw(w) << "rsintheta" << std::endl; for (auto &ang : angquad.angles_) { os << ang << std::endl; } return os; } void AngularQuadrature::output(H5Node &node) const { VecF alpha; alpha.reserve(this->ndir()); VecF theta; theta.reserve(this->ndir()); VecF ox; ox.reserve(this->ndir()); VecF oy; oy.reserve(this->ndir()); VecF oz; oz.reserve(this->ndir()); VecF w; w.reserve(this->ndir()); for (auto a : angles_) { alpha.push_back(a.alpha); theta.push_back(a.theta); ox.push_back(a.ox); oy.push_back(a.oy); oz.push_back(a.oz); w.push_back(a.weight); } auto g = node.create_group("ang_quad"); g.write("alpha", alpha); g.write("theta", theta); g.write("omega_x", ox); g.write("omega_y", oy); g.write("omega_z", oz); g.write("weight", w); return; } void AngularQuadrature::update_weights() { // Different quadratures will be adjusted differently switch (type_) { case QuadratureType::LS: Warn("Don't have weight updates for modularized " "level-symmetric quadrature yet."); break; case QuadratureType::IMPORT: LogScreen << "Manually-specified quadratures are not changed in " "modularization." << std::endl; break; case QuadratureType::USER: LogScreen << "User-specified quadrature weights are not changed in " "modularization." << std::endl; break; // These product quadratures are based on the Chebyshev quadrature, // which as implemented starts as evenly distributed angles of equal // weight. Post modularization, only these azimuthal angles are // modified. Here we update the azimuthal weights to be the portion of // the unit circle that they cover. case QuadratureType::CHEB_GAUSS: case QuadratureType::CHEB_YAMAMOTO: this->update_chebyshev_weights(); break; } return; } /** * \todo This should live with the quadrature type that it is updating (so * somewhere in the product_quadrature.hpp file) */ void AngularQuadrature::update_chebyshev_weights() { // Get the set of polar angles std::vector<std::pair<real_t, real_t>> polar_angles; if (type_ == QuadratureType::CHEB_GAUSS) { polar_angles = GenGauss(n_polar_); } else if (type_ == QuadratureType::CHEB_YAMAMOTO) { polar_angles = GenYamamoto(n_polar_); } else { throw EXCEPT("How did you get here?"); } // Get a vector of the actual, modified/modularized azimuthal angles VecF azi_angles; azi_angles.reserve(ndir_oct_); for (auto angle_it = this->octant(1); angle_it != this->octant(2); ++angle_it) { azi_angles.push_back(angle_it->alpha); } // Make sure that the azimuthal angles are sorted properly so the call // to std::unique will work properly std::sort(azi_angles.begin(), azi_angles.end()); // Remove duplicate azimuthal angles azi_angles.erase( std::unique(azi_angles.begin(), azi_angles.end(), fp_equiv_ulp), azi_angles.end()); // Make sure that what we have matches the number of azimuthal angles // that we should have if ((int)azi_angles.size() != n_azimuthal_) { throw EXCEPT("Wrong number of azimuthal angles!"); } // Calculate the new azimuthal weights VecF azi_weights(n_azimuthal_); VecF azi_bounds; azi_bounds.reserve(n_azimuthal_ + 1); azi_bounds.push_back(0.0); for (int i = 0; i < n_azimuthal_ - 1; i++) { azi_bounds.push_back((azi_angles[i] + azi_angles[i + 1]) / 2.0); } azi_bounds.push_back(HPI); std::vector<std::pair<real_t, real_t>> azi_pairs; azi_pairs.reserve(n_azimuthal_); int iang = 0; for (real_t alpha : azi_angles) { real_t hpi = HPI; real_t w = (azi_bounds[iang + 1] - azi_bounds[iang]) / hpi; azi_pairs.emplace_back(alpha, w); iang++; } angles_ = GenProduct(azi_pairs, polar_angles); // Expand angles to other octants for (int ioct = 2; ioct <= 8; ioct++) { for (int iang = 0; iang < ndir_oct_; iang++) { Angle a = angles_[iang]; angles_.push_back(a.to_octant(ioct)); } } return; } } <commit_msg>Add output of n_polar and n_azimuthal from AngQuad<commit_after>/* Copyright 2016 Mitchell Young 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 "angular_quadrature.hpp" #include <iomanip> #include <iostream> #include <string> #include <vector> #include "pugixml.hpp" #include "util/error.hpp" #include "util/files.hpp" #include "util/fp_utils.hpp" #include "util/string_utils.hpp" #include "util/validate_input.hpp" #include "core/angular_quadrature_user.hpp" #include "core/constants.hpp" #include "core/level_symmetric.hpp" #include "core/product_quadrature.hpp" namespace { const std::vector<std::string> recognized_attributes_ls = {"type", "order"}; const std::vector<std::string> recognized_attributes_prod = { "type", "n_azimuthal", "n_polar"}; const std::vector<std::string> recognized_attributes_user = {"type"}; } namespace mocc { const int AngularQuadrature::reflection_[3][8] = {{1, 0, 3, 2, 5, 4, 7, 6}, {3, 2, 1, 0, 7, 6, 5, 4}, {4, 5, 6, 7, 0, 1, 2, 3}}; AngularQuadrature::AngularQuadrature(const pugi::xml_node &input) { // Make sure we got input if (input.empty()) { throw EXCEPT("No input provided for angular quadrature."); } if (input.name() != std::string("ang_quad")) { std::cerr << input.name() << std::endl; throw EXCEPT("Input is not an <ang_quad/> tag"); } // extract the quadrature order, if present n_azimuthal_ = input.attribute("n_azimuthal").as_int(-1); n_polar_ = input.attribute("n_polar").as_int(-1); // Extract the quadrature type std::string type_str = input.attribute("type").value(); sanitize(type_str); if ((type_str == "ls") || (type_str == "level-symmetric")) { validate_input(input, recognized_attributes_ls); type_ = QuadratureType::LS; // extract the quadrature order int order = input.attribute("order").as_int(-1); // Generate angles for octant 1 angles_ = GenSn(order); } else if ((type_str == "cg") || (type_str == "chebyshev-gauss")) { validate_input(input, recognized_attributes_prod); if ((n_azimuthal_ < 1) || (n_polar_ < 1)) { throw EXCEPT("Number of polar or azimuthal angles is invalid"); } type_ = QuadratureType::CHEB_GAUSS; // Generate angles for octant 1 angles_ = GenProduct(GenChebyshev(n_azimuthal_), GenGauss(n_polar_)); } else if ((type_str == "cy") || (type_str == "chebyshev-yamamoto")) { validate_input(input, recognized_attributes_prod); if ((n_azimuthal_ < 1) || (n_polar_ < 1)) { throw EXCEPT("Number of polar or azimuthal angles is invalid"); } type_ = QuadratureType::CHEB_YAMAMOTO; // Generate angles for octant 1 angles_ = GenProduct(GenChebyshev(n_azimuthal_), GenYamamoto(n_polar_)); } else if (type_str == "user") { validate_input(input, recognized_attributes_user); type_ = QuadratureType::USER; angles_ = GenUserQuadrature(input); } else { std::cerr << "'" << type_str << "'" << std::endl; throw EXCEPT("Invalid angular quadrature type specified."); } // Store the number of angles per octant ndir_oct_ = angles_.size(); // Expand angles to other octants for (int ioct = 2; ioct <= 8; ioct++) { for (int iang = 0; iang < ndir_oct_; iang++) { Angle a = angles_[iang]; angles_.push_back(a.to_octant(ioct)); } } return; } AngularQuadrature::AngularQuadrature(const H5Node &input) { VecF ox; VecF oy; VecF oz; VecF weights; VecF alpha; VecF theta; VecF rsintheta; input.read("ang_quad/omega_x", ox); input.read("ang_quad/omega_y", oy); input.read("ang_quad/omega_z", oz); input.read("ang_quad/weight", weights); input.read("ang_quad/alpha", alpha); input.read("ang_quad/theta", theta); if ((ox.size() != oy.size()) || (ox.size() != oz.size()) || (ox.size() != weights.size())) { throw EXCEPT("Incompatible data sizes"); } int size = ox.size(); if (size % 8 != 0) { throw EXCEPT("Size is not evenly-divisible by 8"); } ndir_oct_ = size / 8; angles_.reserve(size); for (int iang = 0; iang < size; iang++) { angles_.emplace_back(ox[iang], oy[iang], oz[iang], weights[iang]); // This is a bit of a hack to force bit-for-bit conformance with the // values in the HDF5 file. the standard trig functions will result // in some weird precision problems angles_.back().theta = theta[iang]; angles_.back().alpha = alpha[iang]; } type_ = QuadratureType::IMPORT; return; } void AngularQuadrature::modify_angle(int iang, Angle ang) { assert(iang < ndir_oct_); angles_[iang] = ang; for (int ioct = 1; ioct < 8; ioct++) { angles_[iang + ioct * ndir_oct_] = ang.to_octant(ioct + 1); } } std::ostream &operator<<(std::ostream &os, const AngularQuadrature &angquad) { const int w = 12; os << std::setw(w) << "Alpha" << std::setw(w) << "Theta" << std::setw(w) << "omega x" << std::setw(w) << "omega y" << std::setw(w) << "omega z" << std::setw(w) << "weight" << std::setw(w) << "rsintheta" << std::endl; for (auto &ang : angquad.angles_) { os << ang << std::endl; } return os; } void AngularQuadrature::output(H5Node &node) const { VecF alpha; alpha.reserve(this->ndir()); VecF theta; theta.reserve(this->ndir()); VecF ox; ox.reserve(this->ndir()); VecF oy; oy.reserve(this->ndir()); VecF oz; oz.reserve(this->ndir()); VecF w; w.reserve(this->ndir()); for (auto a : angles_) { alpha.push_back(a.alpha); theta.push_back(a.theta); ox.push_back(a.ox); oy.push_back(a.oy); oz.push_back(a.oz); w.push_back(a.weight); } auto g = node.create_group("ang_quad"); g.write("n_polar", n_polar_); g.write("n_azimuthal", n_azimuthal_); g.write("alpha", alpha); g.write("theta", theta); g.write("omega_x", ox); g.write("omega_y", oy); g.write("omega_z", oz); g.write("weight", w); return; } void AngularQuadrature::update_weights() { // Different quadratures will be adjusted differently switch (type_) { case QuadratureType::LS: Warn("Don't have weight updates for modularized " "level-symmetric quadrature yet."); break; case QuadratureType::IMPORT: LogScreen << "Manually-specified quadratures are not changed in " "modularization." << std::endl; break; case QuadratureType::USER: LogScreen << "User-specified quadrature weights are not changed in " "modularization." << std::endl; break; // These product quadratures are based on the Chebyshev quadrature, // which as implemented starts as evenly distributed angles of equal // weight. Post modularization, only these azimuthal angles are // modified. Here we update the azimuthal weights to be the portion of // the unit circle that they cover. case QuadratureType::CHEB_GAUSS: case QuadratureType::CHEB_YAMAMOTO: this->update_chebyshev_weights(); break; } return; } /** * \todo This should live with the quadrature type that it is updating (so * somewhere in the product_quadrature.hpp file) */ void AngularQuadrature::update_chebyshev_weights() { // Get the set of polar angles std::vector<std::pair<real_t, real_t>> polar_angles; if (type_ == QuadratureType::CHEB_GAUSS) { polar_angles = GenGauss(n_polar_); } else if (type_ == QuadratureType::CHEB_YAMAMOTO) { polar_angles = GenYamamoto(n_polar_); } else { throw EXCEPT("How did you get here?"); } // Get a vector of the actual, modified/modularized azimuthal angles VecF azi_angles; azi_angles.reserve(ndir_oct_); for (auto angle_it = this->octant(1); angle_it != this->octant(2); ++angle_it) { azi_angles.push_back(angle_it->alpha); } // Make sure that the azimuthal angles are sorted properly so the call // to std::unique will work properly std::sort(azi_angles.begin(), azi_angles.end()); // Remove duplicate azimuthal angles azi_angles.erase( std::unique(azi_angles.begin(), azi_angles.end(), fp_equiv_ulp), azi_angles.end()); // Make sure that what we have matches the number of azimuthal angles // that we should have if ((int)azi_angles.size() != n_azimuthal_) { throw EXCEPT("Wrong number of azimuthal angles!"); } // Calculate the new azimuthal weights VecF azi_weights(n_azimuthal_); VecF azi_bounds; azi_bounds.reserve(n_azimuthal_ + 1); azi_bounds.push_back(0.0); for (int i = 0; i < n_azimuthal_ - 1; i++) { azi_bounds.push_back((azi_angles[i] + azi_angles[i + 1]) / 2.0); } azi_bounds.push_back(HPI); std::vector<std::pair<real_t, real_t>> azi_pairs; azi_pairs.reserve(n_azimuthal_); int iang = 0; for (real_t alpha : azi_angles) { real_t hpi = HPI; real_t w = (azi_bounds[iang + 1] - azi_bounds[iang]) / hpi; azi_pairs.emplace_back(alpha, w); iang++; } angles_ = GenProduct(azi_pairs, polar_angles); // Expand angles to other octants for (int ioct = 2; ioct <= 8; ioct++) { for (int iang = 0; iang < ndir_oct_; iang++) { Angle a = angles_[iang]; angles_.push_back(a.to_octant(ioct)); } } return; } } <|endoftext|>
<commit_before>#include "pass_bits/helper/seed.hpp" namespace pass { decltype(seed::seed_) seed::seed_ = 12345; decltype(seed::generator_) seed::generator_; std::mt19937_64 &seed::get_generator() { return generator_; } void seed::set_seed( const arma::arma_rng::seed_type seed) { seed_ = seed; // Seeding C++'s and Armadillo's generator. generator_.seed(seed_); arma::arma_rng::set_seed(seed_); } void seed::set_random_seed() { // Initialise Armadillo's generator with any random seed. // This seed will be overwritten later on, no need to store it. arma::arma_rng::set_seed_random(); #if defined(SUPPORT_MPI) // For programs using MPI, each node needs to seeded differently in order to avoid a degeneration of the random number generator, due to synchronisation. // Basically, we generated as much random numbers as there are nodes and seed the i-th node by the i-th generated random number. int node_rank; int number_of_nodes; MPI_Comm_rank(MPI_COMM_WORLD, &node_rank); MPI_Comm_size(MPI_COMM_WORLD, &number_of_nodes); set_seed(arma::randi<arma::Col<arma::arma_rng::seed_type>>(static_cast<arma::uword>(number_of_nodes))(static_cast<arma::uword>(node_rank))); #else // Without MPI, using the first random number generated by Armadillo's generator as seed is sufficient. set_seed(arma::randi<arma::Col<arma::arma_rng::seed_type>>(1)(0)); #endif } arma::arma_rng::seed_type seed::get_seed() { return seed_; } } // namespace pass <commit_msg>bug fix<commit_after>#include "pass_bits/helper/seed.hpp" namespace pass { decltype(seed::seed_) seed::seed_ = 12345; decltype(seed::generator_) seed::generator_; std::mt19937_64 &seed::get_generator() { return generator_; } void seed::set_seed(const arma::arma_rng::seed_type seed) { seed_ = seed; // Seeding C++'s and Armadillo's generator. generator_.seed(seed_); arma::arma_rng::set_seed(seed_); } void seed::set_random_seed() { // Initialise Armadillo's generator with any random seed. // This seed will be overwritten later on, no need to store it. arma::arma_rng::set_seed_random(); #if defined(SUPPORT_MPI) // For programs using MPI, each node needs to seeded differently in order to avoid a degeneration of the random number generator, due to synchronisation. // Basically, we generated as much random numbers as there are nodes and seed the i-th node by the i-th generated random number. set_seed(arma::randi<arma::Col<arma::arma_rng::seed_type>>(static_cast<arma::uword>(pass::number_of_nodes()))(static_cast<arma::uword>(pass::node_rank()))); #else // Without MPI, using the first random number generated by Armadillo's generator as seed is sufficient. set_seed(arma::randi<arma::Col<arma::arma_rng::seed_type>>(1)(0)); #endif } arma::arma_rng::seed_type seed::get_seed() { return seed_; } } // namespace pass <|endoftext|>
<commit_before>#include <babylon/probes/reflection_probe.h> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/core/json_util.h> #include <babylon/engines/constants.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/materials/textures/render_target_texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/misc/string_tools.h> namespace BABYLON { ReflectionProbe::ReflectionProbe(const std::string& iName, const ISize& size, Scene* scene, bool generateMipMaps, bool useFloat, bool iLinearSpace) : name{iName} , position{Vector3::Zero()} , _parentContainer{nullptr} , samples{this, &ReflectionProbe::get_samples, &ReflectionProbe::set_samples} , refreshRate{this, &ReflectionProbe::get_refreshRate, &ReflectionProbe::set_refreshRate} , cubeTexture{this, &ReflectionProbe::get_cubeTexture} , renderList{this, &ReflectionProbe::get_renderList} , linearSpace{iLinearSpace} , _scene{scene} , _renderTargetTexture{nullptr} , _viewMatrix{Matrix::Identity()} , _target{Vector3::Zero()} , _add{Vector3::Zero()} , _attachedMesh{nullptr} , _invertYAxis{false} , _currentApplyByPostProcess{false} { auto textureType = Constants::TEXTURETYPE_UNSIGNED_BYTE; if (useFloat) { const auto caps = _scene->getEngine()->getCaps(); if (caps.textureHalfFloatRender) { textureType = Constants::TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender) { textureType = Constants::TEXTURETYPE_FLOAT; } } _renderTargetTexture = RenderTargetTexture::New(iName, RenderTargetSize{size.width, size.height}, scene, generateMipMaps, true, textureType, true); _renderTargetTexture->gammaSpace = !iLinearSpace; _renderTargetTexture->onBeforeRenderObservable.add( [scene, this](const int* faceIndex, EventState&) { const auto useReverseDepthBuffer = scene->getEngine()->useReverseDepthBuffer; switch (*faceIndex) { case 0: _add.copyFromFloats(1.f, 0.f, 0.f); break; case 1: _add.copyFromFloats(-1.f, 0.f, 0.f); break; case 2: _add.copyFromFloats(0.f, _invertYAxis ? 1.f : -1.f, 0.f); break; case 3: _add.copyFromFloats(0.f, _invertYAxis ? -1.f : 1.f, 0.f); break; case 4: _add.copyFromFloats(0.f, 0.f, scene->useRightHandedSystem() ? -1.f : 1.f); break; case 5: _add.copyFromFloats(0.f, 0.f, scene->useRightHandedSystem() ? 1.f : -1.f); break; default: break; } if (_attachedMesh) { position.copyFrom(_attachedMesh->getAbsolutePosition()); } position.addToRef(_add, _target); if (scene->useRightHandedSystem()) { Matrix::LookAtRHToRef(position, _target, Vector3::Up(), _viewMatrix); if (scene->activeCamera()) { _projectionMatrix = Matrix::PerspectiveFovRH( Math::PI / 2.f, 1, useReverseDepthBuffer ? scene->activeCamera()->maxZ : scene->activeCamera()->minZ, useReverseDepthBuffer ? scene->activeCamera()->minZ : scene->activeCamera()->maxZ, _scene->getEngine()->isNDCHalfZRange); scene->setTransformMatrix(_viewMatrix, _projectionMatrix); } } else { Matrix::LookAtLHToRef(position, _target, Vector3::Up(), _viewMatrix); if (_scene->activeCamera()) { _projectionMatrix = Matrix::PerspectiveFovLH( Math::PI / 2.f, 1, useReverseDepthBuffer ? scene->activeCamera()->maxZ : scene->activeCamera()->minZ, useReverseDepthBuffer ? scene->activeCamera()->minZ : scene->activeCamera()->maxZ, _scene->getEngine()->isNDCHalfZRange); _scene->setTransformMatrix(_viewMatrix, _projectionMatrix); } } _scene->_forcedViewPosition = std::make_unique<Vector3>(position); }); _renderTargetTexture->onBeforeBindObservable.add( [this](RenderTargetTexture* /*texture*/, EventState& /*es*/) -> void { _scene->getEngine()->_debugPushGroup( StringTools::printf("reflection probe generation for %s", name.c_str()), 1); _currentApplyByPostProcess = _scene->imageProcessingConfiguration()->applyByPostProcess(); if (linearSpace) { _scene->imageProcessingConfiguration()->applyByPostProcess = true; } }); _renderTargetTexture->onAfterUnbindObservable.add( [this](RenderTargetTexture* /*texture*/, EventState& /*es*/) -> void { _scene->imageProcessingConfiguration()->applyByPostProcess = _currentApplyByPostProcess; _scene->_forcedViewPosition = nullptr; _scene->updateTransformMatrix(true); _scene->getEngine()->_debugPopGroup(1); }); } ReflectionProbe::~ReflectionProbe() = default; void ReflectionProbe::addToScene(const ReflectionProbePtr& newReflectionProbe) { _scene->reflectionProbes.emplace_back(newReflectionProbe); } unsigned int ReflectionProbe::get_samples() const { return _renderTargetTexture->samples(); } void ReflectionProbe::set_samples(unsigned int value) { _renderTargetTexture->samples = value; } int ReflectionProbe::get_refreshRate() const { return _renderTargetTexture->refreshRate(); } void ReflectionProbe::set_refreshRate(int value) { _renderTargetTexture->refreshRate = value; } Scene* ReflectionProbe::getScene() const { return _scene; } RenderTargetTexturePtr& ReflectionProbe::get_cubeTexture() { return _renderTargetTexture; } std::vector<AbstractMesh*>& ReflectionProbe::get_renderList() { return _renderTargetTexture->renderList; } void ReflectionProbe::attachToMesh(AbstractMesh* mesh) { _attachedMesh = mesh; } void ReflectionProbe::setRenderingAutoClearDepthStencil(unsigned int renderingGroupId, bool autoClearDepthStencil) { _renderTargetTexture->setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); } void ReflectionProbe::dispose() { // Remove from the scene if found stl_util::remove_vector_elements_equal_sharedptr(_scene->reflectionProbes, this); if (_parentContainer) { stl_util::remove_vector_elements_equal_sharedptr(_parentContainer->reflectionProbes, this); _parentContainer = nullptr; } if (_renderTargetTexture) { _renderTargetTexture->dispose(); _renderTargetTexture = nullptr; } } std::string ReflectionProbe::toString(bool fullDetails) { std::ostringstream ret; ret << "Name: " << name; if (fullDetails) { ret << ", position: " << position.toString(); if (_attachedMesh) { ret << ", attached mesh: " << _attachedMesh->name; } } return ret.str(); } std::string ReflectionProbe::getClassName() const { return "ReflectionProbe"; } void ReflectionProbe::serialize(json& /*serializationObject*/) { } ReflectionProbePtr ReflectionProbe::Parse(const json& /*parsedReflectionProbe*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace BABYLON <commit_msg>Setting correct type<commit_after>#include <babylon/probes/reflection_probe.h> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/core/json_util.h> #include <babylon/engines/constants.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/materials/textures/render_target_texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/misc/string_tools.h> namespace BABYLON { ReflectionProbe::ReflectionProbe(const std::string& iName, const ISize& size, Scene* scene, bool generateMipMaps, bool useFloat, bool iLinearSpace) : name{iName} , position{Vector3::Zero()} , _parentContainer{nullptr} , samples{this, &ReflectionProbe::get_samples, &ReflectionProbe::set_samples} , refreshRate{this, &ReflectionProbe::get_refreshRate, &ReflectionProbe::set_refreshRate} , cubeTexture{this, &ReflectionProbe::get_cubeTexture} , renderList{this, &ReflectionProbe::get_renderList} , linearSpace{iLinearSpace} , _scene{scene} , _renderTargetTexture{nullptr} , _viewMatrix{Matrix::Identity()} , _target{Vector3::Zero()} , _add{Vector3::Zero()} , _attachedMesh{nullptr} , _invertYAxis{false} , _currentApplyByPostProcess{false} { auto textureType = Constants::TEXTURETYPE_UNSIGNED_BYTE; if (useFloat) { const auto caps = _scene->getEngine()->getCaps(); if (caps.textureHalfFloatRender) { textureType = Constants::TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender) { textureType = Constants::TEXTURETYPE_FLOAT; } } _renderTargetTexture = RenderTargetTexture::New(iName, RenderTargetSize{size.width, size.height}, scene, generateMipMaps, true, textureType, true); _renderTargetTexture->gammaSpace = !iLinearSpace; _renderTargetTexture->onBeforeRenderObservable.add( [scene, this](const int* faceIndex, EventState&) { const auto useReverseDepthBuffer = scene->getEngine()->useReverseDepthBuffer; switch (*faceIndex) { case 0: _add.copyFromFloats(1.f, 0.f, 0.f); break; case 1: _add.copyFromFloats(-1.f, 0.f, 0.f); break; case 2: _add.copyFromFloats(0.f, _invertYAxis ? 1.f : -1.f, 0.f); break; case 3: _add.copyFromFloats(0.f, _invertYAxis ? -1.f : 1.f, 0.f); break; case 4: _add.copyFromFloats(0.f, 0.f, scene->useRightHandedSystem() ? -1.f : 1.f); break; case 5: _add.copyFromFloats(0.f, 0.f, scene->useRightHandedSystem() ? 1.f : -1.f); break; default: break; } if (_attachedMesh) { position.copyFrom(_attachedMesh->getAbsolutePosition()); } position.addToRef(_add, _target); if (scene->useRightHandedSystem()) { Matrix::LookAtRHToRef(position, _target, Vector3::Up(), _viewMatrix); if (scene->activeCamera()) { _projectionMatrix = Matrix::PerspectiveFovRH( Math::PI / 2.f, 1.f, useReverseDepthBuffer ? scene->activeCamera()->maxZ : scene->activeCamera()->minZ, useReverseDepthBuffer ? scene->activeCamera()->minZ : scene->activeCamera()->maxZ, _scene->getEngine()->isNDCHalfZRange); scene->setTransformMatrix(_viewMatrix, _projectionMatrix); } } else { Matrix::LookAtLHToRef(position, _target, Vector3::Up(), _viewMatrix); if (_scene->activeCamera()) { _projectionMatrix = Matrix::PerspectiveFovLH( Math::PI / 2.f, 1.f, useReverseDepthBuffer ? scene->activeCamera()->maxZ : scene->activeCamera()->minZ, useReverseDepthBuffer ? scene->activeCamera()->minZ : scene->activeCamera()->maxZ, _scene->getEngine()->isNDCHalfZRange); _scene->setTransformMatrix(_viewMatrix, _projectionMatrix); } } _scene->_forcedViewPosition = std::make_unique<Vector3>(position); }); _renderTargetTexture->onBeforeBindObservable.add( [this](RenderTargetTexture* /*texture*/, EventState& /*es*/) -> void { _scene->getEngine()->_debugPushGroup( StringTools::printf("reflection probe generation for %s", name.c_str()), 1); _currentApplyByPostProcess = _scene->imageProcessingConfiguration()->applyByPostProcess(); if (linearSpace) { _scene->imageProcessingConfiguration()->applyByPostProcess = true; } }); _renderTargetTexture->onAfterUnbindObservable.add( [this](RenderTargetTexture* /*texture*/, EventState& /*es*/) -> void { _scene->imageProcessingConfiguration()->applyByPostProcess = _currentApplyByPostProcess; _scene->_forcedViewPosition = nullptr; _scene->updateTransformMatrix(true); _scene->getEngine()->_debugPopGroup(1); }); } ReflectionProbe::~ReflectionProbe() = default; void ReflectionProbe::addToScene(const ReflectionProbePtr& newReflectionProbe) { _scene->reflectionProbes.emplace_back(newReflectionProbe); } unsigned int ReflectionProbe::get_samples() const { return _renderTargetTexture->samples(); } void ReflectionProbe::set_samples(unsigned int value) { _renderTargetTexture->samples = value; } int ReflectionProbe::get_refreshRate() const { return _renderTargetTexture->refreshRate(); } void ReflectionProbe::set_refreshRate(int value) { _renderTargetTexture->refreshRate = value; } Scene* ReflectionProbe::getScene() const { return _scene; } RenderTargetTexturePtr& ReflectionProbe::get_cubeTexture() { return _renderTargetTexture; } std::vector<AbstractMesh*>& ReflectionProbe::get_renderList() { return _renderTargetTexture->renderList; } void ReflectionProbe::attachToMesh(AbstractMesh* mesh) { _attachedMesh = mesh; } void ReflectionProbe::setRenderingAutoClearDepthStencil(unsigned int renderingGroupId, bool autoClearDepthStencil) { _renderTargetTexture->setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); } void ReflectionProbe::dispose() { // Remove from the scene if found stl_util::remove_vector_elements_equal_sharedptr(_scene->reflectionProbes, this); if (_parentContainer) { stl_util::remove_vector_elements_equal_sharedptr(_parentContainer->reflectionProbes, this); _parentContainer = nullptr; } if (_renderTargetTexture) { _renderTargetTexture->dispose(); _renderTargetTexture = nullptr; } } std::string ReflectionProbe::toString(bool fullDetails) { std::ostringstream ret; ret << "Name: " << name; if (fullDetails) { ret << ", position: " << position.toString(); if (_attachedMesh) { ret << ", attached mesh: " << _attachedMesh->name; } } return ret.str(); } std::string ReflectionProbe::getClassName() const { return "ReflectionProbe"; } void ReflectionProbe::serialize(json& /*serializationObject*/) { } ReflectionProbePtr ReflectionProbe::Parse(const json& /*parsedReflectionProbe*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace BABYLON <|endoftext|>
<commit_before>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategyFactory.h" #include "InwardDistributedBeadingStrategy.h" #include "LimitedBeadingStrategy.h" #include "CenterDeviationBeadingStrategy.h" #include "WideningBeadingStrategy.h" #include "DistributedBeadingStrategy.h" #include "RedistributeBeadingStrategy.h" namespace cura { double inward_distributed_center_size = 2; StrategyType toStrategyType(char c) { switch (c) { case 'r': return StrategyType::Center; case 'd': return StrategyType::Distributed; case 'i': return StrategyType::InwardDistributed; } return StrategyType::COUNT; } std::string to_string(StrategyType type) { switch (type) { case StrategyType::Center: return "CenterDeviation"; case StrategyType::Distributed: return "Distributed"; case StrategyType::InwardDistributed: return "InwardDistributed"; default: return "unknown_strategy"; } } coord_t get_weighted_average(const coord_t preferred_bead_width_outer, const coord_t preferred_bead_width_inner, const coord_t max_bead_count) { if (max_bead_count > 2) { return ((preferred_bead_width_outer * 2) + preferred_bead_width_inner * (max_bead_count - 2)) / max_bead_count; } if (max_bead_count <= 0) { return preferred_bead_width_inner; } return preferred_bead_width_outer; } BeadingStrategy* BeadingStrategyFactory::makeStrategy(const StrategyType type, const coord_t preferred_bead_width_outer, const coord_t preferred_bead_width_inner, const coord_t preferred_transition_length, const float transitioning_angle, const bool print_thin_walls, const coord_t min_bead_width, const coord_t min_feature_size, const coord_t max_bead_count) { const coord_t bar_preferred_wall_width = get_weighted_average(preferred_bead_width_outer, preferred_bead_width_inner, max_bead_count); BeadingStrategy* ret = nullptr; switch (type) { case StrategyType::Center: ret = new CenterDeviationBeadingStrategy(bar_preferred_wall_width, transitioning_angle); break; case StrategyType::Distributed: ret = new DistributedBeadingStrategy(bar_preferred_wall_width, preferred_transition_length, transitioning_angle); break; case StrategyType::InwardDistributed: ret = new InwardDistributedBeadingStrategy(bar_preferred_wall_width, preferred_transition_length, transitioning_angle, inward_distributed_center_size); break; default: logError("Cannot make strategy!\n"); return nullptr; } if(print_thin_walls) { logDebug("Applying the Widening Beading meta-strategy with minimum input width %d and minimum output width %d.", min_feature_size, min_bead_width); ret = new WideningBeadingStrategy(ret, min_feature_size, min_bead_width); } if (max_bead_count > 0) { logDebug("Applying the Limited Beading meta-strategy with maximum bead count = %d.", max_bead_count); ret = new LimitedBeadingStrategy(max_bead_count, ret); logDebug("Applying the Redistribute meta-strategy with outer-wall width = %d, inner-wall width = %d", preferred_bead_width_outer, preferred_bead_width_inner); ret = new RedistributeBeadingStrategy(preferred_bead_width_outer, preferred_bead_width_inner, ret); } return ret; } } // namespace cura <commit_msg>Apply LimitedBeadingStrategy last<commit_after>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategyFactory.h" #include "InwardDistributedBeadingStrategy.h" #include "LimitedBeadingStrategy.h" #include "CenterDeviationBeadingStrategy.h" #include "WideningBeadingStrategy.h" #include "DistributedBeadingStrategy.h" #include "RedistributeBeadingStrategy.h" namespace cura { double inward_distributed_center_size = 2; StrategyType toStrategyType(char c) { switch (c) { case 'r': return StrategyType::Center; case 'd': return StrategyType::Distributed; case 'i': return StrategyType::InwardDistributed; } return StrategyType::COUNT; } std::string to_string(StrategyType type) { switch (type) { case StrategyType::Center: return "CenterDeviation"; case StrategyType::Distributed: return "Distributed"; case StrategyType::InwardDistributed: return "InwardDistributed"; default: return "unknown_strategy"; } } coord_t get_weighted_average(const coord_t preferred_bead_width_outer, const coord_t preferred_bead_width_inner, const coord_t max_bead_count) { if (max_bead_count > 2) { return ((preferred_bead_width_outer * 2) + preferred_bead_width_inner * (max_bead_count - 2)) / max_bead_count; } if (max_bead_count <= 0) { return preferred_bead_width_inner; } return preferred_bead_width_outer; } BeadingStrategy* BeadingStrategyFactory::makeStrategy(const StrategyType type, const coord_t preferred_bead_width_outer, const coord_t preferred_bead_width_inner, const coord_t preferred_transition_length, const float transitioning_angle, const bool print_thin_walls, const coord_t min_bead_width, const coord_t min_feature_size, const coord_t max_bead_count) { const coord_t bar_preferred_wall_width = get_weighted_average(preferred_bead_width_outer, preferred_bead_width_inner, max_bead_count); BeadingStrategy* ret = nullptr; switch (type) { case StrategyType::Center: ret = new CenterDeviationBeadingStrategy(bar_preferred_wall_width, transitioning_angle); break; case StrategyType::Distributed: ret = new DistributedBeadingStrategy(bar_preferred_wall_width, preferred_transition_length, transitioning_angle); break; case StrategyType::InwardDistributed: ret = new InwardDistributedBeadingStrategy(bar_preferred_wall_width, preferred_transition_length, transitioning_angle, inward_distributed_center_size); break; default: logError("Cannot make strategy!\n"); return nullptr; } if(print_thin_walls) { logDebug("Applying the Widening Beading meta-strategy with minimum input width %d and minimum output width %d.", min_feature_size, min_bead_width); ret = new WideningBeadingStrategy(ret, min_feature_size, min_bead_width); } if (max_bead_count > 0) { logDebug("Applying the Redistribute meta-strategy with outer-wall width = %d, inner-wall width = %d", preferred_bead_width_outer, preferred_bead_width_inner); ret = new RedistributeBeadingStrategy(preferred_bead_width_outer, preferred_bead_width_inner, ret); //Apply the LimitedBeadingStrategy last, since that adds a 0-width marker wall which other beading strategies shouldn't touch. logDebug("Applying the Limited Beading meta-strategy with maximum bead count = %d.", max_bead_count); ret = new LimitedBeadingStrategy(max_bead_count, ret); } return ret; } } // namespace cura <|endoftext|>
<commit_before>#include <gnuplot-iostream/gnuplot-iostream.h> #include <boost/tuple/tuple.hpp> #include <iostream> #include <iomanip> #include <ctime> #include "Tools.hpp" #include "Magnet.hpp" using namespace std; const int lattice = inputInt(100,"lattice size"); const double defaultJ = 1; const double firstTemp = inputDouble(1,"ambient temperature");; const double defaultKb = 1; const double tStep = 0.01; const int MAX_ITERS = inputInt(500,"maximum iterations"); void plotSpinMatrix(Magnet* m){ Gnuplot gp; gp << setprecision(3); gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set title \"Spins of a Randomized Ising Model After " << MAX_ITERS; gp << " iterations of the Metropolis Algorithm\\nwith Ambient Temperature " << firstTemp; gp << ", k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set output \"mag.png\"\n"; gp << "set palette grey\n"; gp << "set pm3d map\n"; gp << "unset key\n"; gp << "unset colorbox\n"; gp << "splot '-' matrix with image\n"; gp.send1d(m->getAllSpins()); } void plotEnergy(vector<double>& eng, vector<double>& t){ Gnuplot gp; gp << setprecision(3); gp << "set xrange [1:5]\n"; gp << "set yrange [-2:0]\n"; gp << "set title \"Energy per Spin vs. Temperature in the Ising Model\\n"; gp << "with k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set xlabel \"Temperature (inv. Boltzmann Constants)\"\n"; gp << "set ylabel \"Energy per Spin (E_{/Symbol a} / N)\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set output \"energy.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(t,eng)); } void plotDeriv(vector<double>& eng, vector<double>& t){ Gnuplot gp; gp << setprecision(3); gp << "set xrange [1:5]\n"; gp << "set yrange [0:2]\n"; gp << "set title \"Heat Density vs. Temperature in the Ising Model\\n"; gp << "with k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set xlabel \"Temperature (inv. Boltzmann Constants)\"\n"; gp << "set ylabel \"Energy per Spin (E_{/Symbol a} / N)\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set output \"Denergy.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(t,eng)); } int main(){ srand(time(NULL)); Magnet* mag = new Magnet(lattice, firstTemp, defaultKb, defaultJ); vector<double> time; vector<double> energy; vector<double> magnetism; mag->simulate(MAX_ITERS); plotSpinMatrix(mag); mag->randomize(); for(double t = 0.1; t < 5; t+= tStep){ mag->setTemp(t); mag->simulate(MAX_ITERS); energy.push_back(mag->getEnergy()); time.push_back(t); mag->randomize(); } vector<double> rolling = rollingAverage(energy,0.2/tStep); vector<double> deriv = derivate(time,rolling); vector<double> rollingderiv = rollingAverage(deriv,0.2/tStep); plotEnergy(rolling,time); plotDeriv(rollingderiv,time); delete mag; return 0; }<commit_msg>bigrun<commit_after>#include <gnuplot-iostream/gnuplot-iostream.h> #include <boost/tuple/tuple.hpp> #include <iostream> #include <iomanip> #include <ctime> #include "Tools.hpp" #include "Magnet.hpp" using namespace std; const int lattice = inputInt(100,"lattice size"); const double defaultJ = 1; const double firstTemp = inputDouble(1,"ambient temperature");; const double defaultKb = 1; const double tStep = 0.001; const int MAX_ITERS = inputInt(200,"maximum iterations"); void plotSpinMatrix(Magnet* m){ Gnuplot gp; gp << setprecision(3); gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set title \"Spins of a Randomized Ising Model After " << MAX_ITERS; gp << " iterations of the Metropolis Algorithm\\nwith Ambient Temperature " << firstTemp; gp << ", k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set output \"mag.png\"\n"; gp << "set palette grey\n"; gp << "set pm3d map\n"; gp << "unset key\n"; gp << "unset colorbox\n"; gp << "splot '-' matrix with image\n"; gp.send1d(m->getAllSpins()); } void plotEnergy(vector<double>& eng, vector<double>& t){ Gnuplot gp; gp << setprecision(3); gp << "set xrange [1:4]\n"; gp << "set yrange [-2:0]\n"; gp << "set title \"Energy per Spin vs. Temperature in the Ising Model\\n"; gp << "with k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set xlabel \"Temperature (inv. Boltzmann Constants)\"\n"; gp << "set ylabel \"Energy per Spin (E_{/Symbol a} / N)\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set output \"energy.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(t,eng)); } void plotDeriv(vector<double>& eng, vector<double>& t){ Gnuplot gp; gp << setprecision(3); gp << "set xrange [1:4]\n"; gp << "set yrange [0:1.5]\n"; gp << "set title \"Heat Density vs. Temperature in the Ising Model\\n"; gp << "with k_b = " << defaultKb << ", J = " << defaultJ << "\"\n"; gp << "set xlabel \"Temperature (inv. Boltzmann Constants)\"\n"; gp << "set ylabel \"Energy per Spin (E_{/Symbol a} / N)\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set output \"Denergy.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(t,eng)); } int main(){ srand(time(NULL)); Magnet* mag = new Magnet(lattice, firstTemp, defaultKb, defaultJ); vector<double> time; vector<double> energy; vector<double> magnetism; mag->simulate(MAX_ITERS); plotSpinMatrix(mag); mag->randomize(); for(double t = 0.8; t < 4; t+= tStep){ mag->setTemp(t); mag->simulate(MAX_ITERS); energy.push_back(mag->getEnergy()); time.push_back(t); mag->randomize(); cout << "Finished " << t << endl; } vector<double> rolling = rollingAverage(energy,0.2/tStep); vector<double> deriv = derivate(time,rolling); vector<double> rollingderiv = rollingAverage(deriv,0.2/tStep); plotEnergy(rolling,time); plotDeriv(rollingderiv,time); delete mag; return 0; }<|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. #ifndef __CREDENTIALS_HPP__ #define __CREDENTIALS_HPP__ #include <string> #include <vector> #include <stout/option.hpp> #include <stout/path.hpp> #include <stout/protobuf.hpp> #include <stout/try.hpp> #include <stout/os/permissions.hpp> #include <stout/os/read.hpp> namespace mesos { namespace internal { namespace credentials { inline Result<Credentials> read(const Path& path) { LOG(INFO) << "Loading credentials for authentication from '" << path << "'"; Try<std::string> read = os::read(path.string()); if (read.isError()) { return Error("Failed to read credentials file '" + path.string() + "': " + read.error()); } else if (read.get().empty()) { return None(); } Try<os::Permissions> permissions = os::permissions(path.string()); if (permissions.isError()) { LOG(WARNING) << "Failed to stat credentials file '" << path << "': " << permissions.error(); } else if (permissions.get().others.rwx) { LOG(WARNING) << "Permissions on credentials file '" << path << "' are too open. It is recommended that your " << "credentials file is NOT accessible by others."; } // TODO(nfnt): Remove text format support at the end of the deprecation cycle // which started with version 1.0. Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get()); if (!json.isError()) { Try<Credentials> credentials = ::protobuf::parse<Credentials>(json.get()); if (!credentials.isError()) { return credentials.get(); } } Credentials credentials; foreach (const std::string& line, strings::tokenize(read.get(), "\n")) { const std::vector<std::string>& pairs = strings::tokenize(line, " "); if (pairs.size() != 2) { return Error("Invalid credential format at line " + stringify(credentials.credentials().size() + 1)); } // Add the credential. Credential* credential = credentials.add_credentials(); credential->set_principal(pairs[0]); credential->set_secret(pairs[1]); } return credentials; } inline Result<Credential> readCredential(const Path& path) { LOG(INFO) << "Loading credential for authentication from '" << path << "'"; Try<std::string> read = os::read(path.string()); if (read.isError()) { return Error("Failed to read credential file '" + path.string() + "': " + read.error()); } else if (read.get().empty()) { return None(); } Try<os::Permissions> permissions = os::permissions(path.string()); if (permissions.isError()) { LOG(WARNING) << "Failed to stat credential file '" << path << "': " << permissions.error(); } else if (permissions.get().others.rwx) { LOG(WARNING) << "Permissions on credential file '" << path << "' are too open. It is recommended that your " << "credential file is NOT accessible by others."; } Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get()); if (!json.isError()) { Try<Credential> credential = ::protobuf::parse<Credential>(json.get()); if (!credential.isError()) { return credential.get(); } } // TODO(nfnt): Remove text format support at the end of the deprecation cycle // which started with version 1.0. Credential credential; const std::vector<std::string>& line = strings::tokenize(read.get(), "\n"); if (line.size() != 1) { return Error("Expecting only one credential"); } const std::vector<std::string>& pairs = strings::tokenize(line[0], " "); if (pairs.size() != 2) { return Error("Invalid credential format"); } // Add the credential. credential.set_principal(pairs[0]); credential.set_secret(pairs[1]); return credential; } } // namespace credentials { } // namespace internal { } // namespace mesos { #endif // __CREDENTIALS_HPP__ <commit_msg>Removed a period at the end of the log entry in credentials.hpp.<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. #ifndef __CREDENTIALS_HPP__ #define __CREDENTIALS_HPP__ #include <string> #include <vector> #include <stout/option.hpp> #include <stout/path.hpp> #include <stout/protobuf.hpp> #include <stout/try.hpp> #include <stout/os/permissions.hpp> #include <stout/os/read.hpp> namespace mesos { namespace internal { namespace credentials { inline Result<Credentials> read(const Path& path) { LOG(INFO) << "Loading credentials for authentication from '" << path << "'"; Try<std::string> read = os::read(path.string()); if (read.isError()) { return Error("Failed to read credentials file '" + path.string() + "': " + read.error()); } else if (read.get().empty()) { return None(); } Try<os::Permissions> permissions = os::permissions(path.string()); if (permissions.isError()) { LOG(WARNING) << "Failed to stat credentials file '" << path << "': " << permissions.error(); } else if (permissions.get().others.rwx) { LOG(WARNING) << "Permissions on credentials file '" << path << "' are too open; it is recommended that your" << " credentials file is NOT accessible by others"; } // TODO(nfnt): Remove text format support at the end of the deprecation cycle // which started with version 1.0. Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get()); if (!json.isError()) { Try<Credentials> credentials = ::protobuf::parse<Credentials>(json.get()); if (!credentials.isError()) { return credentials.get(); } } Credentials credentials; foreach (const std::string& line, strings::tokenize(read.get(), "\n")) { const std::vector<std::string>& pairs = strings::tokenize(line, " "); if (pairs.size() != 2) { return Error("Invalid credential format at line " + stringify(credentials.credentials().size() + 1)); } // Add the credential. Credential* credential = credentials.add_credentials(); credential->set_principal(pairs[0]); credential->set_secret(pairs[1]); } return credentials; } inline Result<Credential> readCredential(const Path& path) { LOG(INFO) << "Loading credential for authentication from '" << path << "'"; Try<std::string> read = os::read(path.string()); if (read.isError()) { return Error("Failed to read credential file '" + path.string() + "': " + read.error()); } else if (read.get().empty()) { return None(); } Try<os::Permissions> permissions = os::permissions(path.string()); if (permissions.isError()) { LOG(WARNING) << "Failed to stat credential file '" << path << "': " << permissions.error(); } else if (permissions.get().others.rwx) { LOG(WARNING) << "Permissions on credential file '" << path << "' are too open; it is recommended that your" << " credential file is NOT accessible by others"; } Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get()); if (!json.isError()) { Try<Credential> credential = ::protobuf::parse<Credential>(json.get()); if (!credential.isError()) { return credential.get(); } } // TODO(nfnt): Remove text format support at the end of the deprecation cycle // which started with version 1.0. Credential credential; const std::vector<std::string>& line = strings::tokenize(read.get(), "\n"); if (line.size() != 1) { return Error("Expecting only one credential"); } const std::vector<std::string>& pairs = strings::tokenize(line[0], " "); if (pairs.size() != 2) { return Error("Invalid credential format"); } // Add the credential. credential.set_principal(pairs[0]); credential.set_secret(pairs[1]); return credential; } } // namespace credentials { } // namespace internal { } // namespace mesos { #endif // __CREDENTIALS_HPP__ <|endoftext|>
<commit_before>/* This file is part of Ingen. Copyright 2007-2017 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <stdlib.h> #include <iostream> #include <string> #include <glibmm/thread.h> #include <glibmm/timer.h> #include "raul/Path.hpp" #include "ingen_config.h" #include "ingen/Configuration.hpp" #include "ingen/EngineBase.hpp" #include "ingen/Interface.hpp" #include "ingen/Log.hpp" #include "ingen/Parser.hpp" #include "ingen/World.hpp" #include "ingen/client/ThreadedSigClientInterface.hpp" #include "ingen/runtime_paths.hpp" #include "ingen/types.hpp" #ifdef HAVE_SOCKET #include "ingen/client/SocketClient.hpp" #endif using namespace std; using namespace Ingen; Ingen::World* world = NULL; static void ingen_interrupt(int signal) { if (signal == SIGTERM) { cerr << "ingen: Terminated" << endl; delete world; exit(EXIT_FAILURE); } else { cout << "ingen: Interrupted" << endl; if (world && world->engine()) { world->engine()->quit(); } } } static void ingen_try(bool cond, const char* msg) { if (!cond) { cerr << "ingen: error: " << msg << endl; delete world; exit(EXIT_FAILURE); } } static int print_version() { cout << "ingen " << INGEN_VERSION << " <http://drobilla.net/software/ingen>\n" << "Copyright 2007-2017 David Robillard <http://drobilla.net>.\n" << "License: <https://www.gnu.org/licenses/agpl-3.0>\n" << "This is free software; you are free to change and redistribute it.\n" << "There is NO WARRANTY, to the extent permitted by law." << endl; return EXIT_SUCCESS; } int main(int argc, char** argv) { Glib::thread_init(); Ingen::set_bundle_path_from_code((void*)&print_version); // Create world try { world = new Ingen::World(NULL, NULL, NULL); world->load_configuration(argc, argv); if (argc <= 1) { world->conf().print_usage("ingen", cout); return EXIT_FAILURE; } else if (world->conf().option("help").get<int32_t>()) { world->conf().print_usage("ingen", cout); return EXIT_SUCCESS; } else if (world->conf().option("version").get<int32_t>()) { return print_version(); } } catch (std::exception& e) { cout << "ingen: error: " << e.what() << endl; return EXIT_FAILURE; } Configuration& conf = world->conf(); if (conf.option("uuid").is_valid()) { world->set_jack_uuid(conf.option("uuid").ptr<char>()); } // Run engine SPtr<Interface> engine_interface; if (conf.option("engine").get<int32_t>()) { ingen_try(world->load_module("server"), "Failed to load server module"); ingen_try(bool(world->engine()), "Unable to create engine"); world->engine()->listen(); engine_interface = world->interface(); } // If we don't have a local engine interface (for GUI), use network if (!engine_interface) { ingen_try(world->load_module("client"), "Failed to load client module"); #ifdef HAVE_SOCKET Client::SocketClient::register_factories(world); #endif const char* const uri = conf.option("connect").ptr<char>(); ingen_try(Raul::URI::is_valid(uri), (fmt("Invalid URI <%1%>") % uri).str().c_str()); SPtr<Interface> client(new Client::ThreadedSigClientInterface(1024)); engine_interface = world->new_interface(Raul::URI(uri), client); if (!engine_interface && !conf.option("gui").get<int32_t>()) { cerr << (fmt("ingen: error: Failed to connect to `%1%'\n") % uri); delete world; return EXIT_FAILURE; } } world->set_interface(engine_interface); // Load GUI if requested if (conf.option("gui").get<int32_t>()) { ingen_try(world->load_module("gui"), "Failed to load GUI module"); } // Activate the engine, if we have one if (world->engine()) { if (!world->load_module("jack") && !world->load_module("portaudio")) { cerr << "ingen: error: Failed to load driver module" << endl; delete world; exit(EXIT_FAILURE); } } // Load a graph if (conf.option("load").is_valid()) { boost::optional<Raul::Path> parent; boost::optional<Raul::Symbol> symbol; const Atom& path_option = conf.option("path"); if (path_option.is_valid()) { if (Raul::Path::is_valid(path_option.ptr<char>())) { const Raul::Path p(path_option.ptr<char>()); if (!p.is_root()) { parent = p.parent(); symbol = Raul::Symbol(p.symbol()); } } else { cerr << "Invalid path given: '" << path_option.ptr<char>() << endl; } } ingen_try(bool(world->parser()), "Failed to create parser"); const string graph = conf.option("load").ptr<char>(); engine_interface->get(Raul::URI("ingen:/plugins")); engine_interface->get(main_uri()); std::lock_guard<std::mutex> lock(world->rdf_mutex()); world->parser()->parse_file( world, engine_interface.get(), graph, parent, symbol); } else if (conf.option("server-load").is_valid()) { const char* path = conf.option("server-load").ptr<char>(); if (serd_uri_string_has_scheme((const uint8_t*)path)) { std::cout << "Loading " << path << " (server side)" << std::endl; engine_interface->copy(Raul::URI(path), main_uri()); } else { SerdNode uri = serd_node_new_file_uri( (const uint8_t*)path, NULL, NULL, true); std::cout << "Loading " << (const char*)uri.buf << " (server side)" << std::endl; engine_interface->copy(Raul::URI((const char*)uri.buf), main_uri()); serd_node_free(&uri); } } // Save the currently loaded graph if (conf.option("save").is_valid()) { const char* path = conf.option("save").ptr<char>(); if (serd_uri_string_has_scheme((const uint8_t*)path)) { std::cout << "Saving to " << path << std::endl; engine_interface->copy(main_uri(), Raul::URI(path)); } else { SerdNode uri = serd_node_new_file_uri( (const uint8_t*)path, NULL, NULL, true); std::cout << "Saving to " << (const char*)uri.buf << std::endl; engine_interface->copy(main_uri(), Raul::URI((const char*)uri.buf)); serd_node_free(&uri); } } // Activate the engine now that the graph is loaded if (world->engine()) { world->engine()->flush_events(std::chrono::milliseconds(10)); world->engine()->activate(); } // Set up signal handlers that will set quit_flag on interrupt signal(SIGINT, ingen_interrupt); signal(SIGTERM, ingen_interrupt); if (conf.option("gui").get<int32_t>()) { world->run_module("gui"); } else if (world->engine()) { // Run engine main loop until interrupt while (world->engine()->main_iteration()) { Glib::usleep(125000); // 1/8 second } } // Sleep for a half second to allow event queues to drain Glib::usleep(500000); // Shut down if (world->engine()) world->engine()->deactivate(); // Save configuration to restore preferences on next run const std::string path = conf.save( world->uri_map(), "ingen", "options.ttl", Configuration::GLOBAL); std::cout << (fmt("Saved configuration to %1%") % path) << std::endl; engine_interface.reset(); delete world; return 0; } <commit_msg>Ensure thread count is sane<commit_after>/* This file is part of Ingen. Copyright 2007-2017 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <stdlib.h> #include <iostream> #include <string> #include <glibmm/thread.h> #include <glibmm/timer.h> #include "raul/Path.hpp" #include "ingen_config.h" #include "ingen/Configuration.hpp" #include "ingen/EngineBase.hpp" #include "ingen/Interface.hpp" #include "ingen/Log.hpp" #include "ingen/Parser.hpp" #include "ingen/World.hpp" #include "ingen/client/ThreadedSigClientInterface.hpp" #include "ingen/runtime_paths.hpp" #include "ingen/types.hpp" #ifdef HAVE_SOCKET #include "ingen/client/SocketClient.hpp" #endif using namespace std; using namespace Ingen; Ingen::World* world = NULL; static void ingen_interrupt(int signal) { if (signal == SIGTERM) { cerr << "ingen: Terminated" << endl; delete world; exit(EXIT_FAILURE); } else { cout << "ingen: Interrupted" << endl; if (world && world->engine()) { world->engine()->quit(); } } } static void ingen_try(bool cond, const char* msg) { if (!cond) { cerr << "ingen: error: " << msg << endl; delete world; exit(EXIT_FAILURE); } } static int print_version() { cout << "ingen " << INGEN_VERSION << " <http://drobilla.net/software/ingen>\n" << "Copyright 2007-2017 David Robillard <http://drobilla.net>.\n" << "License: <https://www.gnu.org/licenses/agpl-3.0>\n" << "This is free software; you are free to change and redistribute it.\n" << "There is NO WARRANTY, to the extent permitted by law." << endl; return EXIT_SUCCESS; } int main(int argc, char** argv) { Glib::thread_init(); Ingen::set_bundle_path_from_code((void*)&print_version); // Create world try { world = new Ingen::World(NULL, NULL, NULL); world->load_configuration(argc, argv); if (argc <= 1) { world->conf().print_usage("ingen", cout); return EXIT_FAILURE; } else if (world->conf().option("help").get<int32_t>()) { world->conf().print_usage("ingen", cout); return EXIT_SUCCESS; } else if (world->conf().option("version").get<int32_t>()) { return print_version(); } } catch (std::exception& e) { cout << "ingen: error: " << e.what() << endl; return EXIT_FAILURE; } Configuration& conf = world->conf(); if (conf.option("uuid").is_valid()) { world->set_jack_uuid(conf.option("uuid").ptr<char>()); } // Run engine SPtr<Interface> engine_interface; if (conf.option("engine").get<int32_t>()) { if (world->conf().option("threads").get<int32_t>() < 1) { cerr << "ingen: error: threads must be > 0" << endl; return EXIT_FAILURE; } ingen_try(world->load_module("server"), "Failed to load server module"); ingen_try(bool(world->engine()), "Unable to create engine"); world->engine()->listen(); engine_interface = world->interface(); } // If we don't have a local engine interface (for GUI), use network if (!engine_interface) { ingen_try(world->load_module("client"), "Failed to load client module"); #ifdef HAVE_SOCKET Client::SocketClient::register_factories(world); #endif const char* const uri = conf.option("connect").ptr<char>(); ingen_try(Raul::URI::is_valid(uri), (fmt("Invalid URI <%1%>") % uri).str().c_str()); SPtr<Interface> client(new Client::ThreadedSigClientInterface(1024)); engine_interface = world->new_interface(Raul::URI(uri), client); if (!engine_interface && !conf.option("gui").get<int32_t>()) { cerr << (fmt("ingen: error: Failed to connect to `%1%'\n") % uri); delete world; return EXIT_FAILURE; } } world->set_interface(engine_interface); // Load GUI if requested if (conf.option("gui").get<int32_t>()) { ingen_try(world->load_module("gui"), "Failed to load GUI module"); } // Activate the engine, if we have one if (world->engine()) { if (!world->load_module("jack") && !world->load_module("portaudio")) { cerr << "ingen: error: Failed to load driver module" << endl; delete world; exit(EXIT_FAILURE); } } // Load a graph if (conf.option("load").is_valid()) { boost::optional<Raul::Path> parent; boost::optional<Raul::Symbol> symbol; const Atom& path_option = conf.option("path"); if (path_option.is_valid()) { if (Raul::Path::is_valid(path_option.ptr<char>())) { const Raul::Path p(path_option.ptr<char>()); if (!p.is_root()) { parent = p.parent(); symbol = Raul::Symbol(p.symbol()); } } else { cerr << "Invalid path given: '" << path_option.ptr<char>() << endl; } } ingen_try(bool(world->parser()), "Failed to create parser"); const string graph = conf.option("load").ptr<char>(); engine_interface->get(Raul::URI("ingen:/plugins")); engine_interface->get(main_uri()); std::lock_guard<std::mutex> lock(world->rdf_mutex()); world->parser()->parse_file( world, engine_interface.get(), graph, parent, symbol); } else if (conf.option("server-load").is_valid()) { const char* path = conf.option("server-load").ptr<char>(); if (serd_uri_string_has_scheme((const uint8_t*)path)) { std::cout << "Loading " << path << " (server side)" << std::endl; engine_interface->copy(Raul::URI(path), main_uri()); } else { SerdNode uri = serd_node_new_file_uri( (const uint8_t*)path, NULL, NULL, true); std::cout << "Loading " << (const char*)uri.buf << " (server side)" << std::endl; engine_interface->copy(Raul::URI((const char*)uri.buf), main_uri()); serd_node_free(&uri); } } // Save the currently loaded graph if (conf.option("save").is_valid()) { const char* path = conf.option("save").ptr<char>(); if (serd_uri_string_has_scheme((const uint8_t*)path)) { std::cout << "Saving to " << path << std::endl; engine_interface->copy(main_uri(), Raul::URI(path)); } else { SerdNode uri = serd_node_new_file_uri( (const uint8_t*)path, NULL, NULL, true); std::cout << "Saving to " << (const char*)uri.buf << std::endl; engine_interface->copy(main_uri(), Raul::URI((const char*)uri.buf)); serd_node_free(&uri); } } // Activate the engine now that the graph is loaded if (world->engine()) { world->engine()->flush_events(std::chrono::milliseconds(10)); world->engine()->activate(); } // Set up signal handlers that will set quit_flag on interrupt signal(SIGINT, ingen_interrupt); signal(SIGTERM, ingen_interrupt); if (conf.option("gui").get<int32_t>()) { world->run_module("gui"); } else if (world->engine()) { // Run engine main loop until interrupt while (world->engine()->main_iteration()) { Glib::usleep(125000); // 1/8 second } } // Sleep for a half second to allow event queues to drain Glib::usleep(500000); // Shut down if (world->engine()) world->engine()->deactivate(); // Save configuration to restore preferences on next run const std::string path = conf.save( world->uri_map(), "ingen", "options.ttl", Configuration::GLOBAL); std::cout << (fmt("Saved configuration to %1%") % path) << std::endl; engine_interface.reset(); delete world; return 0; } <|endoftext|>
<commit_before>#include "iotsa.h" #include "iotsaConfigFile.h" #ifdef ESP32 #include <SPIFFS.h> #include <esp_log.h> #include <rom/rtc.h> #endif #include <FS.h> // // Global variable initialization // IotsaConfig iotsaConfig; #ifdef IOTSA_WITH_HTTPS #include "iotsaConfigDefaultCert512.h" #endif void IotsaConfig::loop() { if (rebootAtMillis && millis() > rebootAtMillis) { IFDEBUG IotsaSerial.println("Software requested reboot."); ESP.restart(); } } void IotsaConfig::setDefaultHostName() { hostName = "iotsa"; #ifdef ESP32 hostName += String(uint32_t(ESP.getEfuseMac()), HEX); #else hostName += String(ESP.getChipId(), HEX); #endif } void IotsaConfig::setDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS httpsCertificate = defaultHttpsCertificate; httpsCertificateLength = sizeof(defaultHttpsCertificate); httpsKey = defaultHttpsKey; httpsKeyLength = sizeof(defaultHttpsKey); IFDEBUG IotsaSerial.print("Default https key len="); IFDEBUG IotsaSerial.print(httpsKeyLength); IFDEBUG IotsaSerial.print(", cert len="); IFDEBUG IotsaSerial.println(httpsCertificateLength); #endif // IOTSA_WITH_HTTPS } bool IotsaConfig::usingDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS return httpsKey == defaultHttpsKey; #else return false; #endif } const char* IotsaConfig::getBootReason() { static const char *reason = NULL; if (reason == NULL) { reason = "unknown"; #ifndef ESP32 rst_info *rip = ESP.getResetInfoPtr(); static const char *reasons[] = { "power", "hardwareWatchdog", "exception", "softwareWatchdog", "softwareReboot", "deepSleepAwake", "externalReset" }; if (rip->reason < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)rip->reason]; } #else RESET_REASON r = rtc_get_reset_reason(0); RESET_REASON r2 = rtc_get_reset_reason(1); // Determine best reset reason if (r == TG0WDT_SYS_RESET || r == RTCWDT_RTC_RESET) r = r2; static const char *reasons[] = { "0", "power", "2", "softwareReboot", "legacyWatchdog", "deepSleepAwake", "sdio", "tg0Watchdog", "tg1Watchdog", "rtcWatchdog", "intrusion", "tgWatchdogCpu", "softwareRebootCpu", "rtcWatchdogCpu", "externalReset", "brownout", "rtcWatchdogRtc" }; if ((int)r < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)r]; } #endif } return reason; } const char *IotsaConfig::modeName(config_mode mode) { #ifdef IOTSA_WITH_WEB if (mode == IOTSA_MODE_NORMAL) return "normal"; if (mode == IOTSA_MODE_CONFIG) return "configuration"; if (mode == IOTSA_MODE_OTA) return "OTA"; if (mode == IOTSA_MODE_FACTORY_RESET) return "factory-reset"; #endif // IOTSA_WITH_WEB return "unknown"; } bool IotsaConfig::inConfigurationMode(bool extend) { bool ok = configurationMode == IOTSA_MODE_CONFIG; if (ok && extend) extendConfigurationMode(); return ok; } bool IotsaConfig::inConfigurationOrFactoryMode() { if (configurationMode == IOTSA_MODE_CONFIG) return true; if (wifiMode == IOTSA_WIFI_FACTORY) return true; return false; } void IotsaConfig::extendConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode extended"); configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; } void IotsaConfig::endConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode ended"); configurationMode = IOTSA_MODE_NORMAL; configurationModeEndTime = 0; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; configSave(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::beginConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode entered"); configurationMode = IOTSA_MODE_CONFIG; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // No need to tell wifi (or save config): this call is done only by the // WiFi module when switching from factory mode to having a WiFi. } void IotsaConfig::factoryReset() { IFDEBUG IotsaSerial.println("configurationMode: Factory-reset"); delay(1000); IFDEBUG IotsaSerial.println("Formatting SPIFFS..."); SPIFFS.format(); IFDEBUG IotsaSerial.println("Format done, rebooting."); delay(2000); ESP.restart(); } void IotsaConfig::allowRequestedConfigurationMode() { if (nextConfigurationMode == configurationMode) return; IFDEBUG IotsaSerial.print("Switching configurationMode to "); IFDEBUG IotsaSerial.println(nextConfigurationMode); configurationMode = nextConfigurationMode; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; if (configurationMode == IOTSA_MODE_FACTORY_RESET) factoryReset(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::allowRCMDescription(const char *_rcmInteractionDescription) { rcmInteractionDescription = _rcmInteractionDescription; } uint32_t IotsaConfig::getStatusColor() { if (configurationMode == IOTSA_MODE_FACTORY_RESET) return 0x3f0000; // Red: Factory reset mode uint32_t extraColor = 0; switch(wifiMode) { case IOTSA_WIFI_DISABLED: return 0; case IOTSA_WIFI_SEARCHING: return 0x3f1f00; // Orange: searching for WiFi case IOTSA_WIFI_FACTORY: case IOTSA_WIFI_NOTFOUND: extraColor = 0x1f1f1f; // Add a bit of white to the configuration mode color // Pass through default: // Pass through ; } if (configurationMode == IOTSA_MODE_CONFIG) return extraColor | 0x3f003f; // Magenta: user-requested configuration mode if (configurationMode == IOTSA_MODE_OTA) return extraColor | 0x003f3f; // Cyan: OTA mode return extraColor; // Off: all ok, whiteish: factory reset network } void IotsaConfig::pauseSleep() { pauseSleepCount++; } void IotsaConfig::resumeSleep() { pauseSleepCount--; } void IotsaConfig::postponeSleep(uint32_t ms) { uint32_t noSleepBefore = millis() + ms; if (noSleepBefore > postponeSleepMillis) postponeSleepMillis = noSleepBefore; } bool IotsaConfig::canSleep() { if (pauseSleepCount > 0) return false; if (millis() > postponeSleepMillis) postponeSleepMillis = 0; return postponeSleepMillis == 0; } void IotsaConfig::configLoad() { IotsaConfigFileLoad cf("/config/config.cfg"); iotsaConfig.configWasLoaded = true; int tcm; cf.get("mode", tcm, IOTSA_MODE_NORMAL); iotsaConfig.configurationMode = (config_mode)tcm; cf.get("hostName", iotsaConfig.hostName, ""); if (iotsaConfig.hostName == "") iotsaConfig.setDefaultHostName(); cf.get("rebootTimeout", iotsaConfig.configurationModeTimeout, CONFIGURATION_MODE_TIMEOUT); #ifdef IOTSA_WITH_HTTPS if (iotsaConfigFileExists("/config/httpsKey.der") && iotsaConfigFileExists("/config/httpsCert.der")) { bool ok = iotsaConfigFileLoadBinary("/config/httpsKey.der", (uint8_t **)&iotsaConfig.httpsKey, &iotsaConfig.httpsKeyLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsKey.der"); } ok = iotsaConfigFileLoadBinary("/config/httpsCert.der", (uint8_t **)&iotsaConfig.httpsCertificate, &iotsaConfig.httpsCertificateLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsCert.der"); } } #endif // IOTSA_WITH_HTTPS } void IotsaConfig::configSave() { IotsaConfigFileSave cf("/config/config.cfg"); cf.put("mode", nextConfigurationMode); // Note: nextConfigurationMode, which will be read as configurationMode cf.put("hostName", hostName); cf.put("rebootTimeout", configurationModeTimeout); // Key/cert are saved in iotsaConfigMod IFDEBUG IotsaSerial.println("Saved config.cfg"); } void IotsaConfig::ensureConfigLoaded() { if (!configWasLoaded) configLoad(); }; void IotsaConfig::requestReboot(uint32_t ms) { IFDEBUG IotsaSerial.println("Restart requested"); rebootAtMillis = millis() + ms; } void IotsaConfig::printHeapSpace() { size_t memAvail = heap_caps_get_free_size(MALLOC_CAP_8BIT); size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); IFDEBUG IotsaSerial.printf("Available heap space: %u bytes, largest block: %u bytes\n", memAvail, largestBlock); }<commit_msg>On esp8266 printHeapSpace() is a no-op.<commit_after>#include "iotsa.h" #include "iotsaConfigFile.h" #ifdef ESP32 #include <SPIFFS.h> #include <esp_log.h> #include <rom/rtc.h> #endif #include <FS.h> // // Global variable initialization // IotsaConfig iotsaConfig; #ifdef IOTSA_WITH_HTTPS #include "iotsaConfigDefaultCert512.h" #endif void IotsaConfig::loop() { if (rebootAtMillis && millis() > rebootAtMillis) { IFDEBUG IotsaSerial.println("Software requested reboot."); ESP.restart(); } } void IotsaConfig::setDefaultHostName() { hostName = "iotsa"; #ifdef ESP32 hostName += String(uint32_t(ESP.getEfuseMac()), HEX); #else hostName += String(ESP.getChipId(), HEX); #endif } void IotsaConfig::setDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS httpsCertificate = defaultHttpsCertificate; httpsCertificateLength = sizeof(defaultHttpsCertificate); httpsKey = defaultHttpsKey; httpsKeyLength = sizeof(defaultHttpsKey); IFDEBUG IotsaSerial.print("Default https key len="); IFDEBUG IotsaSerial.print(httpsKeyLength); IFDEBUG IotsaSerial.print(", cert len="); IFDEBUG IotsaSerial.println(httpsCertificateLength); #endif // IOTSA_WITH_HTTPS } bool IotsaConfig::usingDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS return httpsKey == defaultHttpsKey; #else return false; #endif } const char* IotsaConfig::getBootReason() { static const char *reason = NULL; if (reason == NULL) { reason = "unknown"; #ifndef ESP32 rst_info *rip = ESP.getResetInfoPtr(); static const char *reasons[] = { "power", "hardwareWatchdog", "exception", "softwareWatchdog", "softwareReboot", "deepSleepAwake", "externalReset" }; if (rip->reason < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)rip->reason]; } #else RESET_REASON r = rtc_get_reset_reason(0); RESET_REASON r2 = rtc_get_reset_reason(1); // Determine best reset reason if (r == TG0WDT_SYS_RESET || r == RTCWDT_RTC_RESET) r = r2; static const char *reasons[] = { "0", "power", "2", "softwareReboot", "legacyWatchdog", "deepSleepAwake", "sdio", "tg0Watchdog", "tg1Watchdog", "rtcWatchdog", "intrusion", "tgWatchdogCpu", "softwareRebootCpu", "rtcWatchdogCpu", "externalReset", "brownout", "rtcWatchdogRtc" }; if ((int)r < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)r]; } #endif } return reason; } const char *IotsaConfig::modeName(config_mode mode) { #ifdef IOTSA_WITH_WEB if (mode == IOTSA_MODE_NORMAL) return "normal"; if (mode == IOTSA_MODE_CONFIG) return "configuration"; if (mode == IOTSA_MODE_OTA) return "OTA"; if (mode == IOTSA_MODE_FACTORY_RESET) return "factory-reset"; #endif // IOTSA_WITH_WEB return "unknown"; } bool IotsaConfig::inConfigurationMode(bool extend) { bool ok = configurationMode == IOTSA_MODE_CONFIG; if (ok && extend) extendConfigurationMode(); return ok; } bool IotsaConfig::inConfigurationOrFactoryMode() { if (configurationMode == IOTSA_MODE_CONFIG) return true; if (wifiMode == IOTSA_WIFI_FACTORY) return true; return false; } void IotsaConfig::extendConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode extended"); configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; } void IotsaConfig::endConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode ended"); configurationMode = IOTSA_MODE_NORMAL; configurationModeEndTime = 0; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; configSave(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::beginConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode entered"); configurationMode = IOTSA_MODE_CONFIG; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // No need to tell wifi (or save config): this call is done only by the // WiFi module when switching from factory mode to having a WiFi. } void IotsaConfig::factoryReset() { IFDEBUG IotsaSerial.println("configurationMode: Factory-reset"); delay(1000); IFDEBUG IotsaSerial.println("Formatting SPIFFS..."); SPIFFS.format(); IFDEBUG IotsaSerial.println("Format done, rebooting."); delay(2000); ESP.restart(); } void IotsaConfig::allowRequestedConfigurationMode() { if (nextConfigurationMode == configurationMode) return; IFDEBUG IotsaSerial.print("Switching configurationMode to "); IFDEBUG IotsaSerial.println(nextConfigurationMode); configurationMode = nextConfigurationMode; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; if (configurationMode == IOTSA_MODE_FACTORY_RESET) factoryReset(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::allowRCMDescription(const char *_rcmInteractionDescription) { rcmInteractionDescription = _rcmInteractionDescription; } uint32_t IotsaConfig::getStatusColor() { if (configurationMode == IOTSA_MODE_FACTORY_RESET) return 0x3f0000; // Red: Factory reset mode uint32_t extraColor = 0; switch(wifiMode) { case IOTSA_WIFI_DISABLED: return 0; case IOTSA_WIFI_SEARCHING: return 0x3f1f00; // Orange: searching for WiFi case IOTSA_WIFI_FACTORY: case IOTSA_WIFI_NOTFOUND: extraColor = 0x1f1f1f; // Add a bit of white to the configuration mode color // Pass through default: // Pass through ; } if (configurationMode == IOTSA_MODE_CONFIG) return extraColor | 0x3f003f; // Magenta: user-requested configuration mode if (configurationMode == IOTSA_MODE_OTA) return extraColor | 0x003f3f; // Cyan: OTA mode return extraColor; // Off: all ok, whiteish: factory reset network } void IotsaConfig::pauseSleep() { pauseSleepCount++; } void IotsaConfig::resumeSleep() { pauseSleepCount--; } void IotsaConfig::postponeSleep(uint32_t ms) { uint32_t noSleepBefore = millis() + ms; if (noSleepBefore > postponeSleepMillis) postponeSleepMillis = noSleepBefore; } bool IotsaConfig::canSleep() { if (pauseSleepCount > 0) return false; if (millis() > postponeSleepMillis) postponeSleepMillis = 0; return postponeSleepMillis == 0; } void IotsaConfig::configLoad() { IotsaConfigFileLoad cf("/config/config.cfg"); iotsaConfig.configWasLoaded = true; int tcm; cf.get("mode", tcm, IOTSA_MODE_NORMAL); iotsaConfig.configurationMode = (config_mode)tcm; cf.get("hostName", iotsaConfig.hostName, ""); if (iotsaConfig.hostName == "") iotsaConfig.setDefaultHostName(); cf.get("rebootTimeout", iotsaConfig.configurationModeTimeout, CONFIGURATION_MODE_TIMEOUT); #ifdef IOTSA_WITH_HTTPS if (iotsaConfigFileExists("/config/httpsKey.der") && iotsaConfigFileExists("/config/httpsCert.der")) { bool ok = iotsaConfigFileLoadBinary("/config/httpsKey.der", (uint8_t **)&iotsaConfig.httpsKey, &iotsaConfig.httpsKeyLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsKey.der"); } ok = iotsaConfigFileLoadBinary("/config/httpsCert.der", (uint8_t **)&iotsaConfig.httpsCertificate, &iotsaConfig.httpsCertificateLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsCert.der"); } } #endif // IOTSA_WITH_HTTPS } void IotsaConfig::configSave() { IotsaConfigFileSave cf("/config/config.cfg"); cf.put("mode", nextConfigurationMode); // Note: nextConfigurationMode, which will be read as configurationMode cf.put("hostName", hostName); cf.put("rebootTimeout", configurationModeTimeout); // Key/cert are saved in iotsaConfigMod IFDEBUG IotsaSerial.println("Saved config.cfg"); } void IotsaConfig::ensureConfigLoaded() { if (!configWasLoaded) configLoad(); }; void IotsaConfig::requestReboot(uint32_t ms) { IFDEBUG IotsaSerial.println("Restart requested"); rebootAtMillis = millis() + ms; } void IotsaConfig::printHeapSpace() { // Difficult to print on esp8266. Debugging only, so just don't print anything. #ifdef ESP32 size_t memAvail = heap_caps_get_free_size(MALLOC_CAP_8BIT); size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); IFDEBUG IotsaSerial.printf("Available heap space: %u bytes, largest block: %u bytes\n", memAvail, largestBlock); #endif }<|endoftext|>
<commit_before>/* * istream implementation which reads a file from a NFS server. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_nfs.hxx" #include "istream/istream_internal.hxx" #include "istream/istream_buffer.hxx" #include "nfs_client.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include "util/ForeignFifoBuffer.hxx" #include <assert.h> #include <string.h> static const size_t NFS_BUFFER_SIZE = 32768; struct istream_nfs { struct istream base; struct nfs_file_handle *handle; /** * The offset of the next "pread" call on the NFS server. */ uint64_t offset; /** * The number of bytes that are remaining on the NFS server, not * including the amount of data that is already pending. */ uint64_t remaining; /** * The number of bytes currently scheduled by nfs_pread_async(). */ size_t pending_read; /** * The number of bytes that shall be discarded from the * nfs_pread_async() result. This is non-zero if istream_skip() * has been called while a read call was pending. */ size_t discard_read; ForeignFifoBuffer<uint8_t> buffer; istream_nfs():buffer(nullptr) {} }; extern const struct nfs_client_read_file_handler istream_nfs_read_handler; /* * internal * */ static void istream_nfs_schedule_read(struct istream_nfs *n) { assert(n->pending_read == 0); const size_t max = n->buffer.IsDefined() ? n->buffer.Write().size : NFS_BUFFER_SIZE; size_t nbytes = n->remaining > max ? max : (size_t)n->remaining; const uint64_t offset = n->offset; n->offset += nbytes; n->remaining -= nbytes; n->pending_read = nbytes; nfs_client_read_file(n->handle, offset, nbytes, &istream_nfs_read_handler, n); } /** * Check for end-of-file, and if there's more data to read, schedule * another read call. * * The input buffer must be empty. */ static void istream_nfs_schedule_read_or_eof(struct istream_nfs *n) { assert(n->buffer.IsEmpty()); if (n->pending_read > 0) return; if (n->remaining > 0) { /* read more */ istream_nfs_schedule_read(n); } else { /* end of file */ nfs_client_close_file(n->handle); istream_deinit_eof(&n->base); } } static void istream_nfs_feed(struct istream_nfs *n, const void *data, size_t length) { assert(length > 0); auto &buffer = n->buffer; if (buffer.IsNull()) { const uint64_t total_size = n->remaining + length; const size_t buffer_size = total_size > NFS_BUFFER_SIZE ? NFS_BUFFER_SIZE : (size_t)total_size; buffer.SetBuffer(PoolAlloc<uint8_t>(*n->base.pool, buffer_size), buffer_size); } auto w = buffer.Write(); assert(w.size >= length); memcpy(w.data, data, length); buffer.Append(length); } static void istream_nfs_read_from_buffer(struct istream_nfs *n) { assert(n->buffer.IsDefined()); size_t remaining = istream_buffer_consume(&n->base, n->buffer); if (remaining == 0 && n->pending_read == 0) istream_nfs_schedule_read_or_eof(n); } /* * nfs_client handler * */ static void istream_nfs_read_data(const void *data, size_t _length, void *ctx) { struct istream_nfs *n = (istream_nfs *)ctx; assert(n->pending_read > 0); assert(n->discard_read <= n->pending_read); assert(_length <= n->pending_read); if (_length < n->pending_read) { nfs_client_close_file(n->handle); GError *error = g_error_new_literal(g_file_error_quark(), 0, "premature end of file"); istream_deinit_abort(&n->base, error); return; } const size_t discard = n->discard_read; const size_t length = n->pending_read - discard; n->pending_read = 0; n->discard_read = 0; if (length > 0) istream_nfs_feed(n, (const char *)data + discard, length); istream_nfs_read_from_buffer(n); } static void istream_nfs_read_error(GError *error, void *ctx) { struct istream_nfs *n = (istream_nfs *)ctx; assert(n->pending_read > 0); nfs_client_close_file(n->handle); istream_deinit_abort(&n->base, error); } const struct nfs_client_read_file_handler istream_nfs_read_handler = { istream_nfs_read_data, istream_nfs_read_error, }; /* * istream implementation * */ static inline struct istream_nfs * istream_to_nfs(struct istream *istream) { return &ContainerCast2(*istream, &istream_nfs::base); } static off_t istream_nfs_available(struct istream *istream, bool partial gcc_unused) { struct istream_nfs *n = istream_to_nfs(istream); return n->remaining + n->pending_read - n->discard_read + n->buffer.GetAvailable(); } static off_t istream_nfs_skip(struct istream *istream, off_t _length) { struct istream_nfs *n = istream_to_nfs(istream); assert(n->discard_read <= n->pending_read); uint64_t length = _length; uint64_t result = 0; if (n->buffer.IsDefined()) { const uint64_t buffer_available = n->buffer.GetAvailable(); const uint64_t consume = length < buffer_available ? length : buffer_available; n->buffer.Consume(consume); result += consume; length -= consume; } const uint64_t pending_available = n->pending_read - n->discard_read; uint64_t consume = length < pending_available ? length : pending_available; n->discard_read += consume; result += consume; length -= consume; if (length > n->remaining) length = n->remaining; n->remaining -= length; n->offset += length; result += length; return result; } static void istream_nfs_read(struct istream *istream) { struct istream_nfs *n = istream_to_nfs(istream); if (!n->buffer.IsEmpty()) istream_nfs_read_from_buffer(n); else istream_nfs_schedule_read_or_eof(n); } static void istream_nfs_close(struct istream *istream) { struct istream_nfs *const n = istream_to_nfs(istream); nfs_client_close_file(n->handle); istream_deinit(&n->base); } static const struct istream_class istream_nfs = { istream_nfs_available, istream_nfs_skip, istream_nfs_read, nullptr, istream_nfs_close, }; /* * constructor * */ struct istream * istream_nfs_new(struct pool *pool, struct nfs_file_handle *handle, uint64_t start, uint64_t end) { assert(pool != nullptr); assert(handle != nullptr); assert(start <= end); auto *n = NewFromPool<struct istream_nfs>(*pool); istream_init(&n->base, &istream_nfs, pool); n->handle = handle; n->offset = start; n->remaining = end - start; n->pending_read = 0; n->discard_read = 0; return &n->base; } <commit_msg>istream_nfs: use C++11 initializers<commit_after>/* * istream implementation which reads a file from a NFS server. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_nfs.hxx" #include "istream/istream_internal.hxx" #include "istream/istream_buffer.hxx" #include "nfs_client.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include "util/ForeignFifoBuffer.hxx" #include <assert.h> #include <string.h> static const size_t NFS_BUFFER_SIZE = 32768; struct istream_nfs { struct istream base; struct nfs_file_handle *handle; /** * The offset of the next "pread" call on the NFS server. */ uint64_t offset; /** * The number of bytes that are remaining on the NFS server, not * including the amount of data that is already pending. */ uint64_t remaining; /** * The number of bytes currently scheduled by nfs_pread_async(). */ size_t pending_read = 0; /** * The number of bytes that shall be discarded from the * nfs_pread_async() result. This is non-zero if istream_skip() * has been called while a read call was pending. */ size_t discard_read = 0; ForeignFifoBuffer<uint8_t> buffer; istream_nfs():buffer(nullptr) {} }; extern const struct nfs_client_read_file_handler istream_nfs_read_handler; /* * internal * */ static void istream_nfs_schedule_read(struct istream_nfs *n) { assert(n->pending_read == 0); const size_t max = n->buffer.IsDefined() ? n->buffer.Write().size : NFS_BUFFER_SIZE; size_t nbytes = n->remaining > max ? max : (size_t)n->remaining; const uint64_t offset = n->offset; n->offset += nbytes; n->remaining -= nbytes; n->pending_read = nbytes; nfs_client_read_file(n->handle, offset, nbytes, &istream_nfs_read_handler, n); } /** * Check for end-of-file, and if there's more data to read, schedule * another read call. * * The input buffer must be empty. */ static void istream_nfs_schedule_read_or_eof(struct istream_nfs *n) { assert(n->buffer.IsEmpty()); if (n->pending_read > 0) return; if (n->remaining > 0) { /* read more */ istream_nfs_schedule_read(n); } else { /* end of file */ nfs_client_close_file(n->handle); istream_deinit_eof(&n->base); } } static void istream_nfs_feed(struct istream_nfs *n, const void *data, size_t length) { assert(length > 0); auto &buffer = n->buffer; if (buffer.IsNull()) { const uint64_t total_size = n->remaining + length; const size_t buffer_size = total_size > NFS_BUFFER_SIZE ? NFS_BUFFER_SIZE : (size_t)total_size; buffer.SetBuffer(PoolAlloc<uint8_t>(*n->base.pool, buffer_size), buffer_size); } auto w = buffer.Write(); assert(w.size >= length); memcpy(w.data, data, length); buffer.Append(length); } static void istream_nfs_read_from_buffer(struct istream_nfs *n) { assert(n->buffer.IsDefined()); size_t remaining = istream_buffer_consume(&n->base, n->buffer); if (remaining == 0 && n->pending_read == 0) istream_nfs_schedule_read_or_eof(n); } /* * nfs_client handler * */ static void istream_nfs_read_data(const void *data, size_t _length, void *ctx) { struct istream_nfs *n = (istream_nfs *)ctx; assert(n->pending_read > 0); assert(n->discard_read <= n->pending_read); assert(_length <= n->pending_read); if (_length < n->pending_read) { nfs_client_close_file(n->handle); GError *error = g_error_new_literal(g_file_error_quark(), 0, "premature end of file"); istream_deinit_abort(&n->base, error); return; } const size_t discard = n->discard_read; const size_t length = n->pending_read - discard; n->pending_read = 0; n->discard_read = 0; if (length > 0) istream_nfs_feed(n, (const char *)data + discard, length); istream_nfs_read_from_buffer(n); } static void istream_nfs_read_error(GError *error, void *ctx) { struct istream_nfs *n = (istream_nfs *)ctx; assert(n->pending_read > 0); nfs_client_close_file(n->handle); istream_deinit_abort(&n->base, error); } const struct nfs_client_read_file_handler istream_nfs_read_handler = { istream_nfs_read_data, istream_nfs_read_error, }; /* * istream implementation * */ static inline struct istream_nfs * istream_to_nfs(struct istream *istream) { return &ContainerCast2(*istream, &istream_nfs::base); } static off_t istream_nfs_available(struct istream *istream, bool partial gcc_unused) { struct istream_nfs *n = istream_to_nfs(istream); return n->remaining + n->pending_read - n->discard_read + n->buffer.GetAvailable(); } static off_t istream_nfs_skip(struct istream *istream, off_t _length) { struct istream_nfs *n = istream_to_nfs(istream); assert(n->discard_read <= n->pending_read); uint64_t length = _length; uint64_t result = 0; if (n->buffer.IsDefined()) { const uint64_t buffer_available = n->buffer.GetAvailable(); const uint64_t consume = length < buffer_available ? length : buffer_available; n->buffer.Consume(consume); result += consume; length -= consume; } const uint64_t pending_available = n->pending_read - n->discard_read; uint64_t consume = length < pending_available ? length : pending_available; n->discard_read += consume; result += consume; length -= consume; if (length > n->remaining) length = n->remaining; n->remaining -= length; n->offset += length; result += length; return result; } static void istream_nfs_read(struct istream *istream) { struct istream_nfs *n = istream_to_nfs(istream); if (!n->buffer.IsEmpty()) istream_nfs_read_from_buffer(n); else istream_nfs_schedule_read_or_eof(n); } static void istream_nfs_close(struct istream *istream) { struct istream_nfs *const n = istream_to_nfs(istream); nfs_client_close_file(n->handle); istream_deinit(&n->base); } static const struct istream_class istream_nfs = { istream_nfs_available, istream_nfs_skip, istream_nfs_read, nullptr, istream_nfs_close, }; /* * constructor * */ struct istream * istream_nfs_new(struct pool *pool, struct nfs_file_handle *handle, uint64_t start, uint64_t end) { assert(pool != nullptr); assert(handle != nullptr); assert(start <= end); auto *n = NewFromPool<struct istream_nfs>(*pool); istream_init(&n->base, &istream_nfs, pool); n->handle = handle; n->offset = start; n->remaining = end - start; return &n->base; } <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/switch.h> #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <iostream> #include <string> #include <cstring> // for memset #include "common.h" namespace pibmv2 { device_info_t device_info_state; } // namespace pibmv2 extern "C" { pi_status_t _pi_init(void *extra) { (void) extra; memset(&pibmv2::device_info_state, 0, sizeof(pibmv2::device_info_state)); return PI_STATUS_SUCCESS; } pi_status_t _pi_assign_device(pi_dev_id_t dev_id, const pi_p4info_t *p4info, pi_assign_extra_t *extra) { (void) extra; pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(!d_info->assigned); d_info->p4info = p4info; d_info->assigned = 1; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_start(pi_dev_id_t dev_id, const pi_p4info_t *p4info, const char *device_data, size_t device_data_size) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); auto error_code = pibmv2::switch_->load_new_config( std::string(device_data, device_data_size)); if (error_code != bm::RuntimeInterface::ErrorCode::SUCCESS) return PI_STATUS_TARGET_ERROR; d_info->p4info = p4info; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_end(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); auto error_code = pibmv2::switch_->swap_configs(); if (error_code != bm::RuntimeInterface::ErrorCode::SUCCESS) return PI_STATUS_TARGET_ERROR; return PI_STATUS_SUCCESS; } pi_status_t _pi_remove_device(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); d_info->assigned = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_destroy() { return PI_STATUS_SUCCESS; } // bmv2 does not support transaction and has no use for the session_handle pi_status_t _pi_session_init(pi_session_handle_t *session_handle) { *session_handle = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_session_cleanup(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_batch_begin(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_batch_end(pi_session_handle_t session_handle, bool hw_sync) { (void) session_handle; (void) hw_sync; return PI_STATUS_SUCCESS; } pi_status_t _pi_packetout_send(pi_dev_id_t dev_id, const char *pkt, size_t size) { (void) dev_id; pibmv2::switch_->receive(pibmv2::cpu_port, pkt, static_cast<int>(size)); return PI_STATUS_SUCCESS; } } <commit_msg>Fix unused-variable warning in PI<commit_after>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/switch.h> #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <iostream> #include <string> #include <cstring> // for memset #include "common.h" namespace pibmv2 { device_info_t device_info_state; } // namespace pibmv2 extern "C" { pi_status_t _pi_init(void *extra) { (void) extra; memset(&pibmv2::device_info_state, 0, sizeof(pibmv2::device_info_state)); return PI_STATUS_SUCCESS; } pi_status_t _pi_assign_device(pi_dev_id_t dev_id, const pi_p4info_t *p4info, pi_assign_extra_t *extra) { (void) extra; pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(!d_info->assigned); d_info->p4info = p4info; d_info->assigned = 1; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_start(pi_dev_id_t dev_id, const pi_p4info_t *p4info, const char *device_data, size_t device_data_size) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); auto error_code = pibmv2::switch_->load_new_config( std::string(device_data, device_data_size)); if (error_code != bm::RuntimeInterface::ErrorCode::SUCCESS) return PI_STATUS_TARGET_ERROR; d_info->p4info = p4info; return PI_STATUS_SUCCESS; } pi_status_t _pi_update_device_end(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); _BM_UNUSED(d_info); assert(d_info->assigned); auto error_code = pibmv2::switch_->swap_configs(); if (error_code != bm::RuntimeInterface::ErrorCode::SUCCESS) return PI_STATUS_TARGET_ERROR; return PI_STATUS_SUCCESS; } pi_status_t _pi_remove_device(pi_dev_id_t dev_id) { pibmv2::device_info_t *d_info = pibmv2::get_device_info(dev_id); assert(d_info->assigned); d_info->assigned = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_destroy() { return PI_STATUS_SUCCESS; } // bmv2 does not support transaction and has no use for the session_handle pi_status_t _pi_session_init(pi_session_handle_t *session_handle) { *session_handle = 0; return PI_STATUS_SUCCESS; } pi_status_t _pi_session_cleanup(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_batch_begin(pi_session_handle_t session_handle) { (void) session_handle; return PI_STATUS_SUCCESS; } pi_status_t _pi_batch_end(pi_session_handle_t session_handle, bool hw_sync) { (void) session_handle; (void) hw_sync; return PI_STATUS_SUCCESS; } pi_status_t _pi_packetout_send(pi_dev_id_t dev_id, const char *pkt, size_t size) { (void) dev_id; pibmv2::switch_->receive(pibmv2::cpu_port, pkt, static_cast<int>(size)); return PI_STATUS_SUCCESS; } } <|endoftext|>