text
stringlengths
54
60.6k
<commit_before>#include <iostream> #include <stdio.h> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/nonfree/features2d.hpp" #include "server/detector/features.h" using namespace cv; using namespace std; namespace { int SURF_MIN_HESSIAN = 400; } // namespace namespace detector { double ComputeFeatureDistance(const Mat& input_image, const string& template_path) { // FIXME(sghiaus): Remove this. return 0; Mat template_image = imread(template_path, CV_LOAD_IMAGE_GRAYSCALE); // Detect keypoints. SurfFeatureDetector detector(SURF_MIN_HESSIAN); vector<KeyPoint> input_kps, template_kps; detector.detect(input_image, input_kps); detector.detect(template_image, template_kps); // Calculate descriptors. SurfDescriptorExtractor extractor; Mat input_des, template_des; extractor.compute(input_image, input_kps, input_des); extractor.compute(template_image, template_kps, template_des); // Perform matching. FlannBasedMatcher matcher; vector<DMatch> matches; matcher.match(template_des, input_des, matches); double total_distance = 0; for (int i = 0; i < template_des.rows; ++i) { total_distance += matches[i].distance; } return total_distance; } } // namespace detector <commit_msg>Removes debug statement.<commit_after>#include <iostream> #include <stdio.h> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/nonfree/features2d.hpp" #include "server/detector/features.h" using namespace cv; using namespace std; namespace { int SURF_MIN_HESSIAN = 400; } // namespace namespace detector { double ComputeFeatureDistance(const Mat& input_image, const string& template_path) { Mat template_image = imread(template_path, CV_LOAD_IMAGE_GRAYSCALE); // Detect keypoints. SurfFeatureDetector detector(SURF_MIN_HESSIAN); vector<KeyPoint> input_kps, template_kps; detector.detect(input_image, input_kps); detector.detect(template_image, template_kps); // Calculate descriptors. SurfDescriptorExtractor extractor; Mat input_des, template_des; extractor.compute(input_image, input_kps, input_des); extractor.compute(template_image, template_kps, template_des); // Perform matching. FlannBasedMatcher matcher; vector<DMatch> matches; matcher.match(template_des, input_des, matches); double total_distance = 0; for (int i = 0; i < template_des.rows; ++i) { total_distance += matches[i].distance; } return total_distance; } } // namespace detector <|endoftext|>
<commit_before>/** @file config.hpp @brief Configuration. @author Timothy Howard @copyright 2013-2014 Timothy Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define CEFORMAT_AUX_ALLOCATOR HORD_AUX_ALLOCATOR //#define CEFORMAT_CONFIG_STRING_TYPE //#define CEFORMAT_CONFIG_OSTRINGSTREAM_TYPE /** @endcond */ #include <duct/config.hpp> /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ DUCT_STRINGIFY(x) /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <commit_msg>config: added HORD_DATA_ENDIAN to configure endianness globally.<commit_after>/** @file config.hpp @brief Configuration. @author Timothy Howard @copyright 2013-2014 Timothy Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define CEFORMAT_AUX_ALLOCATOR HORD_AUX_ALLOCATOR //#define CEFORMAT_CONFIG_STRING_TYPE //#define CEFORMAT_CONFIG_OSTRINGSTREAM_TYPE #define HORD_DATA_ENDIAN duct::Endian::little /** @endcond */ #include <duct/config.hpp> /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ DUCT_STRINGIFY(x) /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <|endoftext|>
<commit_before>#include <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <utility> #include "../core/item.hpp" #include "../string.hpp" #include "command_line.hpp" enum { /* * Same order as they are initialized * in main(). Perhaps we should have a * getter funtion instead? * * These (or well, only main) are used in * validate_arguments() to get the group of * main arguments so that we can find if any of * those are passed. * * I'm a bit unsure if it's worth the time to * implement a better way to do this. This will work * as long as they are in the same order as they are * initialized in in main(). */ main, excl, exact, misc }; enum { /* magic padding numbers */ padding_margin = 4, desc_align_magic = 7 }; cliparser cliparser::make(const string &&progname, const groups &&groups) { return cliparser("Usage: " + progname + " OPTION [OPTION]... [PATH]", std::forward<decltype(groups)>(groups)); } void cliparser::usage() const { std::cout << synopsis_ << "\n\n"; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { size_t len = opt.flag_long.length() + opt.flag.length() + opt.token.length() + padding_margin; maxlen = std::max(len, maxlen); } } /* * Print each option group, its options, the options' * descriptions, token and possible values for said token (if any). */ for (const auto &group : valid_groups_) { std::cout << group.name << " arguments" << (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":") << '\n'; if (group.options.empty()) { std::cout << " N/A, see <https://github.com/Tmplt/bookwyrm/issues/71>\n"; } for (const auto &opt : group.options) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << ' ' << opt.token; pad--; } /* * Print the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << '\n'; pad += opt.flag_long.length() + opt.token.length() + desc_align_magic; std::cout << string(pad, ' ') << opt.token << " is one of: " << bookwyrm::vector_to_string(opt.values); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << '\n'; } std::cout << std::endl; } } bool cliparser::has(const string &option) const { return passed_opts_.find(option) != passed_opts_.cend(); } bool cliparser::has(size_t index) const { return positional_args_.size() > index; } string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return passed_opts_.find(opt)->second; return ""; } string cliparser::get(size_t index) const { return has(index) ? positional_args_[index] : ""; } vector<string> cliparser::get_many(const string &&opt) const { vector<string> values; if (has(opt)) { auto range = passed_opts_.equal_range(opt); /* Can't we just return {range.first, range.second} somehow? */ for (auto &opt = range.first; opt != range.second; opt++) values.push_back(opt->second); } return values; } void cliparser::process_arguments(const vector<string> &args) { bool skip_next_arg = false; for (size_t i = 0; i < args.size(); i++) { if (skip_next_arg) { skip_next_arg = false; continue; } const string_view &arg = args[i]; /* XXX: Work-around for weird string_view behavior. */ if (args.size() > i + 1) { const string_view &next_arg = args[i + 1]; skip_next_arg = parse_pair(arg, next_arg); } else { skip_next_arg = parse_pair(arg, ""); } } } void cliparser::validate_arguments() const { /* Did we get at least one of the required main flags? */ const bool main_opt_passed = std::invoke([ opts = passed_opts_, main_opts = valid_groups_[main].options ] { vector<string> required_opts, passed_opts; /* Since we only want to match against the long flags, we copy those. */ for (const auto &opt : opts) passed_opts.emplace_back(opt.first); for (const auto &opt : main_opts) required_opts.emplace_back(opt.flag_long.substr(2)); return std::find_first_of(passed_opts.cbegin(), passed_opts.cend(), required_opts.cbegin(), required_opts.cend()) != passed_opts.cend(); }); if (has("ident") && passed_opts_.size() > 1) throw argument_error("ident flag is exclusive and may not be passed with another flag"); if (!has("ident") && !main_opt_passed) throw argument_error("at least one main argument must be specified"); if (has(1)) throw argument_error("only one positional argument (the download path) is allowed"); if (has("accuracy")) { try { if (int a = std::stoi(get("accuracy")); a < 0 || a > 100) throw value_error("accuracy is only valid within the range of 0-100% percent"); } catch (std::invalid_argument &) { throw value_error("malformed accuracy"); } } } bool cliparser::parse_pair(const string_view &input, const string_view &input_next) { /* * An option with a required value must of course have one, and * if a list of valid values are associated with that option, * we check that too. */ const auto validate_opt_value = [](const string_view &flag, const string_view &value, const vector<string> &valid_values) { if (value.empty()) throw value_error("missing value for " + string(flag.data())); if (!valid_values.empty() && std::find(valid_values.cbegin(), valid_values.cend(), value) == valid_values.cend()) { throw value_error("invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) + "; valid options are: " + bookwyrm::vector_to_string(valid_values)); } return value; }; for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { if (opt_exists(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { /* The option is only a flag. */ passed_opts_.emplace(opt.flag_long.substr(2), ""); return false; } /* * The option should have an accompanied value. * Let's verify it with opt.values. */ const auto value = validate_opt_value(input, input_next, opt.values); passed_opts_.emplace(opt.flag_long.substr(2), value); return value == input_next; } } } if (input[0] == '-') throw argument_error("unrecognized option " + string(input.data())); positional_args_.emplace_back(input); return false; } bool cliparser::opt_exists(const string_view &option, string opt_short, string opt_long) { const bool is_short = option.compare(0, opt_short.length(), opt_short) == 0, is_long = option.compare(0, opt_long.length(), opt_long) == 0; return is_short || is_long; } <commit_msg>fix(cli): correctly compare strings in `opt_exists`<commit_after>#include <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <utility> #include "../core/item.hpp" #include "../string.hpp" #include "command_line.hpp" enum { /* * Same order as they are initialized * in main(). Perhaps we should have a * getter funtion instead? * * These (or well, only main) are used in * validate_arguments() to get the group of * main arguments so that we can find if any of * those are passed. * * I'm a bit unsure if it's worth the time to * implement a better way to do this. This will work * as long as they are in the same order as they are * initialized in in main(). */ main, excl, exact, misc }; enum { /* magic padding numbers */ padding_margin = 4, desc_align_magic = 7 }; cliparser cliparser::make(const string &&progname, const groups &&groups) { return cliparser("Usage: " + progname + " OPTION [OPTION]... [PATH]", std::forward<decltype(groups)>(groups)); } void cliparser::usage() const { std::cout << synopsis_ << "\n\n"; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { size_t len = opt.flag_long.length() + opt.flag.length() + opt.token.length() + padding_margin; maxlen = std::max(len, maxlen); } } /* * Print each option group, its options, the options' * descriptions, token and possible values for said token (if any). */ for (const auto &group : valid_groups_) { std::cout << group.name << " arguments" << (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":") << '\n'; if (group.options.empty()) { std::cout << " N/A, see <https://github.com/Tmplt/bookwyrm/issues/71>\n"; } for (const auto &opt : group.options) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << ' ' << opt.token; pad--; } /* * Print the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << '\n'; pad += opt.flag_long.length() + opt.token.length() + desc_align_magic; std::cout << string(pad, ' ') << opt.token << " is one of: " << bookwyrm::vector_to_string(opt.values); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << '\n'; } std::cout << std::endl; } } bool cliparser::has(const string &option) const { return passed_opts_.find(option) != passed_opts_.cend(); } bool cliparser::has(size_t index) const { return positional_args_.size() > index; } string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return passed_opts_.find(opt)->second; return ""; } string cliparser::get(size_t index) const { return has(index) ? positional_args_[index] : ""; } vector<string> cliparser::get_many(const string &&opt) const { vector<string> values; if (has(opt)) { auto range = passed_opts_.equal_range(opt); /* Can't we just return {range.first, range.second} somehow? */ for (auto &opt = range.first; opt != range.second; opt++) values.push_back(opt->second); } return values; } void cliparser::process_arguments(const vector<string> &args) { bool skip_next_arg = false; for (size_t i = 0; i < args.size(); i++) { if (skip_next_arg) { skip_next_arg = false; continue; } const string_view &arg = args[i]; /* XXX: Work-around for weird string_view behavior. */ if (args.size() > i + 1) { const string_view &next_arg = args[i + 1]; skip_next_arg = parse_pair(arg, next_arg); } else { skip_next_arg = parse_pair(arg, ""); } } } void cliparser::validate_arguments() const { /* Did we get at least one of the required main flags? */ const bool main_opt_passed = std::invoke([ opts = passed_opts_, main_opts = valid_groups_[main].options ] { vector<string> required_opts, passed_opts; /* Since we only want to match against the long flags, we copy those. */ for (const auto &opt : opts) passed_opts.emplace_back(opt.first); for (const auto &opt : main_opts) required_opts.emplace_back(opt.flag_long.substr(2)); return std::find_first_of(passed_opts.cbegin(), passed_opts.cend(), required_opts.cbegin(), required_opts.cend()) != passed_opts.cend(); }); if (has("ident") && passed_opts_.size() > 1) throw argument_error("ident flag is exclusive and may not be passed with another flag"); if (!has("ident") && !main_opt_passed) throw argument_error("at least one main argument must be specified"); if (has(1)) throw argument_error("only one positional argument (the download path) is allowed"); if (has("accuracy")) { try { if (int a = std::stoi(get("accuracy")); a < 0 || a > 100) throw value_error("accuracy is only valid within the range of 0-100% percent"); } catch (std::invalid_argument &) { throw value_error("malformed accuracy"); } } } bool cliparser::parse_pair(const string_view &input, const string_view &input_next) { /* * An option with a required value must of course have one, and * if a list of valid values are associated with that option, * we check that too. */ const auto validate_opt_value = [](const string_view &flag, const string_view &value, const vector<string> &valid_values) { if (value.empty()) throw value_error("missing value for " + string(flag.data())); if (!valid_values.empty() && std::find(valid_values.cbegin(), valid_values.cend(), value) == valid_values.cend()) { throw value_error("invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) + "; valid options are: " + bookwyrm::vector_to_string(valid_values)); } return value; }; for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { if (opt_exists(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { /* The option is only a flag. */ passed_opts_.emplace(opt.flag_long.substr(2), ""); return false; } /* * The option should have an accompanied value. * Let's verify it with opt.values. */ const auto value = validate_opt_value(input, input_next, opt.values); passed_opts_.emplace(opt.flag_long.substr(2), value); return value == input_next; } } } if (input[0] == '-') throw argument_error("unrecognized option " + string(input.data())); positional_args_.emplace_back(input); return false; } bool cliparser::opt_exists(const string_view &option, string opt_short, string opt_long) { const auto len = std::max({option.length(), opt_short.length(), opt_long.length()}); const bool is_short = option.compare(0, len, opt_short) == 0, is_long = option.compare(0, len, opt_long) == 0; return is_short || is_long; } <|endoftext|>
<commit_before>#ifndef ACQUISITION_HPP #define ACQUISITION_HPP #include <opencv2/opencv.hpp> #include <opencv2/videoio.hpp> class acquisition { private: cv::VideoCapture _capture = 0; /** * handle opencv errors * @param status error code (CV::Error::Code) * @param func_name function name * @param err_msg error description * @param file_name source file name * @param line line number in the source file * @param userdata [description] * @return [description] */ static int handleError (int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata); public: acquisition (); acquisition (const int device); acquisition (const std::string& filename); ~acquisition (); /** * set source of capture data * @param device is the camera identifier */ void source (const int device = -1); /** * set source of capture data * @param filename the to be captured file */ void source (const std::string& filename); /** * capture data * @return return a captured frame */ cv::Mat capture (); /** * get camera count * This moment this will just return the max check value * (10). This is because opencv is not working correctly. * @return number of cameras connected */ int cam_count (); }; #endif // ACQUISITION_HPP <commit_msg>fix issue with acquisition<commit_after>#ifndef ACQUISITION_HPP #define ACQUISITION_HPP #include <opencv2/opencv.hpp> #include <opencv2/videoio.hpp> class acquisition { private: cv::VideoCapture _capture; /** * handle opencv errors * @param status error code (CV::Error::Code) * @param func_name function name * @param err_msg error description * @param file_name source file name * @param line line number in the source file * @param userdata [description] * @return [description] */ static int handleError (int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata); public: acquisition (); acquisition (const int device); acquisition (const std::string& filename); ~acquisition (); /** * set source of capture data * @param device is the camera identifier */ void source (const int device = -1); /** * set source of capture data * @param filename the to be captured file */ void source (const std::string& filename); /** * capture data * @return return a captured frame */ cv::Mat capture (); /** * get camera count * This moment this will just return the max check value * (10). This is because opencv is not working correctly. * @return number of cameras connected */ int cam_count (); }; #endif // ACQUISITION_HPP <|endoftext|>
<commit_before>/** * Copyright (C) 2011 * University of Rochester Department of Computer Science * and * Lehigh University Department of Computer Science and Engineering * * License: Modified BSD * Please see the file LICENSE.RSTM for licensing information */ /** * This file presents a simple library API for using RSTM without compiler * support. The API consists of the following: * * TM_ALLOC : Allocate memory inside a transaction * TM_FREE : Deallocate memory inside a transaction * TM_SYS_INIT : Initialize the STM library * TM_SYS_SHUTDOWN : Shut down the STM library * TM_THREAD_INIT : Initialize a thread before using TM * TM_THREAD_SHUTDOWN : Shut down a thread * TM_SET_POLICY(P) : Change the STM algorithm on the fly * TM_BECOME_IRREVOC() : Become irrevocable or abort * TM_READ(var) : Read from shared memory from a txn * TM_WRITE(var, val) : Write to shared memory from a txn * TM_BEGIN(type) : Start a transaction... use 'atomic' as type * TM_END : End a transaction * * Custom Features: * * stm::restart() : Self-abort and immediately retry a txn * TM_BEGIN_FAST_INITIALIZATION : For fast initialization * TM_END_FAST_INITIALIZATION : For fast initialization * TM_GET_ALGNAME() : Get the current algorithm name * * Compiler Compatibility::Transaction Descriptor Management: * * TM_GET_THREAD() : for getting the thread's descriptor, if needed * TM_ARG_ALONE : for passing descriptors to transactional functions * TM_ARG : (same) * TM_PARAM : (same) * TM_PARAM_ALONE : (same) * * Compiler Compatibility::Annotations (unused in library): * * TM_WAIVER : mark a block that does not get TM instrumentation * TM_CALLABLE : mark a function as being callable by TM */ #ifndef API_LIBRARY_HPP__ #define API_LIBRARY_HPP__ #include <setjmp.h> #include <stm/config.h> #include <common/platform.hpp> #include <stm/txthread.hpp> namespace stm { /** * Code to start a transaction. We assume the caller already performed a * setjmp, and is passing a valid setjmp buffer to this function. * * The code to begin a transaction *could* all live on the far side of a * function pointer. By putting some of the code into this inlined * function, we can: * * (a) avoid overhead under subsumption nesting and * (b) avoid code duplication or MACRO nastiness */ TM_INLINE inline void begin(TxThread* tx, scope_t* s, uint32_t /*abort_flags*/) { if (++tx->nesting_depth > 1) return; // we must ensure that the write of the transaction's scope occurs // *before* the read of the begin function pointer. On modern x86, a // CAS is faster than using WBR or xchg to achieve the ordering. On // SPARC, WBR is best. #ifdef STM_CPU_SPARC tx->scope = s; WBR; #else // NB: this CAS fails on a transaction restart... is that too expensive? casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)s); #endif // some adaptivity mechanisms need to know nontransactional and // transactional time. This code suffices, because it gets the time // between transactions. If we need the time for a single transaction, // we can run ProfileTM if (tx->end_txn_time) tx->total_nontxn_time += (tick() - tx->end_txn_time); // now call the per-algorithm begin function TxThread::tmbegin(tx); } /** * Code to commit a transaction. As in begin(), we are using forced * inlining to save a little bit of overhead for subsumption nesting, and to * prevent code duplication. */ TM_INLINE inline void commit(TxThread* tx) { // don't commit anything if we're nested... just exit this scope if (--tx->nesting_depth) return; // dispatch to the appropriate end function tx->tmcommit(tx); // zero scope (to indicate "not in tx") CFENCE; tx->scope = NULL; // record start of nontransactional time tx->end_txn_time = tick(); } /** * The STM system provides a message that exits the program (preferable to * 'assert(false)'). We use this in the API too, so it needs to be visible * here */ void NORETURN UNRECOVERABLE(const char*); /** * This portion of the API addresses allocation. We provide tx-safe malloc * and free calls, which also work from nontransactional contexts. */ /** * get a chunk of memory that will be automatically reclaimed if the caller * is a transaction that ultimately aborts */ inline void* tx_alloc(size_t size) { return Self->allocator.txAlloc(size); } /** * Free some memory. If the caller is a transaction that ultimately aborts, * the free will not happen. If the caller is a transaction that commits, * the free will happen at commit time. */ inline void tx_free(void* p) { Self->allocator.txFree(p); } /** * Master class for all objects that are used in transactions, to ensure * that those objects have tx-safe allocation * * WARNING: DEPRECATED * * We no longer use the Object class. In G++ it is unsafe to call * destructors from within a transaction (they trash the vtable * pointer in an unrecoverable way!), and some compilers don't handle * new() within a transaction correctly. Ugly though it is, for now, * you should just use malloc and free to create objects. */ struct Object { void* operator new(size_t size) { return tx_alloc(size); } // it is never safe to call a destructor inside a tx with g++, because // the vtable will be overwritten; if the tx aborts, the vtable will not // be restored. We hope this never gets called... void operator delete(void* ptr) { tx_free(ptr); UNRECOVERABLE("Calling destructors is not supported."); } virtual ~Object() { } }; /** * Here we declare the rest of the api to the STM library */ /** * Initialize the library (call before doing any per-thread initialization) * * We rely on the default setjmp/longjmp abort handling when using the * library API. */ void sys_init(void (*abort_handler)(TxThread*) = NULL); /** * Shut down the library. This just dumps some statistics. */ void sys_shutdown(); /*** Set up a thread's transactional context */ inline void thread_init() { TxThread::thread_init(); } /*** Shut down a thread's transactional context */ inline void thread_shutdown() { TxThread::thread_shutdown(); } /** * Set the current STM algorithm/policy. This should be called at the * beginning of each program phase */ void set_policy(const char*); /*** Report the algorithm name that was used to initialize libstm */ const char* get_algname(); /** * Try to become irrevocable. Call this from within a transaction. */ bool become_irrevoc(); /** * Abort the current transaction and restart immediately. */ void restart(); } /*** pull in the per-memory-access instrumentation framework */ #include "library_inst.hpp" /** * Now we can make simple macros for reading and writing shared memory, by * using templates to dispatch to the right code: */ namespace stm { template <typename T> inline T stm_read(T* addr, TxThread* thread) { return DISPATCH<T, sizeof(T)>::read(addr, thread); } template <typename T> inline void stm_write(T* addr, T val, TxThread* thread) { DISPATCH<T, sizeof(T)>::write(addr, val, thread); } } // namespace stm /** * Code should only use these calls, not the template stuff declared above */ #define TM_READ(var) stm::stm_read(&var, tx) #define TM_WRITE(var, val) stm::stm_write(&var, val, tx) /** * This is the way to start a transaction */ #define TM_BEGIN(TYPE) \ { \ stm::TxThread* tx = (stm::TxThread*)stm::Self; \ jmp_buf _jmpbuf; \ uint32_t abort_flags = setjmp(_jmpbuf); \ stm::begin(tx, &_jmpbuf, abort_flags); \ CFENCE; \ { /** * This is the way to commit a transaction. Note that these macros weakly * enforce lexical scoping */ #define TM_END \ } \ stm::commit(tx); \ } /** * Macro to get STM context. This currently produces a pointer to a TxThread */ #define TM_GET_THREAD() stm::TxThread* tx = (stm::TxThread*)stm::Self #define TM_ARG_ALONE stm::TxThread* tx #define TM_ARG , TM_ARG_ALONE #define TM_PARAM , tx #define TM_PARAM_ALONE tx #define TM_WAIVER #define TM_CALLABLE #define TM_SYS_INIT() stm::sys_init() #define TM_THREAD_INIT stm::thread_init #define TM_THREAD_SHUTDOWN() stm::thread_shutdown() #define TM_SYS_SHUTDOWN stm::sys_shutdown #define TM_ALLOC stm::tx_alloc #define TM_FREE stm::tx_free #define TM_SET_POLICY(P) stm::set_policy(P) #define TM_GET_ALGNAME() stm::get_algname() /** * This is gross. ITM, like any good compiler, will make nontransactional * versions of code so that we can cleanly do initialization from outside of * a transaction. The library **can** do this, but only via some cumbersome * template games that we really don't want to keep playing (see the previous * release for examples). * * Since we don't want to have transactional configuration (it is slow, and * it messes up some accounting of commits and transaction sizes), we use the * following trick: if we aren't using a compiler for instrumentation, then * BEGIN_FAST_INITIALIZATION will copy the current STM configuration (envar * STM_CONFIG) to a local, then switch the mode to CGL, then call the * instrumented functions using CGL instrumentation (e.g., the lightest * possible, and correct without a 'commit'). Likewise, if we aren't using a * compiler for instrumentation, then END_FAST_INITIALIZATION will restore * the original configuration, so that the app will use the STM as expected. */ #ifdef STM_API_ITM # define TM_BEGIN_FAST_INITIALIZATION() # define TM_END_FAST_INITIALIZATION() #else # define TM_BEGIN_FAST_INITIALIZATION() \ const char* __config_string__ = TM_GET_ALGNAME(); \ TM_SET_POLICY("CGL"); \ TM_GET_THREAD() # define TM_END_FAST_INITIALIZATION() \ TM_SET_POLICY(__config_string__) #endif #endif // API_LIBRARY_HPP__ <commit_msg>minor fix to the library API interface to irrevocability. Signature still claimed a return value of bool<commit_after>/** * Copyright (C) 2011 * University of Rochester Department of Computer Science * and * Lehigh University Department of Computer Science and Engineering * * License: Modified BSD * Please see the file LICENSE.RSTM for licensing information */ /** * This file presents a simple library API for using RSTM without compiler * support. The API consists of the following: * * TM_ALLOC : Allocate memory inside a transaction * TM_FREE : Deallocate memory inside a transaction * TM_SYS_INIT : Initialize the STM library * TM_SYS_SHUTDOWN : Shut down the STM library * TM_THREAD_INIT : Initialize a thread before using TM * TM_THREAD_SHUTDOWN : Shut down a thread * TM_SET_POLICY(P) : Change the STM algorithm on the fly * TM_BECOME_IRREVOC() : Become irrevocable or abort * TM_READ(var) : Read from shared memory from a txn * TM_WRITE(var, val) : Write to shared memory from a txn * TM_BEGIN(type) : Start a transaction... use 'atomic' as type * TM_END : End a transaction * * Custom Features: * * stm::restart() : Self-abort and immediately retry a txn * TM_BEGIN_FAST_INITIALIZATION : For fast initialization * TM_END_FAST_INITIALIZATION : For fast initialization * TM_GET_ALGNAME() : Get the current algorithm name * * Compiler Compatibility::Transaction Descriptor Management: * * TM_GET_THREAD() : for getting the thread's descriptor, if needed * TM_ARG_ALONE : for passing descriptors to transactional functions * TM_ARG : (same) * TM_PARAM : (same) * TM_PARAM_ALONE : (same) * * Compiler Compatibility::Annotations (unused in library): * * TM_WAIVER : mark a block that does not get TM instrumentation * TM_CALLABLE : mark a function as being callable by TM */ #ifndef API_LIBRARY_HPP__ #define API_LIBRARY_HPP__ #include <setjmp.h> #include <stm/config.h> #include <common/platform.hpp> #include <stm/txthread.hpp> namespace stm { /** * Code to start a transaction. We assume the caller already performed a * setjmp, and is passing a valid setjmp buffer to this function. * * The code to begin a transaction *could* all live on the far side of a * function pointer. By putting some of the code into this inlined * function, we can: * * (a) avoid overhead under subsumption nesting and * (b) avoid code duplication or MACRO nastiness */ TM_INLINE inline void begin(TxThread* tx, scope_t* s, uint32_t /*abort_flags*/) { if (++tx->nesting_depth > 1) return; // we must ensure that the write of the transaction's scope occurs // *before* the read of the begin function pointer. On modern x86, a // CAS is faster than using WBR or xchg to achieve the ordering. On // SPARC, WBR is best. #ifdef STM_CPU_SPARC tx->scope = s; WBR; #else // NB: this CAS fails on a transaction restart... is that too expensive? casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)s); #endif // some adaptivity mechanisms need to know nontransactional and // transactional time. This code suffices, because it gets the time // between transactions. If we need the time for a single transaction, // we can run ProfileTM if (tx->end_txn_time) tx->total_nontxn_time += (tick() - tx->end_txn_time); // now call the per-algorithm begin function TxThread::tmbegin(tx); } /** * Code to commit a transaction. As in begin(), we are using forced * inlining to save a little bit of overhead for subsumption nesting, and to * prevent code duplication. */ TM_INLINE inline void commit(TxThread* tx) { // don't commit anything if we're nested... just exit this scope if (--tx->nesting_depth) return; // dispatch to the appropriate end function tx->tmcommit(tx); // zero scope (to indicate "not in tx") CFENCE; tx->scope = NULL; // record start of nontransactional time tx->end_txn_time = tick(); } /** * The STM system provides a message that exits the program (preferable to * 'assert(false)'). We use this in the API too, so it needs to be visible * here */ void NORETURN UNRECOVERABLE(const char*); /** * This portion of the API addresses allocation. We provide tx-safe malloc * and free calls, which also work from nontransactional contexts. */ /** * get a chunk of memory that will be automatically reclaimed if the caller * is a transaction that ultimately aborts */ inline void* tx_alloc(size_t size) { return Self->allocator.txAlloc(size); } /** * Free some memory. If the caller is a transaction that ultimately aborts, * the free will not happen. If the caller is a transaction that commits, * the free will happen at commit time. */ inline void tx_free(void* p) { Self->allocator.txFree(p); } /** * Master class for all objects that are used in transactions, to ensure * that those objects have tx-safe allocation * * WARNING: DEPRECATED * * We no longer use the Object class. In G++ it is unsafe to call * destructors from within a transaction (they trash the vtable * pointer in an unrecoverable way!), and some compilers don't handle * new() within a transaction correctly. Ugly though it is, for now, * you should just use malloc and free to create objects. */ struct Object { void* operator new(size_t size) { return tx_alloc(size); } // it is never safe to call a destructor inside a tx with g++, because // the vtable will be overwritten; if the tx aborts, the vtable will not // be restored. We hope this never gets called... void operator delete(void* ptr) { tx_free(ptr); UNRECOVERABLE("Calling destructors is not supported."); } virtual ~Object() { } }; /** * Here we declare the rest of the api to the STM library */ /** * Initialize the library (call before doing any per-thread initialization) * * We rely on the default setjmp/longjmp abort handling when using the * library API. */ void sys_init(void (*abort_handler)(TxThread*) = NULL); /** * Shut down the library. This just dumps some statistics. */ void sys_shutdown(); /*** Set up a thread's transactional context */ inline void thread_init() { TxThread::thread_init(); } /*** Shut down a thread's transactional context */ inline void thread_shutdown() { TxThread::thread_shutdown(); } /** * Set the current STM algorithm/policy. This should be called at the * beginning of each program phase */ void set_policy(const char*); /*** Report the algorithm name that was used to initialize libstm */ const char* get_algname(); /** * Become irrevocable. Call this from within a transaction. */ void become_irrevoc(); /** * Abort the current transaction and restart immediately. */ void restart(); } /*** pull in the per-memory-access instrumentation framework */ #include "library_inst.hpp" /** * Now we can make simple macros for reading and writing shared memory, by * using templates to dispatch to the right code: */ namespace stm { template <typename T> inline T stm_read(T* addr, TxThread* thread) { return DISPATCH<T, sizeof(T)>::read(addr, thread); } template <typename T> inline void stm_write(T* addr, T val, TxThread* thread) { DISPATCH<T, sizeof(T)>::write(addr, val, thread); } } // namespace stm /** * Code should only use these calls, not the template stuff declared above */ #define TM_READ(var) stm::stm_read(&var, tx) #define TM_WRITE(var, val) stm::stm_write(&var, val, tx) /** * This is the way to start a transaction */ #define TM_BEGIN(TYPE) \ { \ stm::TxThread* tx = (stm::TxThread*)stm::Self; \ jmp_buf _jmpbuf; \ uint32_t abort_flags = setjmp(_jmpbuf); \ stm::begin(tx, &_jmpbuf, abort_flags); \ CFENCE; \ { /** * This is the way to commit a transaction. Note that these macros weakly * enforce lexical scoping */ #define TM_END \ } \ stm::commit(tx); \ } /** * Macro to get STM context. This currently produces a pointer to a TxThread */ #define TM_GET_THREAD() stm::TxThread* tx = (stm::TxThread*)stm::Self #define TM_ARG_ALONE stm::TxThread* tx #define TM_ARG , TM_ARG_ALONE #define TM_PARAM , tx #define TM_PARAM_ALONE tx #define TM_WAIVER #define TM_CALLABLE #define TM_SYS_INIT() stm::sys_init() #define TM_THREAD_INIT stm::thread_init #define TM_THREAD_SHUTDOWN() stm::thread_shutdown() #define TM_SYS_SHUTDOWN stm::sys_shutdown #define TM_ALLOC stm::tx_alloc #define TM_FREE stm::tx_free #define TM_SET_POLICY(P) stm::set_policy(P) #define TM_BECOME_IRREVOC() stm::becom_irrevoc() #define TM_GET_ALGNAME() stm::get_algname() /** * This is gross. ITM, like any good compiler, will make nontransactional * versions of code so that we can cleanly do initialization from outside of * a transaction. The library **can** do this, but only via some cumbersome * template games that we really don't want to keep playing (see the previous * release for examples). * * Since we don't want to have transactional configuration (it is slow, and * it messes up some accounting of commits and transaction sizes), we use the * following trick: if we aren't using a compiler for instrumentation, then * BEGIN_FAST_INITIALIZATION will copy the current STM configuration (envar * STM_CONFIG) to a local, then switch the mode to CGL, then call the * instrumented functions using CGL instrumentation (e.g., the lightest * possible, and correct without a 'commit'). Likewise, if we aren't using a * compiler for instrumentation, then END_FAST_INITIALIZATION will restore * the original configuration, so that the app will use the STM as expected. */ #ifdef STM_API_ITM # define TM_BEGIN_FAST_INITIALIZATION() # define TM_END_FAST_INITIALIZATION() #else # define TM_BEGIN_FAST_INITIALIZATION() \ const char* __config_string__ = TM_GET_ALGNAME(); \ TM_SET_POLICY("CGL"); \ TM_GET_THREAD() # define TM_END_FAST_INITIALIZATION() \ TM_SET_POLICY(__config_string__) #endif #endif // API_LIBRARY_HPP__ <|endoftext|>
<commit_before>#pragma once /** @file @brief unit test class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <stdio.h> #include <string.h> #include <string> #include <list> #include <iostream> #include <utility> #if defined(_MSC_VER) && (MSC_VER <= 1500) #include <cybozu/inttype.hpp> #else #include <stdint.h> #endif namespace cybozu { namespace test { class AutoRun { typedef void (*Func)(); typedef std::list<std::pair<const char*, Func> > UnitTestList; public: AutoRun() : init_(0) , term_(0) , okCount_(0) , ngCount_(0) , exceptionCount_(0) { } void setup(Func init, Func term) { init_ = init; term_ = term; } void append(const char *name, Func func) { list_.push_back(std::make_pair(name, func)); } void set(bool isOK) { if (isOK) { okCount_++; } else { ngCount_++; } } std::string getBaseName(const std::string& name) const { #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif size_t pos = name.find_last_of(sep); std::string ret = name.substr(pos + 1); pos = ret.find('.'); return ret.substr(0, pos); } int run(int, char *argv[]) { std::string msg; try { if (init_) init_(); for (UnitTestList::const_iterator i = list_.begin(), ie = list_.end(); i != ie; ++i) { std::cout << "ctest:module=" << i->first << std::endl; try { (i->second)(); } catch (std::exception& e) { exceptionCount_++; std::cout << "ctest: " << i->first << " is stopped by exception " << e.what() << std::endl; } catch (...) { exceptionCount_++; std::cout << "ctest: " << i->first << " is stopped by unknown exception" << std::endl; } } if (term_) term_(); } catch (std::exception& e) { msg = std::string("ctest:err:") + e.what(); } catch (...) { msg = "ctest:err: catch unknown exception"; } fflush(stdout); if (msg.empty()) { std::cout << "ctest:name=" << getBaseName(*argv) << ", module=" << list_.size() << ", total=" << (okCount_ + ngCount_ + exceptionCount_) << ", ok=" << okCount_ << ", ng=" << ngCount_ << ", exception=" << exceptionCount_ << std::endl; return 0; } else { std::cout << msg << std::endl; return 1; } } static inline AutoRun& getInstance() { static AutoRun instance; return instance; } private: Func init_; Func term_; int okCount_; int ngCount_; int exceptionCount_; UnitTestList list_; }; static AutoRun& autoRun = AutoRun::getInstance(); inline void test(bool ret, const std::string& msg, const std::string& param, const char *file, int line) { autoRun.set(ret); if (!ret) { std::cout << file << "(" << line << "):" << "ctest:" << msg << "(" << param << ");" << std::endl; } } template<typename T, typename U> bool isEqual(const T& lhs, const U& rhs) { return lhs == rhs; } inline bool isEqual(const char *lhs, const char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(char *lhs, const char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(const char *lhs, char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(char *lhs, char *rhs) { return strcmp(lhs, rhs) == 0; } // avoid to compare float directly inline bool isEqual(float lhs, float rhs) { union fi { float f; uint32_t i; } lfi, rfi; lfi.f = lhs; rfi.f = rhs; return lfi.i == rfi.i; } // avoid to compare double directly inline bool isEqual(double lhs, double rhs) { union di { double d; uint64_t i; } ldi, rdi; ldi.d = lhs; rdi.d = rhs; return ldi.i == rdi.i; } } } // cybozu::test #ifndef CYBOZU_TEST_DISABLE_AUTO_RUN int main(int argc, char *argv[]) { return cybozu::test::autoRun.run(argc, argv); } #endif /** alert if !x @param x [in] */ #define CYBOZU_TEST_ASSERT(x) cybozu::test::test(!!(x), "CYBOZU_TEST_ASSERT", #x, __FILE__, __LINE__) /** alert if x != y @param x [in] @param y [in] */ #define CYBOZU_TEST_EQUAL(x, y) { \ bool eq = cybozu::test::isEqual(x, y); \ cybozu::test::test(eq, "CYBOZU_TEST_EQUAL", #x ", " #y, __FILE__, __LINE__); \ if (!eq) { \ std::cout << "ctest: lhs=" << (x) << std::endl; \ std::cout << "ctest: rhs=" << (y) << std::endl; \ } \ } /** alert if fabs(x, y) >= eps @param x [in] @param y [in] */ #define CYBOZU_TEST_NEAR(x, y, eps) { \ bool isNear = fabs((x) - (y)) < eps; \ cybozu::test::test(isNear, "CYBOZU_TEST_NEAR", #x ", " #y, __FILE__, __LINE__); \ if (!isNear) { \ std::cout << "ctest: lhs=" << (x) << std::endl; \ std::cout << "ctest: rhs=" << (y) << std::endl; \ } \ } #define CYBOZU_TEST_EQUAL_POINTER(x, y) { \ bool eq = x == y; \ cybozu::test::test(eq, "CYBOZU_TEST_EQUAL_POINTER", #x ", " #y, __FILE__, __LINE__); \ if (!eq) { \ std::cout << "ctest: lhs=" << (const void*)(x) << std::endl; \ std::cout << "ctest: rhs=" << (const void*)(y) << std::endl; \ } \ } /** always alert @param msg [in] */ #define CYBOZU_TEST_FAIL(msg) cybozu::test::test(false, "CYBOZU_TEST_FAIL", msg, __FILE__, __LINE__) /** verify message in exception */ #define CYBOZU_TEST_EXCEPTION_MESSAGE(statement, Exception, msg) \ { \ int ret = 0; \ std::string errMsg; \ try { \ statement; \ ret = 1; \ } catch (const Exception& e) { \ errMsg = e.what(); \ if (errMsg.find(msg) == std::string::npos) { \ ret = 2; \ } \ } catch (...) { \ ret = 3; \ } \ if (ret) { \ cybozu::test::autoRun.set(false); \ cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION_MESSAGE", #statement ", " #Exception ", " #msg, __FILE__, __LINE__); \ if (ret == 1) { \ std::cout << "ctest: no exception" << std::endl; \ } else if (ret == 2) { \ std::cout << "ctest: bad exception msg:" << errMsg << std::endl; \ } else { \ std::cout << "ctest: unexpected exception" << std::endl; \ } \ } else { \ cybozu::test::autoRun.set(true); \ } \ } #define CYBOZU_TEST_EXCEPTION(statement, Exception) \ { \ int ret = 0; \ try { \ statement; \ ret = 1; \ } catch (const Exception&) { \ } catch (...) { \ ret = 2; \ } \ if (ret) { \ cybozu::test::autoRun.set(false); \ cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION", #statement ", " #Exception, __FILE__, __LINE__); \ if (ret == 1) { \ std::cout << "ctest: no exception" << std::endl; \ } else { \ std::cout << "ctest: unexpected exception" << std::endl; \ } \ } else { \ cybozu::test::autoRun.set(true); \ } \ } /** verify statement does not throw */ #define CYBOZU_TEST_NO_EXCEPTION(statement) \ try { \ statement; \ cybozu::test::autoRun.set(true); \ } catch (...) { \ cybozu::test::test(false, "CYBOZU_TEST_NO_EXCEPTION", #statement, __FILE__, __LINE__); \ } /** append auto unit test @param name [in] module name */ #define CYBOZU_TEST_AUTO(name) \ void cybozu_test_ ## name(); \ struct cybozu_test_local_ ## name { \ cybozu_test_local_ ## name() \ { \ cybozu::test::autoRun.append(#name, cybozu_test_ ## name); \ } \ } cybozu_test_local_instance_ ## name; \ void cybozu_test_ ## name() /** append auto unit test with fixture @param name [in] module name */ #define CYBOZU_TEST_AUTO_WITH_FIXTURE(name, Fixture) \ void cybozu_test_ ## name(); \ void cybozu_test_real_ ## name() \ { \ Fixture f; \ cybozu_test_ ## name(); \ } \ struct cybozu_test_local_ ## name { \ cybozu_test_local_ ## name() \ { \ cybozu::test::autoRun.append(#name, cybozu_test_real_ ## name); \ } \ } cybozu_test_local_instance_ ## name; \ void cybozu_test_ ## name() /** setup fixture @param Fixture [in] class name of fixture @note cstr of Fixture is called before test and dstr of Fixture is called after test */ #define CYBOZU_TEST_SETUP_FIXTURE(Fixture) \ Fixture *cybozu_test_local_fixture; \ void cybozu_test_local_init() \ { \ cybozu_test_local_fixture = new Fixture(); \ } \ void cybozu_test_local_term() \ { \ delete cybozu_test_local_fixture; \ } \ struct cybozu_test_local_fixture_setup_ { \ cybozu_test_local_fixture_setup_() \ { \ cybozu::test::autoRun.setup(cybozu_test_local_init, cybozu_test_local_term); \ } \ } cybozu_test_local_fixture_setup_instance_; <commit_msg>fix ; display bad num of tests if exception test fails<commit_after>#pragma once /** @file @brief unit test class Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved. */ #include <stdio.h> #include <string.h> #include <string> #include <list> #include <iostream> #include <utility> #if defined(_MSC_VER) && (MSC_VER <= 1500) #include <cybozu/inttype.hpp> #else #include <stdint.h> #endif namespace cybozu { namespace test { class AutoRun { typedef void (*Func)(); typedef std::list<std::pair<const char*, Func> > UnitTestList; public: AutoRun() : init_(0) , term_(0) , okCount_(0) , ngCount_(0) , exceptionCount_(0) { } void setup(Func init, Func term) { init_ = init; term_ = term; } void append(const char *name, Func func) { list_.push_back(std::make_pair(name, func)); } void set(bool isOK) { if (isOK) { okCount_++; } else { ngCount_++; } } std::string getBaseName(const std::string& name) const { #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif size_t pos = name.find_last_of(sep); std::string ret = name.substr(pos + 1); pos = ret.find('.'); return ret.substr(0, pos); } int run(int, char *argv[]) { std::string msg; try { if (init_) init_(); for (UnitTestList::const_iterator i = list_.begin(), ie = list_.end(); i != ie; ++i) { std::cout << "ctest:module=" << i->first << std::endl; try { (i->second)(); } catch (std::exception& e) { exceptionCount_++; std::cout << "ctest: " << i->first << " is stopped by exception " << e.what() << std::endl; } catch (...) { exceptionCount_++; std::cout << "ctest: " << i->first << " is stopped by unknown exception" << std::endl; } } if (term_) term_(); } catch (std::exception& e) { msg = std::string("ctest:err:") + e.what(); } catch (...) { msg = "ctest:err: catch unknown exception"; } fflush(stdout); if (msg.empty()) { std::cout << "ctest:name=" << getBaseName(*argv) << ", module=" << list_.size() << ", total=" << (okCount_ + ngCount_ + exceptionCount_) << ", ok=" << okCount_ << ", ng=" << ngCount_ << ", exception=" << exceptionCount_ << std::endl; return 0; } else { std::cout << msg << std::endl; return 1; } } static inline AutoRun& getInstance() { static AutoRun instance; return instance; } private: Func init_; Func term_; int okCount_; int ngCount_; int exceptionCount_; UnitTestList list_; }; static AutoRun& autoRun = AutoRun::getInstance(); inline void test(bool ret, const std::string& msg, const std::string& param, const char *file, int line) { autoRun.set(ret); if (!ret) { std::cout << file << "(" << line << "):" << "ctest:" << msg << "(" << param << ");" << std::endl; } } template<typename T, typename U> bool isEqual(const T& lhs, const U& rhs) { return lhs == rhs; } inline bool isEqual(const char *lhs, const char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(char *lhs, const char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(const char *lhs, char *rhs) { return strcmp(lhs, rhs) == 0; } inline bool isEqual(char *lhs, char *rhs) { return strcmp(lhs, rhs) == 0; } // avoid to compare float directly inline bool isEqual(float lhs, float rhs) { union fi { float f; uint32_t i; } lfi, rfi; lfi.f = lhs; rfi.f = rhs; return lfi.i == rfi.i; } // avoid to compare double directly inline bool isEqual(double lhs, double rhs) { union di { double d; uint64_t i; } ldi, rdi; ldi.d = lhs; rdi.d = rhs; return ldi.i == rdi.i; } } } // cybozu::test #ifndef CYBOZU_TEST_DISABLE_AUTO_RUN int main(int argc, char *argv[]) { return cybozu::test::autoRun.run(argc, argv); } #endif /** alert if !x @param x [in] */ #define CYBOZU_TEST_ASSERT(x) cybozu::test::test(!!(x), "CYBOZU_TEST_ASSERT", #x, __FILE__, __LINE__) /** alert if x != y @param x [in] @param y [in] */ #define CYBOZU_TEST_EQUAL(x, y) { \ bool eq = cybozu::test::isEqual(x, y); \ cybozu::test::test(eq, "CYBOZU_TEST_EQUAL", #x ", " #y, __FILE__, __LINE__); \ if (!eq) { \ std::cout << "ctest: lhs=" << (x) << std::endl; \ std::cout << "ctest: rhs=" << (y) << std::endl; \ } \ } /** alert if fabs(x, y) >= eps @param x [in] @param y [in] */ #define CYBOZU_TEST_NEAR(x, y, eps) { \ bool isNear = fabs((x) - (y)) < eps; \ cybozu::test::test(isNear, "CYBOZU_TEST_NEAR", #x ", " #y, __FILE__, __LINE__); \ if (!isNear) { \ std::cout << "ctest: lhs=" << (x) << std::endl; \ std::cout << "ctest: rhs=" << (y) << std::endl; \ } \ } #define CYBOZU_TEST_EQUAL_POINTER(x, y) { \ bool eq = x == y; \ cybozu::test::test(eq, "CYBOZU_TEST_EQUAL_POINTER", #x ", " #y, __FILE__, __LINE__); \ if (!eq) { \ std::cout << "ctest: lhs=" << (const void*)(x) << std::endl; \ std::cout << "ctest: rhs=" << (const void*)(y) << std::endl; \ } \ } /** always alert @param msg [in] */ #define CYBOZU_TEST_FAIL(msg) cybozu::test::test(false, "CYBOZU_TEST_FAIL", msg, __FILE__, __LINE__) /** verify message in exception */ #define CYBOZU_TEST_EXCEPTION_MESSAGE(statement, Exception, msg) \ { \ int ret = 0; \ std::string errMsg; \ try { \ statement; \ ret = 1; \ } catch (const Exception& e) { \ errMsg = e.what(); \ if (errMsg.find(msg) == std::string::npos) { \ ret = 2; \ } \ } catch (...) { \ ret = 3; \ } \ if (ret) { \ cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION_MESSAGE", #statement ", " #Exception ", " #msg, __FILE__, __LINE__); \ if (ret == 1) { \ std::cout << "ctest: no exception" << std::endl; \ } else if (ret == 2) { \ std::cout << "ctest: bad exception msg:" << errMsg << std::endl; \ } else { \ std::cout << "ctest: unexpected exception" << std::endl; \ } \ } else { \ cybozu::test::autoRun.set(true); \ } \ } #define CYBOZU_TEST_EXCEPTION(statement, Exception) \ { \ int ret = 0; \ try { \ statement; \ ret = 1; \ } catch (const Exception&) { \ } catch (...) { \ ret = 2; \ } \ if (ret) { \ cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION", #statement ", " #Exception, __FILE__, __LINE__); \ if (ret == 1) { \ std::cout << "ctest: no exception" << std::endl; \ } else { \ std::cout << "ctest: unexpected exception" << std::endl; \ } \ } else { \ cybozu::test::autoRun.set(true); \ } \ } /** verify statement does not throw */ #define CYBOZU_TEST_NO_EXCEPTION(statement) \ try { \ statement; \ cybozu::test::autoRun.set(true); \ } catch (...) { \ cybozu::test::test(false, "CYBOZU_TEST_NO_EXCEPTION", #statement, __FILE__, __LINE__); \ } /** append auto unit test @param name [in] module name */ #define CYBOZU_TEST_AUTO(name) \ void cybozu_test_ ## name(); \ struct cybozu_test_local_ ## name { \ cybozu_test_local_ ## name() \ { \ cybozu::test::autoRun.append(#name, cybozu_test_ ## name); \ } \ } cybozu_test_local_instance_ ## name; \ void cybozu_test_ ## name() /** append auto unit test with fixture @param name [in] module name */ #define CYBOZU_TEST_AUTO_WITH_FIXTURE(name, Fixture) \ void cybozu_test_ ## name(); \ void cybozu_test_real_ ## name() \ { \ Fixture f; \ cybozu_test_ ## name(); \ } \ struct cybozu_test_local_ ## name { \ cybozu_test_local_ ## name() \ { \ cybozu::test::autoRun.append(#name, cybozu_test_real_ ## name); \ } \ } cybozu_test_local_instance_ ## name; \ void cybozu_test_ ## name() /** setup fixture @param Fixture [in] class name of fixture @note cstr of Fixture is called before test and dstr of Fixture is called after test */ #define CYBOZU_TEST_SETUP_FIXTURE(Fixture) \ Fixture *cybozu_test_local_fixture; \ void cybozu_test_local_init() \ { \ cybozu_test_local_fixture = new Fixture(); \ } \ void cybozu_test_local_term() \ { \ delete cybozu_test_local_fixture; \ } \ struct cybozu_test_local_fixture_setup_ { \ cybozu_test_local_fixture_setup_() \ { \ cybozu::test::autoRun.setup(cybozu_test_local_init, cybozu_test_local_term); \ } \ } cybozu_test_local_fixture_setup_instance_; <|endoftext|>
<commit_before>#pragma once /** @file @brief zlib compressor and decompressor class Copyright (C) 2009 Cybozu Labs, Inc., all rights reserved. */ #include <cybozu/exception.hpp> #include <cybozu/endian.hpp> #include <cybozu/stream_fwd.hpp> #include <assert.h> #include <stdio.h> #include <zlib.h> #ifdef _MSC_VER #ifdef _DLL_CPPLIB #pragma comment(lib, "zlib_md.lib") #else #pragma comment(lib, "zlib_mt.lib") #endif #endif namespace cybozu { namespace zlib_local { const int DEF_MEM_LEVEL = 8; } // zlib_local /** zlib compressor class OutputStream must have size_t write(const char *buf, size_t size); */ template<class OutputStream, size_t maxBufSize = 2048> class ZlibCompressorT { OutputStream& os_; unsigned int crc_; unsigned int totalSize_; /* mod 2^32 */ z_stream z_; char buf_[maxBufSize]; bool isFlushCalled_; const bool useGzip_; ZlibCompressorT(const ZlibCompressorT&); void operator=(const ZlibCompressorT&); public: /** @param os [in] output stream @param useGzip [in] useGzip if true, use deflate if false @note useGzip option is not fully tested, so default off */ ZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION) : os_(os) , crc_(crc32(0L, Z_NULL, 0)) , totalSize_(0) , isFlushCalled_(false) , useGzip_(useGzip) { z_.zalloc = Z_NULL; z_.zfree = Z_NULL; z_.opaque = Z_NULL; if (useGzip_) { if (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit2") << std::string(z_.msg); } char header[] = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03"; /* OS_CODE = 0x03(Unix) */ write_os(header, 10); } else { if (deflateInit(&z_, compressionLevel) != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit") << std::string(z_.msg); } } } ~ZlibCompressorT() { if (!isFlushCalled_) { try { flush(); } catch (std::exception& e) { fprintf(stderr, "ZlibCompressor:flush:exception:%s\n", e.what()); } catch (...) { fprintf(stderr, "ZlibCompressor:flush:unknown exception\n"); } } deflateEnd(&z_); } /* compress buf @param buf [in] input data @param size [in] input data size */ void write(const void *buf, size_t _size) { assert(_size < (1U << 31)); uint32_t size = (uint32_t)_size; if (useGzip_) { crc_ = crc32(crc_, (const Bytef *)buf, size); totalSize_ += (unsigned int)size; } z_.next_in = (Bytef*)const_cast<char*>((const char*)buf); z_.avail_in = size; while (z_.avail_in > 0) { z_.next_out = (Bytef*)buf_; z_.avail_out = maxBufSize; int ret = deflate(&z_, Z_NO_FLUSH); if (ret != Z_STREAM_END && ret != Z_OK) { throw cybozu::Exception("zlib:exec:compress") << std::string(z_.msg); } write_os(buf_, maxBufSize - z_.avail_out); if (ret == Z_STREAM_END) break; } } void flush() { isFlushCalled_ = true; z_.next_in = 0; z_.avail_in = 0; for (;;) { z_.next_out = (Bytef*)buf_; z_.avail_out = maxBufSize; int ret = deflate(&z_, Z_FINISH); if (ret != Z_STREAM_END && ret != Z_OK) { throw cybozu::Exception("zlib:flush") << std::string(z_.msg); } write_os(buf_, sizeof(buf_) - z_.avail_out); if (ret == Z_STREAM_END) break; } if (useGzip_) { char tail[8]; cybozu::Set32bitAsLE(&tail[0], crc_); cybozu::Set32bitAsLE(&tail[4], totalSize_); write_os(tail, sizeof(tail)); } } private: void write_os(const char *buf, size_t size) { cybozu::OutputStreamTag<OutputStream>::write(os_, buf, size); } }; /** zlib decompressor class InputStream must have size_t read(char *str, size_t size); */ template<class InputStream, size_t maxBufSize = 2048> class ZlibDecompressorT { typedef cybozu::InputStreamTag<InputStream> In; InputStream& is_; unsigned int crc_; unsigned int totalSize_; /* mod 2^32 */ z_stream z_; int ret_; char buf_[maxBufSize]; const bool useGzip_; bool readGzipHeader_; void readAll(char *buf, size_t size) { In::read(is_, buf, size); } void skipToZero() { for (;;) { char buf[1]; readAll(buf, 1); if (buf[0] == '\0') break; } } void skip(int size) { for (int i = 0 ; i < size; i++) { char buf[1]; readAll(buf, 1); } } void readGzipHeader() { char header[10]; readAll(header, sizeof(header)); enum { FHCRC = 1 << 1, FEXTRA = 1 << 2, FNAME = 1 << 3, FCOMMENT = 1 << 4, RESERVED = 7 << 5, }; char flg = header[3]; if (header[0] == '\x1f' && header[1] == '\x8b' && header[2] == Z_DEFLATED && !(flg & RESERVED)) { if (flg & FEXTRA) { char xlen[2]; readAll(xlen, sizeof(xlen)); int size = cybozu::Get16bitAsLE(xlen); skip(size); } if (flg & FNAME) { skipToZero(); } if (flg & FCOMMENT) { skipToZero(); } if (flg & FHCRC) { skip(2); } return; } throw cybozu::Exception("zlib:ZlibDecompressorT:readGzipHeader:bad gzip header") << std::string(header, 10); } ZlibDecompressorT(const ZlibDecompressorT&); void operator=(const ZlibDecompressorT&); public: /** @param os [in] input stream @param useGzip [in] useGzip if true, use deflate if false @note useGzip option is not fully tested, so default off */ ZlibDecompressorT(InputStream& is, bool useGzip = false) : is_(is) , crc_(crc32(0L, Z_NULL, 0)) , totalSize_(0) , ret_(Z_OK) , useGzip_(useGzip) , readGzipHeader_(false) { z_.zalloc = Z_NULL; z_.zfree = Z_NULL; z_.opaque = Z_NULL; z_.next_in = 0; z_.avail_in = 0; if (useGzip_) { if (inflateInit2(&z_, -MAX_WBITS) != Z_OK) { throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit2") << std::string(z_.msg); } } else { if (inflateInit(&z_) != Z_OK) { throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit") << std::string(z_.msg); } } } ~ZlibDecompressorT() { inflateEnd(&z_); } /* decompress is @param str [out] decompressed data @param str [out] max buf size @return written size */ size_t readSome(void *buf, size_t _size) { assert(_size < (1U << 31)); uint32_t size = (uint32_t)_size; if (size == 0) return 0; if (useGzip_ && !readGzipHeader_) { readGzipHeader(); readGzipHeader_ = true; } z_.next_out = (Bytef*)buf; z_.avail_out = size; do { if (z_.avail_in == 0) { z_.avail_in = (uint32_t)In::readSome(is_, buf_, maxBufSize); if (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0; z_.next_in = (Bytef*)buf_; } ret_ = inflate(&z_, Z_NO_FLUSH); if (ret_ == Z_STREAM_END) break; if (ret_ != Z_OK) { throw cybozu::Exception("zlib:readSome:decompress") << std::string(z_.msg); } } while (size == z_.avail_out); return size - z_.avail_out; } void read(void *buf, size_t size) { char *p = (char *)buf; while (size > 0) { size_t readSize = readSome(p, size); if (readSize == 0) throw cybozu::Exception("zlib:read"); p += readSize; size -= readSize; } } }; } // cybozu <commit_msg>use same format of exception message<commit_after>#pragma once /** @file @brief zlib compressor and decompressor class Copyright (C) 2009 Cybozu Labs, Inc., all rights reserved. */ #include <cybozu/exception.hpp> #include <cybozu/endian.hpp> #include <cybozu/stream_fwd.hpp> #include <assert.h> #include <stdio.h> #include <zlib.h> #ifdef _MSC_VER #ifdef _DLL_CPPLIB #pragma comment(lib, "zlib_md.lib") #else #pragma comment(lib, "zlib_mt.lib") #endif #endif namespace cybozu { namespace zlib_local { const int DEF_MEM_LEVEL = 8; } // zlib_local /** zlib compressor class OutputStream must have size_t write(const char *buf, size_t size); */ template<class OutputStream, size_t maxBufSize = 2048> class ZlibCompressorT { OutputStream& os_; unsigned int crc_; unsigned int totalSize_; /* mod 2^32 */ z_stream z_; char buf_[maxBufSize]; bool isFlushCalled_; const bool useGzip_; ZlibCompressorT(const ZlibCompressorT&); void operator=(const ZlibCompressorT&); public: /** @param os [in] output stream @param useGzip [in] useGzip if true, use deflate if false @note useGzip option is not fully tested, so default off */ ZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION) : os_(os) , crc_(crc32(0L, Z_NULL, 0)) , totalSize_(0) , isFlushCalled_(false) , useGzip_(useGzip) { z_.zalloc = Z_NULL; z_.zfree = Z_NULL; z_.opaque = Z_NULL; if (useGzip_) { if (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit2") << std::string(z_.msg); } char header[] = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03"; /* OS_CODE = 0x03(Unix) */ write_os(header, 10); } else { if (deflateInit(&z_, compressionLevel) != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit") << std::string(z_.msg); } } } ~ZlibCompressorT() { if (!isFlushCalled_) { try { flush(); } catch (std::exception& e) { fprintf(stderr, "zlib:ZlibCompressor:flush:exception:%s\n", e.what()); } catch (...) { fprintf(stderr, "zlib:ZlibCompressor:flush:unknown exception\n"); } } deflateEnd(&z_); } /* compress buf @param buf [in] input data @param size [in] input data size */ void write(const void *buf, size_t _size) { if (_size >= (1u << 31)) throw cybozu::Exception("zlib:ZlibCompressor:write:too large size") << _size; uint32_t size = (uint32_t)_size; if (useGzip_) { crc_ = crc32(crc_, (const Bytef *)buf, size); totalSize_ += (unsigned int)size; } z_.next_in = (Bytef*)const_cast<char*>((const char*)buf); z_.avail_in = size; while (z_.avail_in > 0) { z_.next_out = (Bytef*)buf_; z_.avail_out = maxBufSize; int ret = deflate(&z_, Z_NO_FLUSH); if (ret != Z_STREAM_END && ret != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressor:exec:compress") << std::string(z_.msg); } write_os(buf_, maxBufSize - z_.avail_out); if (ret == Z_STREAM_END) break; } } void flush() { isFlushCalled_ = true; z_.next_in = 0; z_.avail_in = 0; for (;;) { z_.next_out = (Bytef*)buf_; z_.avail_out = maxBufSize; int ret = deflate(&z_, Z_FINISH); if (ret != Z_STREAM_END && ret != Z_OK) { throw cybozu::Exception("zlib:ZlibCompressor:flush") << std::string(z_.msg); } write_os(buf_, sizeof(buf_) - z_.avail_out); if (ret == Z_STREAM_END) break; } if (useGzip_) { char tail[8]; cybozu::Set32bitAsLE(&tail[0], crc_); cybozu::Set32bitAsLE(&tail[4], totalSize_); write_os(tail, sizeof(tail)); } } private: void write_os(const char *buf, size_t size) { cybozu::OutputStreamTag<OutputStream>::write(os_, buf, size); } }; /** zlib decompressor class InputStream must have size_t read(char *str, size_t size); */ template<class InputStream, size_t maxBufSize = 2048> class ZlibDecompressorT { typedef cybozu::InputStreamTag<InputStream> In; InputStream& is_; unsigned int crc_; unsigned int totalSize_; /* mod 2^32 */ z_stream z_; int ret_; char buf_[maxBufSize]; const bool useGzip_; bool readGzipHeader_; void readAll(char *buf, size_t size) { In::read(is_, buf, size); } void skipToZero() { for (;;) { char buf[1]; readAll(buf, 1); if (buf[0] == '\0') break; } } void skip(int size) { for (int i = 0 ; i < size; i++) { char buf[1]; readAll(buf, 1); } } void readGzipHeader() { char header[10]; readAll(header, sizeof(header)); enum { FHCRC = 1 << 1, FEXTRA = 1 << 2, FNAME = 1 << 3, FCOMMENT = 1 << 4, RESERVED = 7 << 5, }; char flg = header[3]; if (header[0] == '\x1f' && header[1] == '\x8b' && header[2] == Z_DEFLATED && !(flg & RESERVED)) { if (flg & FEXTRA) { char xlen[2]; readAll(xlen, sizeof(xlen)); int size = cybozu::Get16bitAsLE(xlen); skip(size); } if (flg & FNAME) { skipToZero(); } if (flg & FCOMMENT) { skipToZero(); } if (flg & FHCRC) { skip(2); } return; } throw cybozu::Exception("zlib:ZlibDecompressorT:readGzipHeader:bad gzip header") << std::string(header, 10); } ZlibDecompressorT(const ZlibDecompressorT&); void operator=(const ZlibDecompressorT&); public: /** @param os [in] input stream @param useGzip [in] useGzip if true, use deflate if false @note useGzip option is not fully tested, so default off */ ZlibDecompressorT(InputStream& is, bool useGzip = false) : is_(is) , crc_(crc32(0L, Z_NULL, 0)) , totalSize_(0) , ret_(Z_OK) , useGzip_(useGzip) , readGzipHeader_(false) { z_.zalloc = Z_NULL; z_.zfree = Z_NULL; z_.opaque = Z_NULL; z_.next_in = 0; z_.avail_in = 0; if (useGzip_) { if (inflateInit2(&z_, -MAX_WBITS) != Z_OK) { throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit2") << std::string(z_.msg); } } else { if (inflateInit(&z_) != Z_OK) { throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit") << std::string(z_.msg); } } } ~ZlibDecompressorT() { inflateEnd(&z_); } /* decompress is @param str [out] decompressed data @param str [out] max buf size @return read size */ size_t readSome(void *buf, size_t _size) { if (_size == 0) return 0; if (_size >= (1u << 31)) throw cybozu::Exception("zlib:ZlibDecompressorT:readSome:too large size") << _size; uint32_t size = (uint32_t)_size; if (useGzip_ && !readGzipHeader_) { readGzipHeader(); readGzipHeader_ = true; } z_.next_out = (Bytef*)buf; z_.avail_out = size; do { if (z_.avail_in == 0) { z_.avail_in = (uint32_t)In::readSome(is_, buf_, maxBufSize); if (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0; z_.next_in = (Bytef*)buf_; } ret_ = inflate(&z_, Z_NO_FLUSH); if (ret_ == Z_STREAM_END) break; if (ret_ != Z_OK) { throw cybozu::Exception("zlib:ZlibDecompressorT:readSome:inflate") << std::string(z_.msg); } } while (size == z_.avail_out); return size - z_.avail_out; } void read(void *buf, size_t size) { char *p = (char *)buf; while (size > 0) { size_t readSize = readSome(p, size); if (readSize == 0) throw cybozu::Exception("zlib:ZlibDecompressorT:read"); p += readSize; size -= readSize; } } }; } // cybozu <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \brief Simple CRTP class to implement a visitor * \tparam D the type of the derived visitor class * * The default implementation is simply to visit the whole tree while not doing anything */ template <typename D, bool V_T = true, bool V_V = true> struct etl_visitor { using derived_t = D; ///< The derived type /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const noexcept { return *static_cast<const derived_t*>(this); } /*! * \brief Visit the given unary expression * \param v The unary expression */ template <typename T, typename Expr, typename UnaryOp> void operator()(etl::unary_expr<T, Expr, UnaryOp>& v) const { as_derived()(v.value()); } /*! * \brief Visit the given binary expression * \param v The binary expression */ template <typename T, typename LeftExpr, typename BinaryOp, typename RightExpr> void operator()(etl::binary_expr<T, LeftExpr, BinaryOp, RightExpr>& v) const { as_derived()(v.lhs()); as_derived()(v.rhs()); } /*! * \brief Visit the given view * \param view The view */ template <typename T, cpp_enable_if(etl::is_view<T>::value)> void operator()(T& view) const { as_derived()(view.value()); } /*! * \brief Visit the given matrix-multiplication transformer * \param transformer The matrix-multiplication transformer */ template <typename L, typename R> void operator()(mm_mul_transformer<L, R>& transformer) const { as_derived()(transformer.lhs()); as_derived()(transformer.rhs()); } /*! * \brief Visit the given transformer * \param transformer The transformer */ template <typename T, cpp_enable_if(etl::is_transformer<T>::value)> void operator()(T& transformer) const { as_derived()(transformer.value()); } /*! * \brief Visit the given temporary unary expr * \param v The temporary unary expr */ template <typename T, cpp_enable_if_cst(V_T && is_temporary_unary_expr<T>::value)> void operator()(T& v){ as_derived()(v.a()); } /*! * \brief Visit the given temporary binary expr * \param v The temporary binary expr */ template <typename T, cpp_enable_if_cst(V_T && is_temporary_binary_expr<T>::value)> void operator()(T& v) const { as_derived()(v.a()); as_derived()(v.b()); } /*! * \brief Visit the given generator expr * \param v The the generator expr */ template <typename Generator> void operator()(const generator_expr<Generator>& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given magic view. * \param v The the magic view. */ template <typename T, cpp_enable_if(etl::is_magic_view<T>::value)> void operator()(const T& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given value class. * \param v The the value class. */ template <typename T, cpp_enable_if(V_V && etl::is_etl_value<T>::value)> void operator()(const T& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given scalar. * \param v The the scalar. */ template <typename T> void operator()(const etl::scalar<T>& v) const { cpp_unused(v); //Leaf } }; /*! * \brief Apply the given visitor to the given expression * \param visitor The visitor to use * \param expr The expression to visit */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(const Visitor& visitor, Expr& expr) { visitor(expr); } /*! * \brief Apply the given visitor to the given expression * \param visitor The visitor to use * \param expr The expression to visit */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Visitor& visitor, Expr& expr) { visitor(expr); } /*! * \brief Apply the given visitor to the given expression * \param expr The expression to visit * \tparam Visitor The visitor to use, will be constructed on the stack */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Expr& expr) { Visitor visitor; visitor(expr); } template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(const Visitor& /*visitor*/, Expr& /*expr*/) {} template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Visitor& /*visitor*/, Expr& /*expr*/) {} template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Expr& /*expr*/) {} } //end of namespace etl <commit_msg>Document disabled functions<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \brief Simple CRTP class to implement a visitor * \tparam D the type of the derived visitor class * * The default implementation is simply to visit the whole tree while not doing anything */ template <typename D, bool V_T = true, bool V_V = true> struct etl_visitor { using derived_t = D; ///< The derived type /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const noexcept { return *static_cast<const derived_t*>(this); } /*! * \brief Visit the given unary expression * \param v The unary expression */ template <typename T, typename Expr, typename UnaryOp> void operator()(etl::unary_expr<T, Expr, UnaryOp>& v) const { as_derived()(v.value()); } /*! * \brief Visit the given binary expression * \param v The binary expression */ template <typename T, typename LeftExpr, typename BinaryOp, typename RightExpr> void operator()(etl::binary_expr<T, LeftExpr, BinaryOp, RightExpr>& v) const { as_derived()(v.lhs()); as_derived()(v.rhs()); } /*! * \brief Visit the given view * \param view The view */ template <typename T, cpp_enable_if(etl::is_view<T>::value)> void operator()(T& view) const { as_derived()(view.value()); } /*! * \brief Visit the given matrix-multiplication transformer * \param transformer The matrix-multiplication transformer */ template <typename L, typename R> void operator()(mm_mul_transformer<L, R>& transformer) const { as_derived()(transformer.lhs()); as_derived()(transformer.rhs()); } /*! * \brief Visit the given transformer * \param transformer The transformer */ template <typename T, cpp_enable_if(etl::is_transformer<T>::value)> void operator()(T& transformer) const { as_derived()(transformer.value()); } /*! * \brief Visit the given temporary unary expr * \param v The temporary unary expr */ template <typename T, cpp_enable_if_cst(V_T && is_temporary_unary_expr<T>::value)> void operator()(T& v){ as_derived()(v.a()); } /*! * \brief Visit the given temporary binary expr * \param v The temporary binary expr */ template <typename T, cpp_enable_if_cst(V_T && is_temporary_binary_expr<T>::value)> void operator()(T& v) const { as_derived()(v.a()); as_derived()(v.b()); } /*! * \brief Visit the given generator expr * \param v The the generator expr */ template <typename Generator> void operator()(const generator_expr<Generator>& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given magic view. * \param v The the magic view. */ template <typename T, cpp_enable_if(etl::is_magic_view<T>::value)> void operator()(const T& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given value class. * \param v The the value class. */ template <typename T, cpp_enable_if(V_V && etl::is_etl_value<T>::value)> void operator()(const T& v) const { cpp_unused(v); //Leaf } /*! * \brief Visit the given scalar. * \param v The the scalar. */ template <typename T> void operator()(const etl::scalar<T>& v) const { cpp_unused(v); //Leaf } }; /*! * \brief Apply the given visitor to the given expression * \param visitor The visitor to use * \param expr The expression to visit */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(const Visitor& visitor, Expr& expr) { visitor(expr); } /*! * \brief Apply the given visitor to the given expression * \param visitor The visitor to use * \param expr The expression to visit */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Visitor& visitor, Expr& expr) { visitor(expr); } /*! * \brief Apply the given visitor to the given expression * \param expr The expression to visit * \tparam Visitor The visitor to use, will be constructed on the stack */ template <typename Visitor, typename Expr, cpp_enable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Expr& expr) { Visitor visitor; visitor(expr); } /*! * \copydoc apply_visitor */ template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(const Visitor& /*visitor*/, Expr& /*expr*/) {} /*! * \copydoc apply_visitor */ template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Visitor& /*visitor*/, Expr& /*expr*/) {} /*! * \copydoc apply_visitor */ template <typename Visitor, typename Expr, cpp_disable_if(Visitor::template enabled<Expr>::value)> void apply_visitor(Expr& /*expr*/) {} } //end of namespace etl <|endoftext|>
<commit_before>#include <mapbox/geojsonvt/transform.hpp> #include <cmath> namespace mapbox { namespace geojsonvt { TilePoint Transform::transformPoint( const ProjectedPoint& p, uint16_t extent, uint32_t z2, uint32_t tx, uint32_t ty) { int16_t x = ::round(extent * (p.x * z2 - tx)); int16_t y = ::round(extent * (p.y * z2 - ty)); return TilePoint(x, y); } const Tile& Transform::transformTile(Tile& tile, uint16_t extent) { if (tile.transformed) { return tile; } const uint32_t z2 = tile.z2; const uint32_t tx = tile.tx; const uint32_t ty = tile.ty; for (auto& feature : tile.features) { const auto& geom = feature.geometry; const auto type = feature.type; if (type == TileFeatureType::Point) { auto& tileGeom = feature.tileGeometry.get<TilePoints>(); auto const& projected_points = geom.get<ProjectedPoints>(); tileGeom.reserve(projected_points.size()); for (const auto& pt : projected_points) { tileGeom.push_back(transformPoint(pt, extent, z2, tx, ty)); } } else { feature.tileGeometry.set<TileRings>(); auto& tileGeom = feature.tileGeometry.get<TileRings>(); for (const auto& r : geom.get<ProjectedRings>()) { TilePoints ring; ring.reserve(r.points.size()); for (const auto& p : r.points) { ring.push_back(transformPoint(p, extent, z2, tx, ty)); } tileGeom.push_back(std::move(ring)); } } } tile.transformed = true; return tile; } } // namespace geojsonvt } // namespace mapbox <commit_msg>optimize transformTile<commit_after>#include <mapbox/geojsonvt/transform.hpp> #include <cmath> namespace mapbox { namespace geojsonvt { inline int16_t trans_x(double x, uint16_t extent, uint32_t z2, uint32_t tx) { return std::round(extent * (x * z2 - tx)); } inline int16_t trans_y(double y, uint16_t extent, uint32_t z2, uint32_t ty) { return std::round(extent * (y * z2 - ty)); } TilePoint Transform::transformPoint( const ProjectedPoint& p, uint16_t extent, uint32_t z2, uint32_t tx, uint32_t ty) { int16_t x = trans_x(p.x, extent, z2,tx); int16_t y = trans_y(p.y, extent, z2,ty); return TilePoint(x, y); } const Tile& Transform::transformTile(Tile& tile, uint16_t extent) { if (tile.transformed) { return tile; } const uint32_t z2 = tile.z2; const uint32_t tx = tile.tx; const uint32_t ty = tile.ty; for (auto& feature : tile.features) { const auto& geom = feature.geometry; const auto type = feature.type; if (type == TileFeatureType::Point) { auto& tileGeom = feature.tileGeometry.get<TilePoints>(); auto const& projected_points = geom.get<ProjectedPoints>(); tileGeom.reserve(projected_points.size()); for (const auto& pt : projected_points) { tileGeom.emplace_back(trans_x(pt.x,extent,z2,tx),trans_x(pt.y,extent,z2,ty)); } } else { feature.tileGeometry.set<TileRings>(); auto& tileGeom = feature.tileGeometry.get<TileRings>(); for (const auto& r : geom.get<ProjectedRings>()) { TilePoints ring; ring.reserve(r.points.size()); for (const auto& pt : r.points) { ring.emplace_back(trans_x(pt.x,extent,z2,tx),trans_x(pt.y,extent,z2,ty)); } tileGeom.push_back(std::move(ring)); } } } tile.transformed = true; return tile; } } // namespace geojsonvt } // namespace mapbox <|endoftext|>
<commit_before>#ifndef TMXPP_FRAME_HPP #define TMXPP_FRAME_HPP #include <chrono> #include <tmxpp/Constrained.hpp> #include <tmxpp/Tile_id.hpp> namespace tmxpp { struct Frame { using Duration = std::chrono::milliseconds; Local_tile_id id; Non_negative<Duration> duration; }; inline bool operator==(Frame l, Frame r) noexcept { return l.id == r.id && l.duration == r.duration; } inline bool operator!=(Frame l, Frame r) noexcept { return !(l == r); } } // namespace tmxpp #endif // TMXPP_FRAME_HPP <commit_msg>Change Frame::Duration::rep to int<commit_after>#ifndef TMXPP_FRAME_HPP #define TMXPP_FRAME_HPP #include <chrono> #include <tmxpp/Constrained.hpp> #include <tmxpp/Tile_id.hpp> namespace tmxpp { struct Frame { using Duration = std::chrono::duration<int, std::chrono::milliseconds::period>; Local_tile_id id; Non_negative<Duration> duration; }; inline bool operator==(Frame l, Frame r) noexcept { return l.id == r.id && l.duration == r.duration; } inline bool operator!=(Frame l, Frame r) noexcept { return !(l == r); } } // namespace tmxpp #endif // TMXPP_FRAME_HPP <|endoftext|>
<commit_before>#include "servermanager.h" #include <qjsonarray> #include <qjsonobject> #include <qjsonvalue> #include <qdatetime> ServerManager::ServerManager(ClientDb clientDb) : clientDatabase(clientDb) { } QJsonObject ServerManager::exportOnlineUsersJson() { QList<client*> *clientList = clientDatabase.getClientsList(); QJsonObject clientsJson; QJsonArray clientsArray; for each (client* client in *clientList) { if (client->loggedIn && (client->loginValidUntil.toUTC() < QDateTime::currentDateTimeUtc())) { QJsonObject singleClient { { "nick", QJsonValue(client->clientNick) }, { "address", QJsonValue(client->address) }, { "port", QJsonValue(client->listeningPort)} }; clientsArray << singleClient; } } clientsJson.insert("users", clientsArray); return clientsJson; }<commit_msg>small Json fix<commit_after>#include "servermanager.h" #include <qjsonarray> #include <qjsonobject> #include <qjsonvalue> #include <qdatetime> ServerManager::ServerManager(ClientDb clientDb) : clientDatabase(clientDb) { } QJsonObject ServerManager::exportOnlineUsersJson() { QList<client*> *clientList = clientDatabase.getClientsList(); QJsonObject clientsJson; QJsonArray clientsArray; for each (client* client in *clientList) { if (client->loggedIn && (client->loginValidUntil.toUTC() > QDateTime::currentDateTimeUtc())) { QJsonObject singleClient { { "nick", QJsonValue(client->clientNick) }, { "address", QJsonValue(client->address) }, { "port", QJsonValue(client->listeningPort)} }; clientsArray << singleClient; } } clientsJson.insert("users", clientsArray); return clientsJson; }<|endoftext|>
<commit_before>#include <Poco/UUIDGenerator.h> #include <Poco/DateTime.h> #include "dao/DeviceDao.h" #include "ui/UIMockInit.h" BEEEON_OBJECT(UIMockInit, BeeeOn::UIMockInit) using namespace Poco; using namespace BeeeOn; void UIMockInit::initUsers() { User joeDoeUser(UserID::random()); joeDoeUser.setFirstName("Joe"); joeDoeUser.setLastName("Doe"); m_userDao->create(joeDoeUser); Identity joeDoe0; joeDoe0.setEmail("joe.doe@example.org"); m_identityDao->create(joeDoe0); VerifiedIdentity preparedJoeDoe0; preparedJoeDoe0.setIdentity(joeDoe0); preparedJoeDoe0.setUser(joeDoeUser); preparedJoeDoe0.setProvider("prepared"); m_verifiedIdentityDao->create(preparedJoeDoe0); User johnsmithUser(UserID::random()); johnsmithUser.setFirstName("John"); johnsmithUser.setLastName("Smith"); m_userDao->create(johnsmithUser); Identity johnsmith0; johnsmith0.setEmail("john.smith@example.org"); m_identityDao->create(johnsmith0); VerifiedIdentity preparedJohnSmith0; preparedJohnSmith0.setIdentity(johnsmith0); preparedJohnSmith0.setUser(johnsmithUser); preparedJohnSmith0.setProvider("prepared"); m_verifiedIdentityDao->create(preparedJohnSmith0); } void UIMockInit::initGateways() { GatewayID id(GatewayID::parse("1284174504043136")); Gateway gateway(id); gateway.setName("Joe Doe's Gateway"); m_gatewayDao->insert(gateway); GatewayID id2(GatewayID::parse("1780053541714013")); Gateway gateway2(id2); gateway2.setName("Gateway To Un/assign"); m_gatewayDao->insert(gateway2); } void UIMockInit::initDevices() { Gateway gateway(GatewayID::parse("1284174504043136")); Device temperature(DeviceID::random(0x41)); temperature.setName("Temperature"); temperature.setGateway(gateway); temperature.setType(0); temperature.setRefresh(5); temperature.setBattery(50.0); temperature.setSignal(90.0); temperature.setFirstSeen(DateTime(2015, 4, 9, 15, 43, 1)); temperature.setLastSeen(DateTime(2016, 9, 1, 13, 27, 18)); temperature.setActiveSince(DateTime(2015, 5, 2, 17, 59, 59)); m_deviceDao->insert(temperature, gateway); Device humidity(DeviceID::random(0x42)); humidity.setName("Humidity"); humidity.setGateway(gateway); humidity.setType(0); humidity.setRefresh(1000); humidity.setBattery(99.0); humidity.setSignal(45.0); humidity.setFirstSeen(DateTime(2016, 8, 8, 8, 8, 8)); humidity.setLastSeen(DateTime()); humidity.setActiveSince(DateTime(2016, 8, 9, 8, 9, 8)); m_deviceDao->insert(humidity, gateway); Device multi(DeviceID::random(0x43)); multi.setName("Multi-sensor"); multi.setGateway(gateway); multi.setType(0); multi.setRefresh(15); multi.setBattery(90.0); multi.setSignal(90.0); multi.setFirstSeen(DateTime(2016, 9, 10, 11, 12, 13)); multi.setLastSeen(DateTime(2016, 10, 10, 11, 11, 22)); multi.setActiveSince(DateTime(2016, 9, 10, 11, 30, 1)); m_deviceDao->insert(multi, gateway); } void UIMockInit::injectionDone() { initUsers(); initGateways(); initDevices(); } <commit_msg>UIMockInit: prepare uninitialized device for testing<commit_after>#include <Poco/UUIDGenerator.h> #include <Poco/DateTime.h> #include <Poco/Timespan.h> #include "dao/DeviceDao.h" #include "ui/UIMockInit.h" BEEEON_OBJECT(UIMockInit, BeeeOn::UIMockInit) using namespace Poco; using namespace BeeeOn; void UIMockInit::initUsers() { User joeDoeUser(UserID::random()); joeDoeUser.setFirstName("Joe"); joeDoeUser.setLastName("Doe"); m_userDao->create(joeDoeUser); Identity joeDoe0; joeDoe0.setEmail("joe.doe@example.org"); m_identityDao->create(joeDoe0); VerifiedIdentity preparedJoeDoe0; preparedJoeDoe0.setIdentity(joeDoe0); preparedJoeDoe0.setUser(joeDoeUser); preparedJoeDoe0.setProvider("prepared"); m_verifiedIdentityDao->create(preparedJoeDoe0); User johnsmithUser(UserID::random()); johnsmithUser.setFirstName("John"); johnsmithUser.setLastName("Smith"); m_userDao->create(johnsmithUser); Identity johnsmith0; johnsmith0.setEmail("john.smith@example.org"); m_identityDao->create(johnsmith0); VerifiedIdentity preparedJohnSmith0; preparedJohnSmith0.setIdentity(johnsmith0); preparedJohnSmith0.setUser(johnsmithUser); preparedJohnSmith0.setProvider("prepared"); m_verifiedIdentityDao->create(preparedJohnSmith0); } void UIMockInit::initGateways() { GatewayID id(GatewayID::parse("1284174504043136")); Gateway gateway(id); gateway.setName("Joe Doe's Gateway"); m_gatewayDao->insert(gateway); GatewayID id2(GatewayID::parse("1780053541714013")); Gateway gateway2(id2); gateway2.setName("Gateway To Un/assign"); m_gatewayDao->insert(gateway2); } void UIMockInit::initDevices() { Gateway gateway(GatewayID::parse("1284174504043136")); Device temperature(DeviceID::random(0x41)); temperature.setName("Temperature"); temperature.setGateway(gateway); temperature.setType(0); temperature.setRefresh(5); temperature.setBattery(50.0); temperature.setSignal(90.0); temperature.setFirstSeen(DateTime(2015, 4, 9, 15, 43, 1)); temperature.setLastSeen(DateTime(2016, 9, 1, 13, 27, 18)); temperature.setActiveSince(DateTime(2015, 5, 2, 17, 59, 59)); m_deviceDao->insert(temperature, gateway); Device humidity(DeviceID::random(0x42)); humidity.setName("Humidity"); humidity.setGateway(gateway); humidity.setType(0); humidity.setRefresh(1000); humidity.setBattery(99.0); humidity.setSignal(45.0); humidity.setFirstSeen(DateTime(2016, 8, 8, 8, 8, 8)); humidity.setLastSeen(DateTime()); humidity.setActiveSince(DateTime(2016, 8, 9, 8, 9, 8)); m_deviceDao->insert(humidity, gateway); Device multi(DeviceID::random(0x43)); multi.setName("Multi-sensor"); multi.setGateway(gateway); multi.setType(0); multi.setRefresh(15); multi.setBattery(90.0); multi.setSignal(90.0); multi.setFirstSeen(DateTime(2016, 9, 10, 11, 12, 13)); multi.setLastSeen(DateTime(2016, 10, 10, 11, 11, 22)); multi.setActiveSince(DateTime(2016, 9, 10, 11, 30, 1)); m_deviceDao->insert(multi, gateway); Device unknown(DeviceID::random(0x44)); unknown.setName("Unknown"); unknown.setGateway(gateway); unknown.setType(0); unknown.setRefresh(20); unknown.setFirstSeen(DateTime() - Timespan(100, 0)); unknown.setLastSeen(DateTime()); m_deviceDao->insert(unknown, gateway); } void UIMockInit::injectionDone() { initUsers(); initGateways(); initDevices(); } <|endoftext|>
<commit_before>// GraphicView.cpp : implementation file // #include "pch.h" #include "agalia.h" #include "GraphicView.h" #include "ImageDrawD2D.h" #include "ImageDrawGDI.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // GraphicView IMPLEMENT_DYNAMIC(GraphicView, CWnd) GraphicView::GraphicView() { } GraphicView::~GraphicView() { if (v) { auto temp = v; v = nullptr; delete temp; } } void GraphicView::init_window(void) { if (::IsWindow(GetSafeHwnd())) { DestroyWindow(); } Create( ::AfxRegisterWndClass(CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW)), _T(""), WS_CHILD | WS_VISIBLE | WS_BORDER, CRect(0, 0, 0, 0), ::AfxGetMainWnd(), (UINT)-1); } void GraphicView::reset_renderer(int mode) { if (0 <= mode) { renderingMode = mode; } if (v) { auto temp = v; v = nullptr; temp->detach(); delete temp; init_window(); } if (renderingMode == 0) { v = new ImageDrawGDI; } else { v = new ImageDrawD2D; } } void GraphicView::reset_content(agaliaContainer* image) { if (!v) return; v->attach(GetSafeHwnd()); v->reset_content(image, colorManagementMode); render(); if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) Invalidate(FALSE); } void GraphicView::reset_color_profile(int mode) { if (0 <= mode) { colorManagementMode = mode; } if (!v) return; v->reset_color_profile(colorManagementMode); if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) Invalidate(FALSE); } void GraphicView::render(void) { DWORD bkcolor = ::GetSysColor(COLOR_APPWORKSPACE); HRESULT hr = E_FAIL; if (v) { hr = v->render(bkcolor); } if (FAILED(hr)) { if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) { CRect rc; GetClientRect(&rc); CClientDC dc(this); dc.FillSolidRect(&rc, bkcolor); } } } BEGIN_MESSAGE_MAP(GraphicView, CWnd) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_SIZE() ON_WM_PAINT() END_MESSAGE_MAP() // GraphicView message handlers int GraphicView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void GraphicView::OnDestroy() { if (v) v->detach(); CWnd::OnDestroy(); } void GraphicView::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (v) { v->update_for_window_size_change(); render(); } } void GraphicView::OnPaint() { CPaintDC dc(this); DWORD bkcolor = ::GetSysColor(COLOR_APPWORKSPACE); HRESULT hr = E_FAIL; if (v) { hr = v->render(bkcolor); } if (FAILED(hr)) { dc.FillSolidRect(&dc.m_ps.rcPaint, bkcolor); } } <commit_msg>Avoid problem with loading image using D2D<commit_after>// GraphicView.cpp : implementation file // #include "pch.h" #include "agalia.h" #include "GraphicView.h" #include "ImageDrawD2D.h" #include "ImageDrawGDI.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // GraphicView IMPLEMENT_DYNAMIC(GraphicView, CWnd) GraphicView::GraphicView() { } GraphicView::~GraphicView() { if (v) { auto temp = v; v = nullptr; delete temp; } } void GraphicView::init_window(void) { if (::IsWindow(GetSafeHwnd())) { DestroyWindow(); } Create( ::AfxRegisterWndClass(CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW)), _T(""), WS_CHILD | WS_VISIBLE | WS_BORDER, CRect(0, 0, 0, 0), ::AfxGetMainWnd(), (UINT)-1); } void GraphicView::reset_renderer(int mode) { if (0 <= mode) { renderingMode = mode; } if (v) { auto temp = v; v = nullptr; temp->detach(); delete temp; init_window(); } if (renderingMode == 0) { v = new ImageDrawGDI; } else { v = new ImageDrawD2D; } } void GraphicView::reset_content(agaliaContainer* image) { if (!v) return; v->attach(GetSafeHwnd()); v->reset_content(image, colorManagementMode); if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) Invalidate(FALSE); } void GraphicView::reset_color_profile(int mode) { if (0 <= mode) { colorManagementMode = mode; } if (!v) return; v->reset_color_profile(colorManagementMode); if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) Invalidate(FALSE); } void GraphicView::render(void) { DWORD bkcolor = ::GetSysColor(COLOR_APPWORKSPACE); HRESULT hr = E_FAIL; if (v) { hr = v->render(bkcolor); } if (FAILED(hr)) { if (::IsWindow(GetSafeHwnd()) && IsWindowVisible()) { CRect rc; GetClientRect(&rc); CClientDC dc(this); dc.FillSolidRect(&rc, bkcolor); } } } BEGIN_MESSAGE_MAP(GraphicView, CWnd) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_SIZE() ON_WM_PAINT() END_MESSAGE_MAP() // GraphicView message handlers int GraphicView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void GraphicView::OnDestroy() { if (v) v->detach(); CWnd::OnDestroy(); } void GraphicView::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (v) { v->update_for_window_size_change(); render(); } } void GraphicView::OnPaint() { CPaintDC dc(this); DWORD bkcolor = ::GetSysColor(COLOR_APPWORKSPACE); HRESULT hr = E_FAIL; if (v) { hr = v->render(bkcolor); } if (FAILED(hr)) { dc.FillSolidRect(&dc.m_ps.rcPaint, bkcolor); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: objshimp.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: kz $ $Date: 2003-08-27 16:23:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SFX_OBJSHIMP_HXX #define _SFX_OBJSHIMP_HXX #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _DATETIME_HXX #include <tools/datetime.hxx> #endif #include <svtools/securityoptions.hxx> #include "objsh.hxx" #include "bitset.hxx" namespace svtools { class AsynchronLink; } //==================================================================== DBG_NAMEEX(SfxObjectShell); class SfxViewFrame; struct MarkData_Impl { String aMark; String aUserData; SfxViewFrame* pFrame; }; class SfxFrame; class SfxDialogLibraryContainer; class SfxScriptLibraryContainer; class SfxImageManager; class SfxToolBoxConfig; class SfxAcceleratorManager; struct SfxObjectShell_Impl { SfxAcceleratorManager* pAccMgr; SfxDocumentInfo* pDocInfo; SfxConfigManager* pCfgMgr; SfxInPlaceObject* pInPlaceObj; // das dazugeh"orige SO2-Objekt, falls this ein SfxInPlaceObject ist BasicManager* pBasicMgr; // Doc-BASIC oder 0 SfxScriptLibraryContainer* pBasicLibContainer; SfxDialogLibraryContainer* pDialogLibContainer; SfxProgress* pProgress; String aTitle; String aTempName; DateTime nTime; sal_uInt16 nVisualDocumentNumber; sal_Bool bTemplateConfig:1, bInList:1, // ob per First/Next erreichbar bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten bIsSaving:1, bPasswd:1, bIsTmp:1, bIsNamedVisible:1, bDidWarnFormat:1, // sal_True, falls schon wg. speichern in Fremformat gewarnt wurde bSetStandardName:1, // sal_True, falls im FileSave Dialog xxxx.sdw im Standardverzeichnis vorgeschlagen werden soll. bDidDangerousSave:1, // sal_True, falls ein Save in ein Alienformat durchgefuehrt wurde bIsTemplate:1, bIsAbortingImport:1, // Importvorgang soll abgebrochen werden. bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs. bInPrepareClose : 1, bPreparedForClose : 1, bWaitingForPicklist : 1,// Muss noch in die Pickliste bModuleSearched : 1, bIsBasicDefault : 1, bIsHelpObjSh : 1, bForbidCaching : 1, bForbidReload : 1, bSupportsEventMacros: 1, bLoadingWindows: 1, bBasicInitialized :1, bHidden :1, // indicates a hidden view shell bIsPrintJobCancelable :1; // Stampit disable/enable cancel button for print jobs ... default = true = enable! String aNewName; // Der Name, unter dem das Doc gespeichert // werden soll IndexBitSet aBitSet; sal_uInt32 lErr; sal_uInt16 nEventId; // falls vor Activate noch ein // Open/Create gesendet werden mu/s sal_Bool bDoNotTouchDocInfo; AutoReloadTimer_Impl *pReloadTimer; MarkData_Impl* pMarkData; sal_uInt16 nLoadedFlags; String aMark; Size aViewSize; // wird leider vom Writer beim sal_Bool bInFrame; // HTML-Import gebraucht sal_Bool bModalMode; sal_Bool bRunningMacro; sal_Bool bReloadAvailable; sal_uInt16 nAutoLoadLocks; SfxModule* pModule; SfxFrame* pFrame; SfxImageManager* pImageManager; SfxToolBoxConfig* pTbxConfig; SfxEventConfigItem_Impl* pEventConfig; SfxObjectShellFlags eFlags; svtools::AsynchronLink* pCloser; String aBaseURL; sal_Bool bReadOnlyUI; SvRefBaseRef xHeaderAttributes; sal_Bool bHiddenLockedByAPI; sal_Bool bInCloseEvent; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel; sal_uInt16 nStyleFilter; sal_Int16 nMacroMode; sal_Bool bDisposing; SfxObjectShell_Impl() : pAccMgr(0), nTime(), bIsTmp( sal_False), bClosing( sal_False), bSetInPlaceObj( sal_False), bPasswd( sal_False), pInPlaceObj( 0), pBasicMgr( 0), pBasicLibContainer( 0 ), pDialogLibContainer( 0 ), pProgress( 0), nVisualDocumentNumber( USHRT_MAX), bIsSaving( sal_False), bIsNamedVisible( sal_False), pCfgMgr( 0), bTemplateConfig( sal_False), bDidWarnFormat( sal_False), bDidDangerousSave(sal_False), bIsBasicDefault( sal_True ), bIsTemplate(sal_False), lErr(ERRCODE_NONE), nEventId ( 0), pDocInfo ( 0), bIsAbortingImport ( sal_False), bInList ( sal_False), bImportDone ( sal_False), pReloadTimer ( 0), nLoadedFlags ( SFX_LOADED_MAINDOCUMENT ), pMarkData( 0 ), bInFrame( sal_False ), bModalMode( sal_False ), bRunningMacro( sal_False ), bReloadAvailable( sal_False ), nAutoLoadLocks( 0 ), bInPrepareClose( sal_False ), bPreparedForClose( sal_False ), bWaitingForPicklist( sal_False ), pModule( 0 ), bModuleSearched( sal_False ), pFrame( 0 ), pImageManager( 0 ), pTbxConfig( 0 ), pEventConfig(NULL), bIsHelpObjSh( sal_False ), bForbidCaching( sal_False ), bDoNotTouchDocInfo( sal_False ), bForbidReload( sal_False ), bBasicInitialized( sal_False ), eFlags( SFXOBJECTSHELL_UNDEFINED ), pCloser( 0 ), bSupportsEventMacros( sal_True ), bReadOnlyUI( sal_False ), bHiddenLockedByAPI( sal_False ), bInCloseEvent( sal_False ), bLoadingWindows( sal_False ), bHidden( sal_False ) , nStyleFilter( 0 ) , nMacroMode( -1 ) , bDisposing( sal_False ) {} ~SfxObjectShell_Impl(); }; #endif <commit_msg>INTEGRATION: CWS valgrind01 (1.18.24); FILE MERGED 2003/11/03 13:05:31 hr 1.18.24.1: #i20184#: initialize bIsPrintJobCancelable member of SfxObjectShell_Impl<commit_after>/************************************************************************* * * $RCSfile: objshimp.hxx,v $ * * $Revision: 1.19 $ * * last change: $Author: rt $ $Date: 2003-11-25 10:51:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SFX_OBJSHIMP_HXX #define _SFX_OBJSHIMP_HXX #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _DATETIME_HXX #include <tools/datetime.hxx> #endif #include <svtools/securityoptions.hxx> #include "objsh.hxx" #include "bitset.hxx" namespace svtools { class AsynchronLink; } //==================================================================== DBG_NAMEEX(SfxObjectShell); class SfxViewFrame; struct MarkData_Impl { String aMark; String aUserData; SfxViewFrame* pFrame; }; class SfxFrame; class SfxDialogLibraryContainer; class SfxScriptLibraryContainer; class SfxImageManager; class SfxToolBoxConfig; class SfxAcceleratorManager; struct SfxObjectShell_Impl { SfxAcceleratorManager* pAccMgr; SfxDocumentInfo* pDocInfo; SfxConfigManager* pCfgMgr; SfxInPlaceObject* pInPlaceObj; // das dazugeh"orige SO2-Objekt, falls this ein SfxInPlaceObject ist BasicManager* pBasicMgr; // Doc-BASIC oder 0 SfxScriptLibraryContainer* pBasicLibContainer; SfxDialogLibraryContainer* pDialogLibContainer; SfxProgress* pProgress; String aTitle; String aTempName; DateTime nTime; sal_uInt16 nVisualDocumentNumber; sal_Bool bTemplateConfig:1, bInList:1, // ob per First/Next erreichbar bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten bIsSaving:1, bPasswd:1, bIsTmp:1, bIsNamedVisible:1, bDidWarnFormat:1, // sal_True, falls schon wg. speichern in Fremformat gewarnt wurde bSetStandardName:1, // sal_True, falls im FileSave Dialog xxxx.sdw im Standardverzeichnis vorgeschlagen werden soll. bDidDangerousSave:1, // sal_True, falls ein Save in ein Alienformat durchgefuehrt wurde bIsTemplate:1, bIsAbortingImport:1, // Importvorgang soll abgebrochen werden. bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs. bInPrepareClose : 1, bPreparedForClose : 1, bWaitingForPicklist : 1,// Muss noch in die Pickliste bModuleSearched : 1, bIsBasicDefault : 1, bIsHelpObjSh : 1, bForbidCaching : 1, bForbidReload : 1, bSupportsEventMacros: 1, bLoadingWindows: 1, bBasicInitialized :1, bHidden :1, // indicates a hidden view shell bIsPrintJobCancelable :1; // Stampit disable/enable cancel button for print jobs ... default = true = enable! String aNewName; // Der Name, unter dem das Doc gespeichert // werden soll IndexBitSet aBitSet; sal_uInt32 lErr; sal_uInt16 nEventId; // falls vor Activate noch ein // Open/Create gesendet werden mu/s sal_Bool bDoNotTouchDocInfo; AutoReloadTimer_Impl *pReloadTimer; MarkData_Impl* pMarkData; sal_uInt16 nLoadedFlags; String aMark; Size aViewSize; // wird leider vom Writer beim sal_Bool bInFrame; // HTML-Import gebraucht sal_Bool bModalMode; sal_Bool bRunningMacro; sal_Bool bReloadAvailable; sal_uInt16 nAutoLoadLocks; SfxModule* pModule; SfxFrame* pFrame; SfxImageManager* pImageManager; SfxToolBoxConfig* pTbxConfig; SfxEventConfigItem_Impl* pEventConfig; SfxObjectShellFlags eFlags; svtools::AsynchronLink* pCloser; String aBaseURL; sal_Bool bReadOnlyUI; SvRefBaseRef xHeaderAttributes; sal_Bool bHiddenLockedByAPI; sal_Bool bInCloseEvent; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel; sal_uInt16 nStyleFilter; sal_Int16 nMacroMode; sal_Bool bDisposing; SfxObjectShell_Impl() : pAccMgr(0), nTime(), bIsTmp( sal_False), bClosing( sal_False), bSetInPlaceObj( sal_False), bPasswd( sal_False), pInPlaceObj( 0), pBasicMgr( 0), pBasicLibContainer( 0 ), pDialogLibContainer( 0 ), pProgress( 0), nVisualDocumentNumber( USHRT_MAX), bIsSaving( sal_False), bIsNamedVisible( sal_False), pCfgMgr( 0), bTemplateConfig( sal_False), bDidWarnFormat( sal_False), bDidDangerousSave(sal_False), bIsBasicDefault( sal_True ), bIsTemplate(sal_False), lErr(ERRCODE_NONE), nEventId ( 0), pDocInfo ( 0), bIsAbortingImport ( sal_False), bInList ( sal_False), bImportDone ( sal_False), pReloadTimer ( 0), nLoadedFlags ( SFX_LOADED_MAINDOCUMENT ), pMarkData( 0 ), bInFrame( sal_False ), bModalMode( sal_False ), bRunningMacro( sal_False ), bReloadAvailable( sal_False ), nAutoLoadLocks( 0 ), bInPrepareClose( sal_False ), bPreparedForClose( sal_False ), bWaitingForPicklist( sal_False ), pModule( 0 ), bModuleSearched( sal_False ), pFrame( 0 ), pImageManager( 0 ), pTbxConfig( 0 ), pEventConfig(NULL), bIsHelpObjSh( sal_False ), bForbidCaching( sal_False ), bDoNotTouchDocInfo( sal_False ), bForbidReload( sal_False ), bBasicInitialized( sal_False ), eFlags( SFXOBJECTSHELL_UNDEFINED ), pCloser( 0 ), bSupportsEventMacros( sal_True ), bReadOnlyUI( sal_False ), bHiddenLockedByAPI( sal_False ), bInCloseEvent( sal_False ), bLoadingWindows( sal_False ), bHidden( sal_False ) , nStyleFilter( 0 ) , nMacroMode( -1 ) , bDisposing( sal_False ) , bIsPrintJobCancelable( sal_True ) {} ~SfxObjectShell_Impl(); }; #endif <|endoftext|>
<commit_before>#include <cmath> #include <cstdarg> #include <iostream> #include "opencv2/core.hpp" using namespace cv; #include "math.hpp" float median(std::vector<float>& v) { const int n = v.size(); assert(n > 0); if (n == 1) return v[0]; std::sort(v.begin(), v.end()); return v[n / 2]; } float mean(std::vector<float>& v) { const int n = v.size(); if (n == 0) return 0.f; float sum = std::accumulate(std::begin(v), std::end(v), 0.0); return sum / n; } float var(std::vector<float>& v) { const int n = v.size(); if (n == 0) return 0.f; float _mean = mean(v); return sqrt(std::accumulate(std::begin(v), std::end(v), 0.f, [&](const float b, const float e) { float diff = e - _mean; return b + diff * diff; }) / n); } float randInt(const float min, const float max) { return roundf(rand() / (float)RAND_MAX * (max - min) + min); } Rect randomCrop(const Mat& img, const float w2hrat) { int h = img.rows, w = img.cols, minh = max(32, h / 5), minw = max(32, w / 5); int x0, y0, dx, dy; while (1) { x0 = randInt(0, w - minw); y0 = randInt(0, h - minh); dy = randInt(minh, h - 1 - y0); if (w2hrat > 1e-5) // Valid aspect ratio { dx = roundf((float) dy * w2hrat); if (dx < minw || x0 + dx + 1 > w) continue; } else dx = randInt(minw, w - 1 - x0); return Rect(x0, y0, dx, dy); } } Rect randomCrop(const Mat& img, const Rect good_crop, const float thresh) { Rect crop = randomCrop(img); while (cropOverlap(good_crop, crop) > thresh) crop = randomCrop(img); return crop; } float cropOverlap(const Rect crop1, const Rect crop2) { int x1a = crop1.x, y1a = crop1.y, x1b = crop1.x + crop1.width, y1b = crop1.y + crop1.height, x2a = crop2.x, y2a = crop2.y, x2b = crop2.x + crop2.width, y2b = crop2.y + crop2.height; int ow = max(0, min(x1b, x2b) - max(x1a, x2a)), oh = max(0, min(y1b, y2b) - max(y1a, y2a)); int oA = ow * oh; if (oA == 0) return 0; int A1 = crop1.width * crop1.height, A2 = crop2.width * crop2.height; return oA / (float) (A1 + A2 - oA); } <commit_msg>Make randomCrop assume nothing for minimum crop size<commit_after>#include <cmath> #include <cstdarg> #include <iostream> #include "opencv2/core.hpp" using namespace cv; #include "math.hpp" float median(std::vector<float>& v) { const int n = v.size(); assert(n > 0); if (n == 1) return v[0]; std::sort(v.begin(), v.end()); return v[n / 2]; } float mean(std::vector<float>& v) { const int n = v.size(); if (n == 0) return 0.f; float sum = std::accumulate(std::begin(v), std::end(v), 0.0); return sum / n; } float var(std::vector<float>& v) { const int n = v.size(); if (n == 0) return 0.f; float _mean = mean(v); return sqrt(std::accumulate(std::begin(v), std::end(v), 0.f, [&](const float b, const float e) { float diff = e - _mean; return b + diff * diff; }) / n); } float randInt(const float min, const float max) { return roundf(rand() / (float)RAND_MAX * (max - min) + min); } Rect randomCrop(const Mat& img, const float w2hrat) { int h = img.rows, w = img.cols, minh = 8, minw = 8; int x0, y0, dx, dy; while (1) { x0 = randInt(0, w - minw); y0 = randInt(0, h - minh); dy = randInt(minh, h - 1 - y0); if (w2hrat > 1e-5) // Valid aspect ratio { dx = roundf((float) dy * w2hrat); if (dx < minw || x0 + dx + 1 > w) continue; } else dx = randInt(minw, w - 1 - x0); return Rect(x0, y0, dx, dy); } } Rect randomCrop(const Mat& img, const Rect good_crop, const float thresh) { Rect crop = randomCrop(img); while (cropOverlap(good_crop, crop) > thresh) crop = randomCrop(img); return crop; } float cropOverlap(const Rect crop1, const Rect crop2) { int x1a = crop1.x, y1a = crop1.y, x1b = crop1.x + crop1.width, y1b = crop1.y + crop1.height, x2a = crop2.x, y2a = crop2.y, x2b = crop2.x + crop2.width, y2b = crop2.y + crop2.height; int ow = max(0, min(x1b, x2b) - max(x1a, x2a)), oh = max(0, min(y1b, y2b) - max(y1a, y2a)); int oA = ow * oh; if (oA == 0) return 0; int A1 = crop1.width * crop1.height, A2 = crop2.width * crop2.height; return oA / (float) (A1 + A2 - oA); } <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <string> #include <cstdlib> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/regex.hpp> #include <nix/util/util.hpp> using namespace std; namespace nix { namespace util { // default id base (16 or 32) const int ID_BASE = 32; // Base32hex alphabet (RFC 4648) const char* ID_ALPHABET = "0123456789abcdefghijklmnopqrstuv"; // Unit scaling, SI only, substitutions for micro and ohm... const string PREFIXES = "(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)"; const string UNITS = "(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%)"; const string POWER = "(\\^[+-]?[1-9]\\d*)"; const map<string, double> PREFIX_FACTORS = {{"y", 1.0e-24}, {"z", 1.0e-21}, {"a", 1.0e-18}, {"f", 1.0e-15}, {"p", 1.0e-12}, {"n",1.0e-9}, {"u", 1.0e-6}, {"m", 1.0e-3}, {"c", 1.0e-2}, {"d",1.0e-1}, {"da", 1.0e1}, {"h", 1.0e2}, {"k", 1.0e3}, {"M",1.0e6}, {"G", 1.0e9}, {"T", 1.0e12}, {"P", 1.0e15}, {"E",1.0e18}, {"Z", 1.0e21}, {"Y", 1.0e24}}; string createId(string prefix, int length) { static bool initialized = false; if(!initialized) { initialized = true; srand(time(NULL)); } string id; if (prefix.length() > 0) { id.append(prefix); id.append("_"); } for (int i = 0; i < length; i++) { char c = ID_ALPHABET[(size_t) (((double) (rand())) / RAND_MAX * ID_BASE)]; id.push_back(c); } return id; } string timeToStr(time_t time) { using namespace boost::posix_time; ptime timetmp = from_time_t(time); return to_iso_string(timetmp); } time_t strToTime(const string &time) { using namespace boost::posix_time; ptime timetmp(from_iso_string(time)); ptime epoch(boost::gregorian::date(1970, 1, 1)); return (timetmp - epoch).total_seconds(); } void splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power){ boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER); boost::regex prefix_and_unit(PREFIXES + UNITS); boost::regex unit_and_power(UNITS + POWER); boost::regex unit_only(UNITS); boost::regex prefix_only(PREFIXES); if(boost::regex_match(combinedUnit, prefix_and_unit_and_power)){ boost::match_results<std::string::const_iterator> m; boost::regex_search(combinedUnit, m, prefix_only); prefix = m[0]; string suffix = m.suffix(); boost::regex_search(suffix,m,unit_only); unit = m[0]; power = m.suffix(); } else if(boost::regex_match(combinedUnit, prefix_and_unit)){ boost::match_results<std::string::const_iterator> m; boost::regex_search(combinedUnit, m, prefix_only); prefix = m[0]; unit = m.suffix(); power = ""; } else{ unit = combinedUnit; prefix = ""; power = ""; } } void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits){ boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?"); boost::regex separator("(\\*|/)"); boost::match_results<std::string::const_iterator> m; boost::regex_search(compoundUnit, m, opt_prefix_and_unit_and_power); while(m.suffix().length() > 0){ string suffix = m.suffix(); atomicUnits.push_back(m[0]); boost::regex_search(suffix.substr(1), m, opt_prefix_and_unit_and_power); } atomicUnits.push_back(m[0]); } bool isSIUnit(const string &unit){ boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?"); return boost::regex_match(unit, opt_prefix_and_unit_and_power); } bool isCompoundSIUnit(const string &unit){ string atomic_unit = PREFIXES + "?" + UNITS + POWER + "?"; boost::regex compound_unit("(" + atomic_unit + "(\\*|/))+"+ atomic_unit); return boost::regex_match(unit, compound_unit); } double getSIScaling(const string &originUnit, const string &destinationUnit){ double scaling = 1.0; if (isSIUnit(originUnit) && isSIUnit(destinationUnit)){ string org_unit, org_prefix, org_power; string dest_unit, dest_prefix, dest_power; splitUnit(originUnit, org_prefix, org_unit, org_power); splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power); if(dest_unit.compare(org_unit) != 0){ throw runtime_error("Origin and destination units are not the same!"); } if(dest_prefix.length() == 0){ scaling = 1.0 / PREFIX_FACTORS.at(org_prefix); } else if (org_prefix.length() == 0){ scaling = PREFIX_FACTORS.at(dest_prefix); } else{ scaling = PREFIX_FACTORS.at(dest_prefix) / PREFIX_FACTORS.at(org_prefix); } }else{ throw runtime_error("Origin unit and/or destination unit are not valid!"); } return scaling; } } // namespace util } // namespace nix <commit_msg>util: initialise the rng inside a std::call_once<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <string> #include <cstdlib> #include <mutex> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/regex.hpp> #include <nix/util/util.hpp> using namespace std; namespace nix { namespace util { // default id base (16 or 32) const int ID_BASE = 32; // Base32hex alphabet (RFC 4648) const char* ID_ALPHABET = "0123456789abcdefghijklmnopqrstuv"; // Unit scaling, SI only, substitutions for micro and ohm... const string PREFIXES = "(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)"; const string UNITS = "(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%)"; const string POWER = "(\\^[+-]?[1-9]\\d*)"; const map<string, double> PREFIX_FACTORS = {{"y", 1.0e-24}, {"z", 1.0e-21}, {"a", 1.0e-18}, {"f", 1.0e-15}, {"p", 1.0e-12}, {"n",1.0e-9}, {"u", 1.0e-6}, {"m", 1.0e-3}, {"c", 1.0e-2}, {"d",1.0e-1}, {"da", 1.0e1}, {"h", 1.0e2}, {"k", 1.0e3}, {"M",1.0e6}, {"G", 1.0e9}, {"T", 1.0e12}, {"P", 1.0e15}, {"E",1.0e18}, {"Z", 1.0e21}, {"Y", 1.0e24}}; string createId(string prefix, int length) { static std::once_flag rand_init; std::call_once(rand_init, []() { srand(time(NULL)); }); string id; if (prefix.length() > 0) { id.append(prefix); id.append("_"); } for (int i = 0; i < length; i++) { char c = ID_ALPHABET[(size_t) (((double) (rand())) / RAND_MAX * ID_BASE)]; id.push_back(c); } return id; } string timeToStr(time_t time) { using namespace boost::posix_time; ptime timetmp = from_time_t(time); return to_iso_string(timetmp); } time_t strToTime(const string &time) { using namespace boost::posix_time; ptime timetmp(from_iso_string(time)); ptime epoch(boost::gregorian::date(1970, 1, 1)); return (timetmp - epoch).total_seconds(); } void splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power){ boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER); boost::regex prefix_and_unit(PREFIXES + UNITS); boost::regex unit_and_power(UNITS + POWER); boost::regex unit_only(UNITS); boost::regex prefix_only(PREFIXES); if(boost::regex_match(combinedUnit, prefix_and_unit_and_power)){ boost::match_results<std::string::const_iterator> m; boost::regex_search(combinedUnit, m, prefix_only); prefix = m[0]; string suffix = m.suffix(); boost::regex_search(suffix,m,unit_only); unit = m[0]; power = m.suffix(); } else if(boost::regex_match(combinedUnit, prefix_and_unit)){ boost::match_results<std::string::const_iterator> m; boost::regex_search(combinedUnit, m, prefix_only); prefix = m[0]; unit = m.suffix(); power = ""; } else{ unit = combinedUnit; prefix = ""; power = ""; } } void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits){ boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?"); boost::regex separator("(\\*|/)"); boost::match_results<std::string::const_iterator> m; boost::regex_search(compoundUnit, m, opt_prefix_and_unit_and_power); while(m.suffix().length() > 0){ string suffix = m.suffix(); atomicUnits.push_back(m[0]); boost::regex_search(suffix.substr(1), m, opt_prefix_and_unit_and_power); } atomicUnits.push_back(m[0]); } bool isSIUnit(const string &unit){ boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?"); return boost::regex_match(unit, opt_prefix_and_unit_and_power); } bool isCompoundSIUnit(const string &unit){ string atomic_unit = PREFIXES + "?" + UNITS + POWER + "?"; boost::regex compound_unit("(" + atomic_unit + "(\\*|/))+"+ atomic_unit); return boost::regex_match(unit, compound_unit); } double getSIScaling(const string &originUnit, const string &destinationUnit){ double scaling = 1.0; if (isSIUnit(originUnit) && isSIUnit(destinationUnit)){ string org_unit, org_prefix, org_power; string dest_unit, dest_prefix, dest_power; splitUnit(originUnit, org_prefix, org_unit, org_power); splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power); if(dest_unit.compare(org_unit) != 0){ throw runtime_error("Origin and destination units are not the same!"); } if(dest_prefix.length() == 0){ scaling = 1.0 / PREFIX_FACTORS.at(org_prefix); } else if (org_prefix.length() == 0){ scaling = PREFIX_FACTORS.at(dest_prefix); } else{ scaling = PREFIX_FACTORS.at(dest_prefix) / PREFIX_FACTORS.at(org_prefix); } }else{ throw runtime_error("Origin unit and/or destination unit are not valid!"); } return scaling; } } // namespace util } // namespace nix <|endoftext|>
<commit_before>// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/process_util.h" #include "gin/dictionary.h" #include "shell/common/gin_converters/callback_converter.h" namespace electron { void EmitWarning(node::Environment* env, const std::string& warning_msg, const std::string& warning_type) { gin::Dictionary process(env->isolate(), env->process_object()); base::RepeatingCallback<void(base::StringPiece, base::StringPiece, base::StringPiece)> emit_warning; process.Get("emitWarning", &emit_warning); emit_warning.Run(warning_msg, warning_type, ""); } } // namespace electron <commit_msg>fix: wrap EmitWarning with HandleScope (#23667)<commit_after>// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/process_util.h" #include "gin/dictionary.h" #include "shell/common/gin_converters/callback_converter.h" namespace electron { void EmitWarning(node::Environment* env, const std::string& warning_msg, const std::string& warning_type) { v8::HandleScope scope(env->isolate()); gin::Dictionary process(env->isolate(), env->process_object()); base::RepeatingCallback<void(base::StringPiece, base::StringPiece, base::StringPiece)> emit_warning; process.Get("emitWarning", &emit_warning); emit_warning.Run(warning_msg, warning_type, ""); } } // namespace electron <|endoftext|>
<commit_before>#include "ui_mainwindow.h" #include "utilities.h" #include "window.h" #include <QDesktopServices> #include <QWebSettings> #include <QSettings> #include <QProcess> #include <QDir> #include <QTime> Utilities utils; Utilities::Utilities() : settings(QSettings::IniFormat, QSettings::UserScope, "solusipse", "web-to-webm") { killed = false; } void Utilities::setCommons() { QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); win.ui->player->settings()->setAttribute(QWebSettings::PluginsEnabled, true); } QString Utilities::execBinary(QString bin, int multiline = 0) { QProcess program; program.start(bin); while(program.waitForFinished(-1)) { if (multiline == 0) { return QString::fromLocal8Bit(program.readAllStandardOutput().simplified()); } return program.readAllStandardOutput(); } utils.addToLog("Error on executing command: " + bin); return "error_exec"; } QString Utilities::getVideoTitle(QString url) { return execBinary(getBinaryName() + " -e " + url); } QString Utilities::getVideoID(QString url) { return execBinary(getBinaryName() + " --get-id " + url); } QString Utilities::prepareUrl(QString url) { currentID = getVideoID(url); if (currentID == "error_exec") return currentID; if (currentID.isEmpty()) return "error_url"; return url; } void Utilities::addToLog(QString line, bool display) { if (line.length() < 3) return; line.prepend("[" + QTime().currentTime().toString() + "] "); if (display) win.ui->logBox->appendHtml(line); line.replace("<br>", "").replace("<b>", "").replace("</b>", ""); if (!log.contains("\n")) log.append(line + "\n"); else log.append(line); } bool Utilities::checkUrl() { if (currentVideoUrl.isEmpty()) { addToLog("Add valid video first."); return false; } addToLog("<br><b>Started downloading video:</b><br>" + win.ui->urlEdit->text()); return true; } QVector< QVector<QString> > Utilities::createQualityList(QString url) { QVector< QVector<QString> > list; QString formats = execBinary(getBinaryName() + " -F " + url, 1); QStringList formatsList = formats.split("\n"); /* * there are always clips in webm and mp4 with same resolution * since mp4 provides better quality and there is sometimes * higher quality in mp4 format available, script is excluding webm * at this moment */ for (int i = formatsList.length()-1; i >= 0 ; i--) { if (!formatsList[i].contains("webm")) if (!formatsList[i].contains("audio only")) if (!formatsList[i].contains("video only")) { QRegExp resolution("\\d{3,4}x\\d{3}"); resolution.indexIn(formatsList[i]); QRegExp format("\\w\\w\\w"); format.indexIn(formatsList[i]); QString strResolution = resolution.capturedTexts()[0]; QString strFormat = format.capturedTexts()[0]; if (strResolution != "" && strFormat != "") { QString strCode = formatsList[i].split(" ")[0]; QVector<QString> single; single.append(strResolution); single.append(strCode); single.append(strFormat); list.append(single); } } } return list; } QString Utilities::getVideoQuality() { return currentQualityList[win.ui->qualityComboBox->currentIndex()][1]; } QString Utilities::getFileName() { return currentID + "-" + currentQualityList[win.ui->qualityComboBox->currentIndex()][1] + "." + currentQualityList[win.ui->qualityComboBox->currentIndex()][2]; } void Utilities::killProcesses() { if (utils.downloadProcess != NULL) { killed = true; utils.downloadProcess->kill(); } if (utils.conversionProcess != NULL) { killed = true; utils.conversionProcess->kill(); } } QString Utilities::getBinaryName() { if (!configGetValue("youtubedl_path").isEmpty()) return configGetValue("youtubedl_path"); if (SYSTEM == 0) return "youtube-dl.exe"; if (SYSTEM == 1) return QCoreApplication::applicationDirPath() + "/youtube-dl"; return "youtube-dl"; } QString Utilities::ffmpegBinaryName() { if (!configGetValue("ffmpeg_path").isEmpty()) return configGetValue("ffmpeg_path"); if (SYSTEM == 0) return "ffmpeg.exe"; if (SYSTEM == 1) return QCoreApplication::applicationDirPath() + "/ffmpeg"; return "ffmpeg"; } QString Utilities::getCurrentRawFilename() { QString path = QFileInfo(getCurrentFilename()).absolutePath(); QString name = QFileInfo(getCurrentFilename()).baseName(); return path + "/" + name + "." + currentQualityList[win.ui->qualityComboBox->currentIndex()][2]; } QString Utilities::getCurrentFilename() { if (pathChanged) return currentFileName; return getDefaultFilename(); } QString Utilities::getDefaultFilename() { if (configGetValue("default_path").isEmpty()) return QDir().homePath() + "/" + QFileInfo(getFileName()).baseName() + ".webm"; return configGetValue("default_path") + "/" + QFileInfo(getFileName()).baseName() + ".webm"; } int Utilities::getTrimmedVideoDuration() { QString cutFrom = win.ui->cutFromEdit->text(); QString cutTo = win.ui->cutToEdit->text(); int time = parseTime(cutFrom).secsTo(parseTime(cutTo)); utils.addToLog("Output video length: " + (QTime(0,0,0).addSecs(time)).toString("hh:mm:ss")); return time; } QTime Utilities::parseTime(QString s) { int occurences = s.count(":"); if (occurences == 0) { return QTime(0,0,0).addSecs(s.toInt()); } if (occurences == 1) { return QTime::fromString(s, "mm:ss"); } if (occurences == 2) { return QTime::fromString(s, "hh:mm:ss"); } return QTime(); } void Utilities::loadVideo(QString url) { url = utils.prepareUrl(url); if (url == "error_exec") { utils.currentVideoUrl = ""; return; } if (url == "error_url") { utils.addToLog("<b>Error:</b> provided url is incorrect."); utils.currentVideoUrl = ""; return; } killProcesses(); pathChanged = false; currentQualityList = createQualityList(url); win.setVideoDetails(url); addToLog("<b>Loaded video:</b> <br>" + win.ui->urlEdit->text()); } void Utilities::configInit() { configSetValueIfBlank("remove_sound", "false"); configSetValueIfBlank("dont_convert", "false"); configSetValueIfBlank("remove_raw", "true"); configSetValueIfBlank("default_path", ""); configSetValueIfBlank("open_output", "false"); configSetValueIfBlank("show_ytdl_log", "true"); configSetValueIfBlank("show_ffmpeg_log", "true"); configSetValueIfBlank("youtubedl_path", ""); configSetValueIfBlank("ffmpeg_path", ""); } void Utilities::configSaveAll() { settings.setValue("remove_sound", win.ui->menuRemoveAudio->isChecked()); settings.setValue("dont_convert", win.ui->menuDontConvert->isChecked()); settings.setValue("remove_raw", win.ui->menuRemoveRawVideo->isChecked()); settings.setValue("open_output", win.ui->menuShowFile->isChecked()); settings.setValue("show_ytdl_log", win.ui->menuYoutubedlOutput->isChecked()); settings.setValue("show_ffmpeg_log", win.ui->menuFfmpegOutput->isChecked()); } void Utilities::configLoadAll() { win.ui->menuRemoveAudio->setChecked(configGetValueBool("remove_sound")); win.ui->menuDontConvert->setChecked(configGetValueBool("dont_convert")); win.ui->menuRemoveRawVideo->setChecked(configGetValueBool("remove_raw")); win.ui->menuShowFile->setChecked(configGetValueBool("open_output")); win.ui->menuYoutubedlOutput->setChecked(configGetValueBool("show_ytdl_log")); win.ui->menuFfmpegOutput->setChecked(configGetValueBool("show_ffmpeg_log")); } void Utilities::configSetValue(QString k, QString v) { settings.setValue(k, v); } void Utilities::configSetValueIfBlank(QString k, QString v) { if (!settings.contains(k)) settings.setValue(k, v); } QString Utilities::configGetValue(QString k) { return settings.value(k).toString(); } bool Utilities::configGetValueBool(QString k) { return settings.value(k).toBool(); } void Utilities::removeRawVideo() { QFile::remove(getCurrentRawFilename()); } void Utilities::showFileInDirectory() { QDesktopServices::openUrl("file:///" + QFileInfo(getCurrentFilename()).absolutePath()); } bool Utilities::checkBinaries() { } <commit_msg>added support for videos of unknown quality<commit_after>#include "ui_mainwindow.h" #include "utilities.h" #include "window.h" #include <QDesktopServices> #include <QWebSettings> #include <QSettings> #include <QProcess> #include <QDir> #include <QTime> Utilities utils; Utilities::Utilities() : settings(QSettings::IniFormat, QSettings::UserScope, "solusipse", "web-to-webm") { killed = false; } void Utilities::setCommons() { QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); win.ui->player->settings()->setAttribute(QWebSettings::PluginsEnabled, true); } QString Utilities::execBinary(QString bin, int multiline = 0) { QProcess program; program.start(bin); while(program.waitForFinished(-1)) { if (multiline == 0) { return QString::fromLocal8Bit(program.readAllStandardOutput().simplified()); } return program.readAllStandardOutput(); } utils.addToLog("Error on executing command: " + bin); return "error_exec"; } QString Utilities::getVideoTitle(QString url) { return execBinary(getBinaryName() + " -e " + url); } QString Utilities::getVideoID(QString url) { return execBinary(getBinaryName() + " --get-id " + url); } QString Utilities::prepareUrl(QString url) { currentID = getVideoID(url); if (currentID == "error_exec") return currentID; if (currentID.isEmpty()) return "error_url"; return url; } void Utilities::addToLog(QString line, bool display) { if (line.length() < 3) return; line.prepend("[" + QTime().currentTime().toString() + "] "); if (display) win.ui->logBox->appendHtml(line); line.replace("<br>", "").replace("<b>", "").replace("</b>", ""); if (!log.contains("\n")) log.append(line + "\n"); else log.append(line); } bool Utilities::checkUrl() { if (currentVideoUrl.isEmpty()) { addToLog("Add valid video first."); return false; } addToLog("<br><b>Started downloading video:</b><br>" + win.ui->urlEdit->text()); return true; } QVector< QVector<QString> > Utilities::createQualityList(QString url) { QVector< QVector<QString> > list; QString formats = execBinary(getBinaryName() + " -F " + url, 1); QStringList formatsList = formats.split("\n"); /* * there are always clips in webm and mp4 with same resolution * since mp4 provides better quality and there is sometimes * higher quality in mp4 format available, script is excluding webm * at this moment */ for (int i = formatsList.length()-1; i >= 0 ; i--) { if (!formatsList[i].contains("webm")) if (!formatsList[i].contains("audio only")) if (!formatsList[i].contains("video only")) { QRegExp resolution("\\d{3,4}x\\d{3,4}"); resolution.indexIn(formatsList[i]); QRegExp format("\\w\\w\\w"); format.indexIn(formatsList[i]); QString strResolution = resolution.capturedTexts()[0]; QString strFormat = format.capturedTexts()[0]; if (strFormat != "" && formatsList[i].contains("unknown")) strResolution = "unknown"; if (strResolution != "" && strFormat != "") { QString strCode = formatsList[i].split(" ")[0]; QVector<QString> single; single.append(strResolution); single.append(strCode); single.append(strFormat); list.append(single); } } } return list; } QString Utilities::getVideoQuality() { return currentQualityList[win.ui->qualityComboBox->currentIndex()][1]; } QString Utilities::getFileName() { return currentID + "-" + currentQualityList[win.ui->qualityComboBox->currentIndex()][1] + "." + currentQualityList[win.ui->qualityComboBox->currentIndex()][2]; } void Utilities::killProcesses() { if (utils.downloadProcess != NULL) { killed = true; utils.downloadProcess->kill(); } if (utils.conversionProcess != NULL) { killed = true; utils.conversionProcess->kill(); } } QString Utilities::getBinaryName() { if (!configGetValue("youtubedl_path").isEmpty()) return configGetValue("youtubedl_path"); if (SYSTEM == 0) return "youtube-dl.exe"; if (SYSTEM == 1) return QCoreApplication::applicationDirPath() + "/youtube-dl"; return "youtube-dl"; } QString Utilities::ffmpegBinaryName() { if (!configGetValue("ffmpeg_path").isEmpty()) return configGetValue("ffmpeg_path"); if (SYSTEM == 0) return "ffmpeg.exe"; if (SYSTEM == 1) return QCoreApplication::applicationDirPath() + "/ffmpeg"; return "ffmpeg"; } QString Utilities::getCurrentRawFilename() { QString path = QFileInfo(getCurrentFilename()).absolutePath(); QString name = QFileInfo(getCurrentFilename()).baseName(); return path + "/" + name + "." + currentQualityList[win.ui->qualityComboBox->currentIndex()][2]; } QString Utilities::getCurrentFilename() { if (pathChanged) return currentFileName; return getDefaultFilename(); } QString Utilities::getDefaultFilename() { if (configGetValue("default_path").isEmpty()) return QDir().homePath() + "/" + QFileInfo(getFileName()).baseName() + ".webm"; return configGetValue("default_path") + "/" + QFileInfo(getFileName()).baseName() + ".webm"; } int Utilities::getTrimmedVideoDuration() { QString cutFrom = win.ui->cutFromEdit->text(); QString cutTo = win.ui->cutToEdit->text(); int time = parseTime(cutFrom).secsTo(parseTime(cutTo)); utils.addToLog("Output video length: " + (QTime(0,0,0).addSecs(time)).toString("hh:mm:ss")); return time; } QTime Utilities::parseTime(QString s) { int occurences = s.count(":"); if (occurences == 0) { return QTime(0,0,0).addSecs(s.toInt()); } if (occurences == 1) { return QTime::fromString(s, "mm:ss"); } if (occurences == 2) { return QTime::fromString(s, "hh:mm:ss"); } return QTime(); } void Utilities::loadVideo(QString url) { url = utils.prepareUrl(url); if (url == "error_exec") { utils.currentVideoUrl = ""; return; } if (url == "error_url") { utils.addToLog("<b>Error:</b> provided url is incorrect."); utils.currentVideoUrl = ""; return; } killProcesses(); pathChanged = false; currentQualityList = createQualityList(url); win.setVideoDetails(url); addToLog("<b>Loaded video:</b> <br>" + win.ui->urlEdit->text()); } void Utilities::configInit() { configSetValueIfBlank("remove_sound", "false"); configSetValueIfBlank("dont_convert", "false"); configSetValueIfBlank("remove_raw", "true"); configSetValueIfBlank("default_path", ""); configSetValueIfBlank("open_output", "false"); configSetValueIfBlank("show_ytdl_log", "true"); configSetValueIfBlank("show_ffmpeg_log", "true"); configSetValueIfBlank("youtubedl_path", ""); configSetValueIfBlank("ffmpeg_path", ""); } void Utilities::configSaveAll() { settings.setValue("remove_sound", win.ui->menuRemoveAudio->isChecked()); settings.setValue("dont_convert", win.ui->menuDontConvert->isChecked()); settings.setValue("remove_raw", win.ui->menuRemoveRawVideo->isChecked()); settings.setValue("open_output", win.ui->menuShowFile->isChecked()); settings.setValue("show_ytdl_log", win.ui->menuYoutubedlOutput->isChecked()); settings.setValue("show_ffmpeg_log", win.ui->menuFfmpegOutput->isChecked()); } void Utilities::configLoadAll() { win.ui->menuRemoveAudio->setChecked(configGetValueBool("remove_sound")); win.ui->menuDontConvert->setChecked(configGetValueBool("dont_convert")); win.ui->menuRemoveRawVideo->setChecked(configGetValueBool("remove_raw")); win.ui->menuShowFile->setChecked(configGetValueBool("open_output")); win.ui->menuYoutubedlOutput->setChecked(configGetValueBool("show_ytdl_log")); win.ui->menuFfmpegOutput->setChecked(configGetValueBool("show_ffmpeg_log")); } void Utilities::configSetValue(QString k, QString v) { settings.setValue(k, v); } void Utilities::configSetValueIfBlank(QString k, QString v) { if (!settings.contains(k)) settings.setValue(k, v); } QString Utilities::configGetValue(QString k) { return settings.value(k).toString(); } bool Utilities::configGetValueBool(QString k) { return settings.value(k).toBool(); } void Utilities::removeRawVideo() { QFile::remove(getCurrentRawFilename()); } void Utilities::showFileInDirectory() { QDesktopServices::openUrl("file:///" + QFileInfo(getCurrentFilename()).absolutePath()); } bool Utilities::checkBinaries() { } <|endoftext|>
<commit_before>/** * @file llweb.cpp * @brief Functions dealing with web browsers * @author James Cook * * $LicenseInfo:firstyear=2006&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llweb.h" // Library includes #include "llwindow.h" // spawnWebBrowser() #include "llagent.h" #include "llappviewer.h" #include "llfloatermediabrowser.h" #include "llfloaterreg.h" #include "lllogininstance.h" #include "llparcel.h" #include "llsd.h" #include "lltoastalertpanel.h" #include "llui.h" #include "lluri.h" #include "llversioninfo.h" #include "llviewercontrol.h" #include "llviewernetwork.h" #include "llviewerparcelmgr.h" #include "llviewerregion.h" #include "llviewerwindow.h" #include "llnotificationsutil.h" bool on_load_url_external_response(const LLSD& notification, const LLSD& response, bool async ); class URLLoader : public LLToastAlertPanel::URLLoader { virtual void load(const std::string& url , bool force_open_externally) { if (force_open_externally) { LLWeb::loadURLExternal(url); } else { LLWeb::loadURL(url); } } }; static URLLoader sAlertURLLoader; // static void LLWeb::initClass() { LLToastAlertPanel::setURLLoader(&sAlertURLLoader); } // static void LLWeb::loadURL(const std::string& url, const std::string& target, const std::string& uuid) { if(target == "_internal") { // Force load in the internal browser, as if with a blank target. loadURLInternal(url, "", uuid); } else if (gSavedSettings.getBOOL("UseExternalBrowser") || (target == "_external")) { loadURLExternal(url); } else { loadURLInternal(url, target, uuid); } } // static void LLWeb::loadURLInternal(const std::string &url, const std::string& target, const std::string& uuid) { LLFloaterMediaBrowser::create(url, target, uuid); } // static void LLWeb::loadURLExternal(const std::string& url, const std::string& uuid) { loadURLExternal(url, true); } // static void LLWeb::loadURLExternal(const std::string& url, bool async, const std::string& uuid) { // Act like the proxy window was closed, since we won't be able to track targeted windows in the external browser. LLViewerMedia::proxyWindowClosed(uuid); LLSD payload; payload["url"] = url; LLNotificationsUtil::add( "WebLaunchExternalTarget", LLSD(), payload, boost::bind(on_load_url_external_response, _1, _2, async)); } // static bool on_load_url_external_response(const LLSD& notification, const LLSD& response, bool async ) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); if ( 0 == option ) { LLSD payload = notification["payload"]; std::string url = payload["url"].asString(); std::string escaped_url = LLWeb::escapeURL(url); if (gViewerWindow) { gViewerWindow->getWindow()->spawnWebBrowser(escaped_url, async); } } return false; } // static std::string LLWeb::escapeURL(const std::string& url) { // The CURL curl_escape() function escapes colons, slashes, // and all characters but A-Z and 0-9. Do a cheesy mini-escape. std::string escaped_url; S32 len = url.length(); for (S32 i = 0; i < len; i++) { char c = url[i]; if (c == ' ') { escaped_url += "%20"; } else if (c == '\\') { escaped_url += "%5C"; } else { escaped_url += c; } } return escaped_url; } //static std::string LLWeb::expandURLSubstitutions(const std::string &url, const LLSD &default_subs) { LLSD substitution = default_subs; substitution["VERSION"] = LLVersionInfo::getVersion(); substitution["VERSION_MAJOR"] = LLVersionInfo::getMajor(); substitution["VERSION_MINOR"] = LLVersionInfo::getMinor(); substitution["VERSION_PATCH"] = LLVersionInfo::getPatch(); substitution["VERSION_BUILD"] = LLVersionInfo::getBuild(); substitution["CHANNEL"] = LLVersionInfo::getChannel(); substitution["GRID"] = LLGridManager::getInstance()->getGridLabel(); substitution["OS"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple(); substitution["SESSION_ID"] = gAgent.getSessionID(); substitution["FIRST_LOGIN"] = gAgent.isFirstLogin(); // work out the current language std::string lang = LLUI::getLanguage(); if (lang == "en-us") { // *HACK: the correct fix is to change English.lproj/language.txt, // but we're late in the release cycle and this is a less risky fix lang = "en"; } substitution["LANGUAGE"] = lang; // find the region ID LLUUID region_id; LLViewerRegion *region = gAgent.getRegion(); if (region) { region_id = region->getRegionID(); } substitution["REGION_ID"] = region_id; // find the parcel local ID S32 parcel_id = 0; LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel(); if (parcel) { parcel_id = parcel->getLocalID(); } substitution["PARCEL_ID"] = llformat("%d", parcel_id); // expand all of the substitution strings and escape the url std::string expanded_url = url; LLStringUtil::format(expanded_url, substitution); return LLWeb::escapeURL(expanded_url); } <commit_msg>Fix one variant of LLWeb::loadURLExternal() not passing through the uuid to the other variant.<commit_after>/** * @file llweb.cpp * @brief Functions dealing with web browsers * @author James Cook * * $LicenseInfo:firstyear=2006&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llweb.h" // Library includes #include "llwindow.h" // spawnWebBrowser() #include "llagent.h" #include "llappviewer.h" #include "llfloatermediabrowser.h" #include "llfloaterreg.h" #include "lllogininstance.h" #include "llparcel.h" #include "llsd.h" #include "lltoastalertpanel.h" #include "llui.h" #include "lluri.h" #include "llversioninfo.h" #include "llviewercontrol.h" #include "llviewernetwork.h" #include "llviewerparcelmgr.h" #include "llviewerregion.h" #include "llviewerwindow.h" #include "llnotificationsutil.h" bool on_load_url_external_response(const LLSD& notification, const LLSD& response, bool async ); class URLLoader : public LLToastAlertPanel::URLLoader { virtual void load(const std::string& url , bool force_open_externally) { if (force_open_externally) { LLWeb::loadURLExternal(url); } else { LLWeb::loadURL(url); } } }; static URLLoader sAlertURLLoader; // static void LLWeb::initClass() { LLToastAlertPanel::setURLLoader(&sAlertURLLoader); } // static void LLWeb::loadURL(const std::string& url, const std::string& target, const std::string& uuid) { if(target == "_internal") { // Force load in the internal browser, as if with a blank target. loadURLInternal(url, "", uuid); } else if (gSavedSettings.getBOOL("UseExternalBrowser") || (target == "_external")) { loadURLExternal(url); } else { loadURLInternal(url, target, uuid); } } // static void LLWeb::loadURLInternal(const std::string &url, const std::string& target, const std::string& uuid) { LLFloaterMediaBrowser::create(url, target, uuid); } // static void LLWeb::loadURLExternal(const std::string& url, const std::string& uuid) { loadURLExternal(url, true, uuid); } // static void LLWeb::loadURLExternal(const std::string& url, bool async, const std::string& uuid) { // Act like the proxy window was closed, since we won't be able to track targeted windows in the external browser. LLViewerMedia::proxyWindowClosed(uuid); LLSD payload; payload["url"] = url; LLNotificationsUtil::add( "WebLaunchExternalTarget", LLSD(), payload, boost::bind(on_load_url_external_response, _1, _2, async)); } // static bool on_load_url_external_response(const LLSD& notification, const LLSD& response, bool async ) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); if ( 0 == option ) { LLSD payload = notification["payload"]; std::string url = payload["url"].asString(); std::string escaped_url = LLWeb::escapeURL(url); if (gViewerWindow) { gViewerWindow->getWindow()->spawnWebBrowser(escaped_url, async); } } return false; } // static std::string LLWeb::escapeURL(const std::string& url) { // The CURL curl_escape() function escapes colons, slashes, // and all characters but A-Z and 0-9. Do a cheesy mini-escape. std::string escaped_url; S32 len = url.length(); for (S32 i = 0; i < len; i++) { char c = url[i]; if (c == ' ') { escaped_url += "%20"; } else if (c == '\\') { escaped_url += "%5C"; } else { escaped_url += c; } } return escaped_url; } //static std::string LLWeb::expandURLSubstitutions(const std::string &url, const LLSD &default_subs) { LLSD substitution = default_subs; substitution["VERSION"] = LLVersionInfo::getVersion(); substitution["VERSION_MAJOR"] = LLVersionInfo::getMajor(); substitution["VERSION_MINOR"] = LLVersionInfo::getMinor(); substitution["VERSION_PATCH"] = LLVersionInfo::getPatch(); substitution["VERSION_BUILD"] = LLVersionInfo::getBuild(); substitution["CHANNEL"] = LLVersionInfo::getChannel(); substitution["GRID"] = LLGridManager::getInstance()->getGridLabel(); substitution["OS"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple(); substitution["SESSION_ID"] = gAgent.getSessionID(); substitution["FIRST_LOGIN"] = gAgent.isFirstLogin(); // work out the current language std::string lang = LLUI::getLanguage(); if (lang == "en-us") { // *HACK: the correct fix is to change English.lproj/language.txt, // but we're late in the release cycle and this is a less risky fix lang = "en"; } substitution["LANGUAGE"] = lang; // find the region ID LLUUID region_id; LLViewerRegion *region = gAgent.getRegion(); if (region) { region_id = region->getRegionID(); } substitution["REGION_ID"] = region_id; // find the parcel local ID S32 parcel_id = 0; LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel(); if (parcel) { parcel_id = parcel->getLocalID(); } substitution["PARCEL_ID"] = llformat("%d", parcel_id); // expand all of the substitution strings and escape the url std::string expanded_url = url; LLStringUtil::format(expanded_url, substitution); return LLWeb::escapeURL(expanded_url); } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ // This file is partially included in the manual, do not modify // without updating the references in the *.tex files! // Manual references: lines 32-93 (Error.tex) #ifndef CAF_SEC_HPP #define CAF_SEC_HPP #include "caf/error.hpp" #include "caf/make_message.hpp" namespace caf { /// SEC stands for "System Error Code". This enum contains /// error codes used internally by CAF. enum class sec : uint8_t { /// Indicates that an actor dropped an unexpected message. unexpected_message = 1, /// Indicates that a response message did not match the provided handler. unexpected_response, /// Indicates that the receiver of a request is no longer alive. request_receiver_down, /// Indicates that a request message timed out. request_timeout, /// Indicates that requested group module does not exist. no_such_group_module, /// Unpublishing or connecting failed: no actor bound to given port. no_actor_published_at_port, /// Connecting failed because a remote actor had an unexpected interface. unexpected_actor_messaging_interface, /// Migration failed because the state of an actor is not serializable. state_not_serializable, /// An actor received an unsupported key for `('sys', 'get', key)` messages. unsupported_sys_key, /// An actor received an unsupported system message. unsupported_sys_message, /// A remote node disconnected during CAF handshake. disconnect_during_handshake, /// Tried to forward a message via BASP to an invalid actor handle. cannot_forward_to_invalid_actor, /// Tried to forward a message via BASP to an unknown node ID. no_route_to_receiving_node, /// Middleman could not assign a connection handle to a broker. failed_to_assign_scribe_from_handle, /// Middleman could not assign an acceptor handle to a broker. failed_to_assign_doorman_from_handle, /// User requested to close port 0 or to close a port not managed by CAF. cannot_close_invalid_port, /// Middleman could not connect to a remote node. cannot_connect_to_node, /// Middleman could not open requested port. cannot_open_port, /// A C system call in the middleman failed. network_syscall_failed, /// A function received one or more invalid arguments. invalid_argument, /// A network socket reported an invalid network protocol family. invalid_protocol_family, /// Middleman could not publish an actor because it was invalid. cannot_publish_invalid_actor, /// A remote spawn failed because the provided types did not match. cannot_spawn_actor_from_arguments, /// Serialization failed because there was not enough data to read. end_of_stream, /// Serialization failed because no CAF context is available. no_context, /// Serialization failed because CAF misses run-time type information. unknown_type, /// Serialization of actors failed because no proxy registry is available. no_proxy_registry, /// An exception was thrown during message handling. runtime_error, /// Linking to a remote actor failed because actor no longer exists. remote_linking_failed, /// Adding an upstream to a stream failed. cannot_add_upstream, /// Adding an upstream to a stream failed because it already exists. upstream_already_exists, /// Unable to process upstream messages because upstream is invalid. invalid_upstream, /// Adding a downstream to a stream failed. cannot_add_downstream, /// Adding a downstream to a stream failed because it already exists. downstream_already_exists, /// Unable to process downstream messages because downstream is invalid. invalid_downstream, /// Cannot start streaming without next stage. no_downstream_stages_defined, /// Actor failed to initialize state after receiving a stream handshake. stream_init_failed, /// Unable to process a stream since due to missing state. invalid_stream_state, /// A function view was called without assigning an actor first. bad_function_call }; /// @relates sec std::string to_string(sec); /// @relates sec error make_error(sec); /// @relates sec template <class T, class... Ts> error make_error(sec code, T&& x, Ts&&... xs) { return {static_cast<uint8_t>(code), atom("system"), make_message(std::forward<T>(x), std::forward<Ts>(xs)...)}; } } // namespace caf #endif // CAF_SEC_HPP <commit_msg>Add numbers to SEC header to easier lookup<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ // This file is partially included in the manual, do not modify // without updating the references in the *.tex files! // Manual references: lines 32-93 (Error.tex) #ifndef CAF_SEC_HPP #define CAF_SEC_HPP #include "caf/error.hpp" #include "caf/make_message.hpp" namespace caf { /// SEC stands for "System Error Code". This enum contains /// error codes used internally by CAF. enum class sec : uint8_t { /// Indicates that an actor dropped an unexpected message. unexpected_message = 1, /// Indicates that a response message did not match the provided handler. unexpected_response, /// Indicates that the receiver of a request is no longer alive. request_receiver_down, /// Indicates that a request message timed out. request_timeout, /// Indicates that requested group module does not exist. no_such_group_module = 5, /// Unpublishing or connecting failed: no actor bound to given port. no_actor_published_at_port, /// Connecting failed because a remote actor had an unexpected interface. unexpected_actor_messaging_interface, /// Migration failed because the state of an actor is not serializable. state_not_serializable, /// An actor received an unsupported key for `('sys', 'get', key)` messages. unsupported_sys_key, /// An actor received an unsupported system message. unsupported_sys_message = 10, /// A remote node disconnected during CAF handshake. disconnect_during_handshake, /// Tried to forward a message via BASP to an invalid actor handle. cannot_forward_to_invalid_actor, /// Tried to forward a message via BASP to an unknown node ID. no_route_to_receiving_node, /// Middleman could not assign a connection handle to a broker. failed_to_assign_scribe_from_handle, /// Middleman could not assign an acceptor handle to a broker. failed_to_assign_doorman_from_handle = 15, /// User requested to close port 0 or to close a port not managed by CAF. cannot_close_invalid_port, /// Middleman could not connect to a remote node. cannot_connect_to_node, /// Middleman could not open requested port. cannot_open_port, /// A C system call in the middleman failed. network_syscall_failed, /// A function received one or more invalid arguments. invalid_argument = 20, /// A network socket reported an invalid network protocol family. invalid_protocol_family, /// Middleman could not publish an actor because it was invalid. cannot_publish_invalid_actor, /// A remote spawn failed because the provided types did not match. cannot_spawn_actor_from_arguments, /// Serialization failed because there was not enough data to read. end_of_stream, /// Serialization failed because no CAF context is available. no_context = 25, /// Serialization failed because CAF misses run-time type information. unknown_type, /// Serialization of actors failed because no proxy registry is available. no_proxy_registry, /// An exception was thrown during message handling. runtime_error, /// Linking to a remote actor failed because actor no longer exists. remote_linking_failed, /// Adding an upstream to a stream failed. cannot_add_upstream = 30, /// Adding an upstream to a stream failed because it already exists. upstream_already_exists, /// Unable to process upstream messages because upstream is invalid. invalid_upstream, /// Adding a downstream to a stream failed. cannot_add_downstream, /// Adding a downstream to a stream failed because it already exists. downstream_already_exists, /// Unable to process downstream messages because downstream is invalid. invalid_downstream = 35, /// Cannot start streaming without next stage. no_downstream_stages_defined, /// Actor failed to initialize state after receiving a stream handshake. stream_init_failed, /// Unable to process a stream since due to missing state. invalid_stream_state, /// A function view was called without assigning an actor first. bad_function_call }; /// @relates sec std::string to_string(sec); /// @relates sec error make_error(sec); /// @relates sec template <class T, class... Ts> error make_error(sec code, T&& x, Ts&&... xs) { return {static_cast<uint8_t>(code), atom("system"), make_message(std::forward<T>(x), std::forward<Ts>(xs)...)}; } } // namespace caf #endif // CAF_SEC_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * The software must be used only for Non-Commercial Use which means any * use which is NOT directed to receiving any direct monetary * compensation for, or commercial advantage from such use. Illustrative * examples of non-commercial use are academic research, personal study, * teaching, education and corporate research & development. * Illustrative examples of commercial use are distributing products for * commercial advantage and providing services using the software for * commercial advantage. * * If you wish to use this software or functionality therein that may be * covered by patents for commercial use, please contact: * Director of Intellectual Property Licensing * Office of Strategy and Technology * Hewlett-Packard Company * 1501 Page Mill Road * Palo Alto, California 94304 * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. Neither the name of * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. No right of * sublicense is granted herewith. Derivatives of the software and * output created using the software may be prepared, but only for * Non-Commercial Uses. Derivatives of the software may be shared with * others provided: (i) the others agree to abide by the list of * conditions herein which includes the Non-Commercial Use restrictions; * and (ii) such Derivatives of the software include the above copyright * notice to acknowledge the contribution from this software where * applicable, this list of conditions and the disclaimer below. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/x86/predecoder.hh" #include "base/misc.hh" #include "base/trace.hh" #include "sim/host.hh" namespace X86ISA { void Predecoder::reset() { origPC = basePC + offset; DPRINTF(Predecoder, "Setting origPC to %#x\n", origPC); emi.rex = 0; emi.legacy = 0; emi.opcode.num = 0; immediateCollected = 0; emi.immediate = 0; displacementCollected = 0; emi.displacement = 0; emi.modRM = 0; emi.sib = 0; emi.mode = 0; } void Predecoder::process() { //This function drives the predecoder state machine. //Some sanity checks. You shouldn't try to process more bytes if //there aren't any, and you shouldn't overwrite an already //predecoder ExtMachInst. assert(!outOfBytes); assert(!emiIsReady); //While there's still something to do... while(!emiIsReady && !outOfBytes) { uint8_t nextByte = getNextByte(); switch(state) { case ResetState: reset(); state = PrefixState; case PrefixState: state = doPrefixState(nextByte); break; case OpcodeState: state = doOpcodeState(nextByte); break; case ModRMState: state = doModRMState(nextByte); break; case SIBState: state = doSIBState(nextByte); break; case DisplacementState: state = doDisplacementState(); break; case ImmediateState: state = doImmediateState(); break; case ErrorState: panic("Went to the error state in the predecoder.\n"); default: panic("Unrecognized state! %d\n", state); } } } //Either get a prefix and record it in the ExtMachInst, or send the //state machine on to get the opcode(s). Predecoder::State Predecoder::doPrefixState(uint8_t nextByte) { uint8_t prefix = Prefixes[nextByte]; State nextState = PrefixState; if(prefix) consumeByte(); switch(prefix) { //Operand size override prefixes case OperandSizeOverride: DPRINTF(Predecoder, "Found operand size override prefix.\n"); emi.legacy.op = true; break; case AddressSizeOverride: DPRINTF(Predecoder, "Found address size override prefix.\n"); emi.legacy.addr = true; break; //Segment override prefixes case CSOverride: case DSOverride: case ESOverride: case FSOverride: case GSOverride: case SSOverride: DPRINTF(Predecoder, "Found segment override.\n"); emi.legacy.seg = prefix; break; case Lock: DPRINTF(Predecoder, "Found lock prefix.\n"); emi.legacy.lock = true; break; case Rep: DPRINTF(Predecoder, "Found rep prefix.\n"); emi.legacy.rep = true; break; case Repne: DPRINTF(Predecoder, "Found repne prefix.\n"); emi.legacy.repne = true; break; case RexPrefix: DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte); emi.rex = nextByte; break; case 0: nextState = OpcodeState; break; default: panic("Unrecognized prefix %#x\n", nextByte); } return nextState; } //Load all the opcodes (currently up to 2) and then figure out //what immediate and/or ModRM is needed. Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte) { State nextState = ErrorState; emi.opcode.num++; //We can't handle 3+ byte opcodes right now assert(emi.opcode.num < 3); consumeByte(); if(emi.opcode.num == 1 && nextByte == 0x0f) { nextState = OpcodeState; DPRINTF(Predecoder, "Found two byte opcode.\n"); emi.opcode.prefixA = nextByte; } else if(emi.opcode.num == 2 && (nextByte == 0x0f || (nextByte & 0xf8) == 0x38)) { panic("Three byte opcodes aren't yet supported!\n"); nextState = OpcodeState; DPRINTF(Predecoder, "Found three byte opcode.\n"); emi.opcode.prefixB = nextByte; } else { DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte); emi.opcode.op = nextByte; //Figure out the effective operand size. This can be overriden to //a fixed value at the decoder level. int logOpSize; if(/*FIXME long mode*/1) { if(emi.rex.w) logOpSize = 3; // 64 bit operand size else if(emi.legacy.op) logOpSize = 1; // 16 bit operand size else logOpSize = 2; // 32 bit operand size } else if(/*FIXME default 32*/1) { if(emi.legacy.op) logOpSize = 1; // 16 bit operand size else logOpSize = 2; // 32 bit operand size } else // 16 bit default operand size { if(emi.legacy.op) logOpSize = 2; // 32 bit operand size else logOpSize = 1; // 16 bit operand size } //Figure out how big of an immediate we'll retreive based //on the opcode. int immType = ImmediateType[emi.opcode.num - 1][nextByte]; immediateSize = SizeTypeToSize[logOpSize - 1][immType]; //Set the actual op size emi.opSize = 1 << logOpSize; //Determine what to expect next if (UsesModRM[emi.opcode.num - 1][nextByte]) { nextState = ModRMState; } else { if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } } } return nextState; } //Get the ModRM byte and determine what displacement, if any, there is. //Also determine whether or not to get the SIB byte, displacement, or //immediate next. Predecoder::State Predecoder::doModRMState(uint8_t nextByte) { State nextState = ErrorState; emi.modRM = nextByte; DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte); if (0) {//FIXME in 16 bit mode //figure out 16 bit displacement size if(nextByte & 0xC7 == 0x06 || nextByte & 0xC0 == 0x80) displacementSize = 2; else if(nextByte & 0xC0 == 0x40) displacementSize = 1; else displacementSize = 0; } else { //figure out 32/64 bit displacement size if(nextByte & 0xC6 == 0x04 || nextByte & 0xC0 == 0x80) displacementSize = 4; else if(nextByte & 0xC0 == 0x40) displacementSize = 1; else displacementSize = 0; } //If there's an SIB, get that next. //There is no SIB in 16 bit mode. if(nextByte & 0x7 == 4 && nextByte & 0xC0 != 0xC0) { // && in 32/64 bit mode) nextState = SIBState; } else if(displacementSize) { nextState = DisplacementState; } else if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } //The ModRM byte is consumed no matter what consumeByte(); return nextState; } //Get the SIB byte. We don't do anything with it at this point, other //than storing it in the ExtMachInst. Determine if we need to get a //displacement or immediate next. Predecoder::State Predecoder::doSIBState(uint8_t nextByte) { State nextState = ErrorState; emi.sib = nextByte; DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte); consumeByte(); if(displacementSize) { nextState = DisplacementState; } else if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } return nextState; } //Gather up the displacement, or at least as much of it //as we can get. Predecoder::State Predecoder::doDisplacementState() { State nextState = ErrorState; getImmediate(displacementCollected, emi.displacement, displacementSize); DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n", displacementSize, displacementCollected); if(displacementSize == displacementCollected) { //Sign extend the displacement switch(displacementSize) { case 1: emi.displacement = sext<8>(emi.displacement); break; case 2: emi.displacement = sext<16>(emi.displacement); break; case 4: emi.displacement = sext<32>(emi.displacement); break; default: panic("Undefined displacement size!\n"); } DPRINTF(Predecoder, "Collected displacement %#x.\n", emi.displacement); if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } } else nextState = DisplacementState; return nextState; } //Gather up the immediate, or at least as much of it //as we can get Predecoder::State Predecoder::doImmediateState() { State nextState = ErrorState; getImmediate(immediateCollected, emi.immediate, immediateSize); DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n", immediateSize, immediateCollected); if(immediateSize == immediateCollected) { //XXX Warning! The following is an observed pattern and might //not always be true! //Instructions which use 64 bit operands but 32 bit immediates //need to have the immediate sign extended to 64 bits. //Instructions which use true 64 bit immediates won't be //affected, and instructions that use true 32 bit immediates //won't notice. if(immediateSize == 4) emi.immediate = sext<32>(emi.immediate); DPRINTF(Predecoder, "Collected immediate %#x.\n", emi.immediate); emiIsReady = true; nextState = ResetState; } else nextState = ImmediateState; return nextState; } } <commit_msg>Sign extend byte immediates as well. There might need to be a fancier system in place to handle this in the future.<commit_after>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * The software must be used only for Non-Commercial Use which means any * use which is NOT directed to receiving any direct monetary * compensation for, or commercial advantage from such use. Illustrative * examples of non-commercial use are academic research, personal study, * teaching, education and corporate research & development. * Illustrative examples of commercial use are distributing products for * commercial advantage and providing services using the software for * commercial advantage. * * If you wish to use this software or functionality therein that may be * covered by patents for commercial use, please contact: * Director of Intellectual Property Licensing * Office of Strategy and Technology * Hewlett-Packard Company * 1501 Page Mill Road * Palo Alto, California 94304 * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. Neither the name of * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. No right of * sublicense is granted herewith. Derivatives of the software and * output created using the software may be prepared, but only for * Non-Commercial Uses. Derivatives of the software may be shared with * others provided: (i) the others agree to abide by the list of * conditions herein which includes the Non-Commercial Use restrictions; * and (ii) such Derivatives of the software include the above copyright * notice to acknowledge the contribution from this software where * applicable, this list of conditions and the disclaimer below. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "arch/x86/predecoder.hh" #include "base/misc.hh" #include "base/trace.hh" #include "sim/host.hh" namespace X86ISA { void Predecoder::reset() { origPC = basePC + offset; DPRINTF(Predecoder, "Setting origPC to %#x\n", origPC); emi.rex = 0; emi.legacy = 0; emi.opcode.num = 0; immediateCollected = 0; emi.immediate = 0; displacementCollected = 0; emi.displacement = 0; emi.modRM = 0; emi.sib = 0; emi.mode = 0; } void Predecoder::process() { //This function drives the predecoder state machine. //Some sanity checks. You shouldn't try to process more bytes if //there aren't any, and you shouldn't overwrite an already //predecoder ExtMachInst. assert(!outOfBytes); assert(!emiIsReady); //While there's still something to do... while(!emiIsReady && !outOfBytes) { uint8_t nextByte = getNextByte(); switch(state) { case ResetState: reset(); state = PrefixState; case PrefixState: state = doPrefixState(nextByte); break; case OpcodeState: state = doOpcodeState(nextByte); break; case ModRMState: state = doModRMState(nextByte); break; case SIBState: state = doSIBState(nextByte); break; case DisplacementState: state = doDisplacementState(); break; case ImmediateState: state = doImmediateState(); break; case ErrorState: panic("Went to the error state in the predecoder.\n"); default: panic("Unrecognized state! %d\n", state); } } } //Either get a prefix and record it in the ExtMachInst, or send the //state machine on to get the opcode(s). Predecoder::State Predecoder::doPrefixState(uint8_t nextByte) { uint8_t prefix = Prefixes[nextByte]; State nextState = PrefixState; if(prefix) consumeByte(); switch(prefix) { //Operand size override prefixes case OperandSizeOverride: DPRINTF(Predecoder, "Found operand size override prefix.\n"); emi.legacy.op = true; break; case AddressSizeOverride: DPRINTF(Predecoder, "Found address size override prefix.\n"); emi.legacy.addr = true; break; //Segment override prefixes case CSOverride: case DSOverride: case ESOverride: case FSOverride: case GSOverride: case SSOverride: DPRINTF(Predecoder, "Found segment override.\n"); emi.legacy.seg = prefix; break; case Lock: DPRINTF(Predecoder, "Found lock prefix.\n"); emi.legacy.lock = true; break; case Rep: DPRINTF(Predecoder, "Found rep prefix.\n"); emi.legacy.rep = true; break; case Repne: DPRINTF(Predecoder, "Found repne prefix.\n"); emi.legacy.repne = true; break; case RexPrefix: DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte); emi.rex = nextByte; break; case 0: nextState = OpcodeState; break; default: panic("Unrecognized prefix %#x\n", nextByte); } return nextState; } //Load all the opcodes (currently up to 2) and then figure out //what immediate and/or ModRM is needed. Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte) { State nextState = ErrorState; emi.opcode.num++; //We can't handle 3+ byte opcodes right now assert(emi.opcode.num < 3); consumeByte(); if(emi.opcode.num == 1 && nextByte == 0x0f) { nextState = OpcodeState; DPRINTF(Predecoder, "Found two byte opcode.\n"); emi.opcode.prefixA = nextByte; } else if(emi.opcode.num == 2 && (nextByte == 0x0f || (nextByte & 0xf8) == 0x38)) { panic("Three byte opcodes aren't yet supported!\n"); nextState = OpcodeState; DPRINTF(Predecoder, "Found three byte opcode.\n"); emi.opcode.prefixB = nextByte; } else { DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte); emi.opcode.op = nextByte; //Figure out the effective operand size. This can be overriden to //a fixed value at the decoder level. int logOpSize; if(/*FIXME long mode*/1) { if(emi.rex.w) logOpSize = 3; // 64 bit operand size else if(emi.legacy.op) logOpSize = 1; // 16 bit operand size else logOpSize = 2; // 32 bit operand size } else if(/*FIXME default 32*/1) { if(emi.legacy.op) logOpSize = 1; // 16 bit operand size else logOpSize = 2; // 32 bit operand size } else // 16 bit default operand size { if(emi.legacy.op) logOpSize = 2; // 32 bit operand size else logOpSize = 1; // 16 bit operand size } //Figure out how big of an immediate we'll retreive based //on the opcode. int immType = ImmediateType[emi.opcode.num - 1][nextByte]; immediateSize = SizeTypeToSize[logOpSize - 1][immType]; //Set the actual op size emi.opSize = 1 << logOpSize; //Determine what to expect next if (UsesModRM[emi.opcode.num - 1][nextByte]) { nextState = ModRMState; } else { if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } } } return nextState; } //Get the ModRM byte and determine what displacement, if any, there is. //Also determine whether or not to get the SIB byte, displacement, or //immediate next. Predecoder::State Predecoder::doModRMState(uint8_t nextByte) { State nextState = ErrorState; emi.modRM = nextByte; DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte); if (0) {//FIXME in 16 bit mode //figure out 16 bit displacement size if(nextByte & 0xC7 == 0x06 || nextByte & 0xC0 == 0x80) displacementSize = 2; else if(nextByte & 0xC0 == 0x40) displacementSize = 1; else displacementSize = 0; } else { //figure out 32/64 bit displacement size if(nextByte & 0xC6 == 0x04 || nextByte & 0xC0 == 0x80) displacementSize = 4; else if(nextByte & 0xC0 == 0x40) displacementSize = 1; else displacementSize = 0; } //If there's an SIB, get that next. //There is no SIB in 16 bit mode. if(nextByte & 0x7 == 4 && nextByte & 0xC0 != 0xC0) { // && in 32/64 bit mode) nextState = SIBState; } else if(displacementSize) { nextState = DisplacementState; } else if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } //The ModRM byte is consumed no matter what consumeByte(); return nextState; } //Get the SIB byte. We don't do anything with it at this point, other //than storing it in the ExtMachInst. Determine if we need to get a //displacement or immediate next. Predecoder::State Predecoder::doSIBState(uint8_t nextByte) { State nextState = ErrorState; emi.sib = nextByte; DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte); consumeByte(); if(displacementSize) { nextState = DisplacementState; } else if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } return nextState; } //Gather up the displacement, or at least as much of it //as we can get. Predecoder::State Predecoder::doDisplacementState() { State nextState = ErrorState; getImmediate(displacementCollected, emi.displacement, displacementSize); DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n", displacementSize, displacementCollected); if(displacementSize == displacementCollected) { //Sign extend the displacement switch(displacementSize) { case 1: emi.displacement = sext<8>(emi.displacement); break; case 2: emi.displacement = sext<16>(emi.displacement); break; case 4: emi.displacement = sext<32>(emi.displacement); break; default: panic("Undefined displacement size!\n"); } DPRINTF(Predecoder, "Collected displacement %#x.\n", emi.displacement); if(immediateSize) { nextState = ImmediateState; } else { emiIsReady = true; nextState = ResetState; } } else nextState = DisplacementState; return nextState; } //Gather up the immediate, or at least as much of it //as we can get Predecoder::State Predecoder::doImmediateState() { State nextState = ErrorState; getImmediate(immediateCollected, emi.immediate, immediateSize); DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n", immediateSize, immediateCollected); if(immediateSize == immediateCollected) { //XXX Warning! The following is an observed pattern and might //not always be true! //Instructions which use 64 bit operands but 32 bit immediates //need to have the immediate sign extended to 64 bits. //Instructions which use true 64 bit immediates won't be //affected, and instructions that use true 32 bit immediates //won't notice. switch(immediateSize) { case 4: emi.immediate = sext<32>(emi.immediate); break; case 1: emi.immediate = sext<8>(emi.immediate); } DPRINTF(Predecoder, "Collected immediate %#x.\n", emi.immediate); emiIsReady = true; nextState = ResetState; } else nextState = ImmediateState; return nextState; } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // audiofx.cpp: General effect processing routines. // Copyright (C) 1999-2002,2004,2006 Kai Vehmanen // // Attributes: // eca-style-version: 3 (see Ecasound Programmer's Guide) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <kvu_dbc.h> #include <kvu_numtostr.h> #include "sample-specs.h" #include "samplebuffer.h" #include "audiofx.h" #include "eca-logger.h" EFFECT_BASE::EFFECT_BASE(void) : channels_rep(0) { } EFFECT_BASE::~EFFECT_BASE(void) { } void EFFECT_BASE::init(SAMPLE_BUFFER* sbuf) { ECA_LOG_MSG(ECA_LOGGER::user_objects, "(audiofx) Init w/ samplerate " + kvu_numtostr(samples_per_second()) + " for object " + name() + "."); set_channels(sbuf->number_of_channels()); DBC_CHECK(channels() > 0); DBC_CHECK(samples_per_second() > 0); } int EFFECT_BASE::channels(void) const { return channels_rep; } void EFFECT_BASE::set_samples_per_second(SAMPLE_SPECS::sample_rate_t new_rate) { ECA_LOG_MSG(ECA_LOGGER::user_objects, "Setting samplerate to " + kvu_numtostr(new_rate) + " for object " + name() + ". Old value " + kvu_numtostr(samples_per_second()) + "."); /* note: changing the sample rate might change values of * of parameters, so we want to preserve the values */ if (samples_per_second() != new_rate) { std::vector<parameter_t> old_values (number_of_params()); for(int n = 0; n < number_of_params(); n++) { old_values[n] = get_parameter(n + 1); } ECA_SAMPLERATE_AWARE::set_samples_per_second(new_rate); for(int n = 0; n < number_of_params(); n++) { set_parameter(n + 1, old_values[n]); } } } void EFFECT_BASE::set_channels(int v) { channels_rep = v; } <commit_msg>Fixed trivial coding style issue.<commit_after>// ------------------------------------------------------------------------ // audiofx.cpp: General effect processing routines. // Copyright (C) 1999-2002,2004,2006,2008 Kai Vehmanen // // Attributes: // eca-style-version: 3 (see Ecasound Programmer's Guide) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <kvu_dbc.h> #include <kvu_numtostr.h> #include "sample-specs.h" #include "samplebuffer.h" #include "audiofx.h" #include "eca-logger.h" EFFECT_BASE::EFFECT_BASE(void) : channels_rep(0) { } EFFECT_BASE::~EFFECT_BASE(void) { } void EFFECT_BASE::init(SAMPLE_BUFFER* sbuf) { ECA_LOG_MSG(ECA_LOGGER::user_objects, "Init w/ samplerate " + kvu_numtostr(samples_per_second()) + " for object " + name() + "."); set_channels(sbuf->number_of_channels()); DBC_CHECK(channels() > 0); DBC_CHECK(samples_per_second() > 0); } int EFFECT_BASE::channels(void) const { return channels_rep; } void EFFECT_BASE::set_samples_per_second(SAMPLE_SPECS::sample_rate_t new_rate) { ECA_LOG_MSG(ECA_LOGGER::user_objects, "Setting samplerate to " + kvu_numtostr(new_rate) + " for object " + name() + ". Old value " + kvu_numtostr(samples_per_second()) + "."); /* note: changing the sample rate might change values of * of parameters, so we want to preserve the values */ if (samples_per_second() != new_rate) { std::vector<parameter_t> old_values (number_of_params()); for(int n = 0; n < number_of_params(); n++) { old_values[n] = get_parameter(n + 1); } ECA_SAMPLERATE_AWARE::set_samples_per_second(new_rate); for(int n = 0; n < number_of_params(); n++) { set_parameter(n + 1, old_values[n]); } } } void EFFECT_BASE::set_channels(int v) { channels_rep = v; } <|endoftext|>
<commit_before>/* * Copyright 2015 LabWare * Copyright 2014 Google, Inc. * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Boris Shingarov */ #ifndef __ARCH_X86_REMOTEGDB_HH__ #define __ARCH_X86_REMOTEGDB_HH__ #include <algorithm> #include "arch/x86/types.hh" #include "base/remote_gdb.hh" class System; class ThreadContext; namespace X86ISA { class RemoteGDB : public BaseRemoteGDB { protected: bool acc(Addr addr, size_t len); bool checkBpLen(size_t len) { return len == 1; } class X86GdbRegCache : public BaseGdbRegCache { using BaseGdbRegCache::BaseGdbRegCache; private: struct { uint32_t eax; uint32_t ecx; uint32_t edx; uint32_t ebx; uint32_t esp; uint32_t ebp; uint32_t esi; uint32_t edi; uint32_t eip; uint32_t eflags; uint32_t cs; uint32_t ss; uint32_t ds; uint32_t es; uint32_t fs; uint32_t gs; } r; public: char *data() const { return (char *)&r; } size_t size() const { return sizeof(r); } void getRegs(ThreadContext*); void setRegs(ThreadContext*) const; const std::string name() const { return gdb->name() + ".X86GdbRegCache"; } }; class AMD64GdbRegCache : public BaseGdbRegCache { using BaseGdbRegCache::BaseGdbRegCache; private: struct { uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rsi; uint64_t rdi; uint64_t rbp; uint64_t rsp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rip; uint32_t eflags; uint32_t cs; uint32_t ss; uint32_t ds; uint32_t es; uint32_t fs; uint32_t gs; /* * We do not model st[], FPU status regs, xmm[] etc. * While it's not ok to have G-packets larger than what gdb * knows about, it is ok to have smaller ones. */ } r; public: char *data() const { return (char *)&r; } size_t size() const { return sizeof(r); } void getRegs(ThreadContext*); void setRegs(ThreadContext*) const; const std::string name() const { return gdb->name() + ".AMD64GdbRegCache"; } }; X86GdbRegCache regCache32; AMD64GdbRegCache regCache64; public: RemoteGDB(System *system, ThreadContext *context); BaseGdbRegCache *gdbRegs(); }; } // namespace X86ISA #endif // __ARCH_X86_REMOTEGDB_HH__ <commit_msg>x86: Fixed remote debugging of simulated code<commit_after>/* * Copyright 2015 LabWare * Copyright 2014 Google, Inc. * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Boris Shingarov */ #ifndef __ARCH_X86_REMOTEGDB_HH__ #define __ARCH_X86_REMOTEGDB_HH__ #include <algorithm> #include "arch/x86/types.hh" #include "base/remote_gdb.hh" class System; class ThreadContext; namespace X86ISA { class RemoteGDB : public BaseRemoteGDB { protected: bool acc(Addr addr, size_t len); bool checkBpLen(size_t len) { return len == 1; } class X86GdbRegCache : public BaseGdbRegCache { using BaseGdbRegCache::BaseGdbRegCache; private: struct { uint32_t eax; uint32_t ecx; uint32_t edx; uint32_t ebx; uint32_t esp; uint32_t ebp; uint32_t esi; uint32_t edi; uint32_t eip; uint32_t eflags; uint32_t cs; uint32_t ss; uint32_t ds; uint32_t es; uint32_t fs; uint32_t gs; } r; public: char *data() const { return (char *)&r; } size_t size() const { return sizeof(r); } void getRegs(ThreadContext*); void setRegs(ThreadContext*) const; const std::string name() const { return gdb->name() + ".X86GdbRegCache"; } }; class AMD64GdbRegCache : public BaseGdbRegCache { using BaseGdbRegCache::BaseGdbRegCache; private: struct M5_ATTR_PACKED { uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rsi; uint64_t rdi; uint64_t rbp; uint64_t rsp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rip; uint32_t eflags; uint32_t cs; uint32_t ss; uint32_t ds; uint32_t es; uint32_t fs; uint32_t gs; /* * We do not model st[], FPU status regs, xmm[] etc. * While it's not ok to have G-packets larger than what gdb * knows about, it is ok to have smaller ones. */ } r; public: char *data() const { return (char *)&r; } size_t size() const { return sizeof(r); } void getRegs(ThreadContext*); void setRegs(ThreadContext*) const; const std::string name() const { return gdb->name() + ".AMD64GdbRegCache"; } }; X86GdbRegCache regCache32; AMD64GdbRegCache regCache64; public: RemoteGDB(System *system, ThreadContext *context); BaseGdbRegCache *gdbRegs(); }; } // namespace X86ISA #endif // __ARCH_X86_REMOTEGDB_HH__ <|endoftext|>
<commit_before>/* * TWI/I2C library for Arduino Zero * Copyright (c) 2015 Arduino LLC. All rights reserved. * * 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 */ extern "C" { #include <string.h> } #include <Arduino.h> #include <wiring_private.h> #include "Wire.h" TwoWire::TwoWire(SERCOM * s) { this->sercom = s; transmissionBegun = false; } void TwoWire::begin(void) { //Master Mode sercom->initMasterWIRE(TWI_CLOCK); sercom->enableWIRE(); pinPeripheral(PIN_WIRE_SDA, g_APinDescription[PIN_WIRE_SDA].ulPinType); pinPeripheral(PIN_WIRE_SCL, g_APinDescription[PIN_WIRE_SCL].ulPinType); } void TwoWire::begin(uint8_t address) { //Slave mode sercom->initSlaveWIRE(address); sercom->enableWIRE(); } void TwoWire::setClock(uint32_t frequency) { // dummy funtion } uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) { if(quantity == 0) { return 0; } size_t byteRead = 0; if(sercom->startTransmissionWIRE(address, WIRE_READ_FLAG)) { // Read first data rxBuffer.store_char(sercom->readDataWIRE()); // Connected to slave //while(toRead--) for(byteRead = 0; byteRead < quantity; ++byteRead) { if( byteRead == quantity - 1) // Stop transmission { sercom->prepareNackBitWIRE(); // Prepare NACK to stop slave transmission //sercom->readDataWIRE(); // Clear data register to send NACK sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop } else // Continue transmission { sercom->prepareAckBitWIRE(); // Prepare Acknowledge sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave rxBuffer.store_char( sercom->readDataWIRE() ); // Read data and send the ACK } } } return byteRead; } uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity) { return requestFrom(address, quantity, true); } void TwoWire::beginTransmission(uint8_t address) { // save address of target and clear buffer txAddress = address; txBuffer.clear(); transmissionBegun = true; } // Errors: // 0 : Success // 1 : Data too long // 2 : NACK on transmit of address // 3 : NACK on transmit of data // 4 : Other error uint8_t TwoWire::endTransmission(bool stopBit) { transmissionBegun = false ; // Check if there are data to send if ( txBuffer.available() == 0) { return 4 ; } // Start I2C transmission if ( !sercom->startTransmissionWIRE( txAddress, WIRE_WRITE_FLAG ) ) { sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); return 2 ; // Address error } // Send all buffer while( txBuffer.available() ) { // Trying to send data if ( !sercom->sendDataMasterWIRE( txBuffer.read_char() ) ) { sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); return 3 ; // Nack or error } if(txBuffer.available() == 0) { sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); } } return 0; } uint8_t TwoWire::endTransmission() { return endTransmission(true); } size_t TwoWire::write(uint8_t ucData) { if(sercom->isMasterWIRE()) { // No writing, without begun transmission or a full buffer if ( !transmissionBegun || txBuffer.isFull() ) { return 0 ; } txBuffer.store_char( ucData ) ; return 1 ; } else { if(sercom->sendDataSlaveWIRE( ucData )) { return 1; } } return 0; } size_t TwoWire::write(const uint8_t *data, size_t quantity) { //Try to store all data for(size_t i = 0; i < quantity; ++i) { //Return the number of data stored, when the buffer is full (if write return 0) if(!write(data[i])) return i; } //All data stored return quantity; } int TwoWire::available(void) { return rxBuffer.available(); } int TwoWire::read(void) { return rxBuffer.read_char(); } int TwoWire::peek(void) { return rxBuffer.peek(); } void TwoWire::flush(void) { // Do nothing, use endTransmission(..) to force // data transfer. } void TwoWire::onReceive(void(*function)(int)) { onReceiveCallback = function; } void TwoWire::onRequest(void(*function)(void)) { onRequestCallback = function; } void TwoWire::onService(void) { if ( sercom->isSlaveWIRE() ) { //Received data if(sercom->isDataReadyWIRE()) { //Store data rxBuffer.store_char(sercom->readDataWIRE()); //Stop or Restart detected if(sercom->isStopDetectedWIRE() || sercom->isRestartDetectedWIRE()) { //Calling onReceiveCallback, if exists if(onReceiveCallback) { onReceiveCallback(available()); } } } //Address Match if(sercom->isAddressMatch()) { //Is a request ? if(sercom->isMasterReadOperationWIRE()) { //Calling onRequestCallback, if exists if(onRequestCallback) { onRequestCallback(); } } } } } /* void TwoWire::onService(void) { // Retrieve interrupt status uint32_t sr = TWI_GetStatus(twi); if (status == SLAVE_IDLE && TWI_STATUS_SVACC(sr)) { TWI_DisableIt(twi, TWI_IDR_SVACC); TWI_EnableIt(twi, TWI_IER_RXRDY | TWI_IER_GACC | TWI_IER_NACK | TWI_IER_EOSACC | TWI_IER_SCL_WS | TWI_IER_TXCOMP); srvBufferLength = 0; srvBufferIndex = 0; // Detect if we should go into RECV or SEND status // SVREAD==1 means *master* reading -> SLAVE_SEND if (!TWI_STATUS_SVREAD(sr)) { status = SLAVE_RECV; } else { status = SLAVE_SEND; // Alert calling program to generate a response ASAP if (onRequestCallback) onRequestCallback(); else // create a default 1-byte response write((uint8_t) 0); } } if (status != SLAVE_IDLE) { if (TWI_STATUS_TXCOMP(sr) && TWI_STATUS_EOSACC(sr)) { if (status == SLAVE_RECV && onReceiveCallback) { // Copy data into rxBuffer // (allows to receive another packet while the // user program reads actual data) for (uint8_t i = 0; i < srvBufferLength; ++i) rxBuffer[i] = srvBuffer[i]; rxBufferIndex = 0; rxBufferLength = srvBufferLength; // Alert calling program onReceiveCallback( rxBufferLength); } // Transfer completed TWI_EnableIt(twi, TWI_SR_SVACC); TWI_DisableIt(twi, TWI_IDR_RXRDY | TWI_IDR_GACC | TWI_IDR_NACK | TWI_IDR_EOSACC | TWI_IDR_SCL_WS | TWI_IER_TXCOMP); status = SLAVE_IDLE; } } if (status == SLAVE_RECV) { if (TWI_STATUS_RXRDY(sr)) { if (srvBufferLength < BUFFER_LENGTH) srvBuffer[srvBufferLength++] = TWI_ReadByte(twi); } } if (status == SLAVE_SEND) { if (TWI_STATUS_TXRDY(sr) && !TWI_STATUS_NACK(sr)) { uint8_t c = 'x'; if (srvBufferIndex < srvBufferLength) c = srvBuffer[srvBufferIndex++]; TWI_WriteByte(twi, c); } } } */ #if WIRE_INTERFACES_COUNT > 0 /*static void Wire_Init(void) { pmc_enable_periph_clk(WIRE_INTERFACE_ID); PIO_Configure( g_APinDescription[PIN_WIRE_SDA].pPort, g_APinDescription[PIN_WIRE_SDA].ulPinType, g_APinDescription[PIN_WIRE_SDA].ulPin, g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration); PIO_Configure( g_APinDescription[PIN_WIRE_SCL].pPort, g_APinDescription[PIN_WIRE_SCL].ulPinType, g_APinDescription[PIN_WIRE_SCL].ulPin, g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration); NVIC_DisableIRQ(WIRE_ISR_ID); NVIC_ClearPendingIRQ(WIRE_ISR_ID); NVIC_SetPriority(WIRE_ISR_ID, 0); NVIC_EnableIRQ(WIRE_ISR_ID); }*/ TwoWire Wire(&sercom3); void SERCOM3_Handler(void) { Wire.onService(); } #endif <commit_msg>[Wire] simplified coding unnecessarily complex (hfvogt)<commit_after>/* * TWI/I2C library for Arduino Zero * Copyright (c) 2015 Arduino LLC. All rights reserved. * * 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 */ extern "C" { #include <string.h> } #include <Arduino.h> #include <wiring_private.h> #include "Wire.h" TwoWire::TwoWire(SERCOM * s) { this->sercom = s; transmissionBegun = false; } void TwoWire::begin(void) { //Master Mode sercom->initMasterWIRE(TWI_CLOCK); sercom->enableWIRE(); pinPeripheral(PIN_WIRE_SDA, g_APinDescription[PIN_WIRE_SDA].ulPinType); pinPeripheral(PIN_WIRE_SCL, g_APinDescription[PIN_WIRE_SCL].ulPinType); } void TwoWire::begin(uint8_t address) { //Slave mode sercom->initSlaveWIRE(address); sercom->enableWIRE(); } void TwoWire::setClock(uint32_t frequency) { // dummy funtion } uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) { if(quantity == 0) { return 0; } size_t byteRead = 0; if(sercom->startTransmissionWIRE(address, WIRE_READ_FLAG)) { // Read first data rxBuffer.store_char(sercom->readDataWIRE()); // Connected to slave for (byteRead = 1; byteRead < quantity; ++byteRead) { sercom->prepareAckBitWIRE(); // Prepare Acknowledge sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave rxBuffer.store_char(sercom->readDataWIRE()); // Read data and send the ACK } sercom->prepareNackBitWIRE(); // Prepare NACK to stop slave transmission //sercom->readDataWIRE(); // Clear data register to send NACK sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop } return byteRead; } uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity) { return requestFrom(address, quantity, true); } void TwoWire::beginTransmission(uint8_t address) { // save address of target and clear buffer txAddress = address; txBuffer.clear(); transmissionBegun = true; } // Errors: // 0 : Success // 1 : Data too long // 2 : NACK on transmit of address // 3 : NACK on transmit of data // 4 : Other error uint8_t TwoWire::endTransmission(bool stopBit) { transmissionBegun = false ; // Check if there are data to send if ( txBuffer.available() == 0) { return 4 ; } // Start I2C transmission if ( !sercom->startTransmissionWIRE( txAddress, WIRE_WRITE_FLAG ) ) { sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); return 2 ; // Address error } // Send all buffer while( txBuffer.available() ) { // Trying to send data if ( !sercom->sendDataMasterWIRE( txBuffer.read_char() ) ) { sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); return 3 ; // Nack or error } } sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); return 0; } uint8_t TwoWire::endTransmission() { return endTransmission(true); } size_t TwoWire::write(uint8_t ucData) { if(sercom->isMasterWIRE()) { // No writing, without begun transmission or a full buffer if ( !transmissionBegun || txBuffer.isFull() ) { return 0 ; } txBuffer.store_char( ucData ) ; return 1 ; } else { if(sercom->sendDataSlaveWIRE( ucData )) { return 1; } } return 0; } size_t TwoWire::write(const uint8_t *data, size_t quantity) { //Try to store all data for(size_t i = 0; i < quantity; ++i) { //Return the number of data stored, when the buffer is full (if write return 0) if(!write(data[i])) return i; } //All data stored return quantity; } int TwoWire::available(void) { return rxBuffer.available(); } int TwoWire::read(void) { return rxBuffer.read_char(); } int TwoWire::peek(void) { return rxBuffer.peek(); } void TwoWire::flush(void) { // Do nothing, use endTransmission(..) to force // data transfer. } void TwoWire::onReceive(void(*function)(int)) { onReceiveCallback = function; } void TwoWire::onRequest(void(*function)(void)) { onRequestCallback = function; } void TwoWire::onService(void) { if ( sercom->isSlaveWIRE() ) { //Received data if(sercom->isDataReadyWIRE()) { //Store data rxBuffer.store_char(sercom->readDataWIRE()); //Stop or Restart detected if(sercom->isStopDetectedWIRE() || sercom->isRestartDetectedWIRE()) { //Calling onReceiveCallback, if exists if(onReceiveCallback) { onReceiveCallback(available()); } } } //Address Match if(sercom->isAddressMatch()) { //Is a request ? if(sercom->isMasterReadOperationWIRE()) { //Calling onRequestCallback, if exists if(onRequestCallback) { onRequestCallback(); } } } } } /* void TwoWire::onService(void) { // Retrieve interrupt status uint32_t sr = TWI_GetStatus(twi); if (status == SLAVE_IDLE && TWI_STATUS_SVACC(sr)) { TWI_DisableIt(twi, TWI_IDR_SVACC); TWI_EnableIt(twi, TWI_IER_RXRDY | TWI_IER_GACC | TWI_IER_NACK | TWI_IER_EOSACC | TWI_IER_SCL_WS | TWI_IER_TXCOMP); srvBufferLength = 0; srvBufferIndex = 0; // Detect if we should go into RECV or SEND status // SVREAD==1 means *master* reading -> SLAVE_SEND if (!TWI_STATUS_SVREAD(sr)) { status = SLAVE_RECV; } else { status = SLAVE_SEND; // Alert calling program to generate a response ASAP if (onRequestCallback) onRequestCallback(); else // create a default 1-byte response write((uint8_t) 0); } } if (status != SLAVE_IDLE) { if (TWI_STATUS_TXCOMP(sr) && TWI_STATUS_EOSACC(sr)) { if (status == SLAVE_RECV && onReceiveCallback) { // Copy data into rxBuffer // (allows to receive another packet while the // user program reads actual data) for (uint8_t i = 0; i < srvBufferLength; ++i) rxBuffer[i] = srvBuffer[i]; rxBufferIndex = 0; rxBufferLength = srvBufferLength; // Alert calling program onReceiveCallback( rxBufferLength); } // Transfer completed TWI_EnableIt(twi, TWI_SR_SVACC); TWI_DisableIt(twi, TWI_IDR_RXRDY | TWI_IDR_GACC | TWI_IDR_NACK | TWI_IDR_EOSACC | TWI_IDR_SCL_WS | TWI_IER_TXCOMP); status = SLAVE_IDLE; } } if (status == SLAVE_RECV) { if (TWI_STATUS_RXRDY(sr)) { if (srvBufferLength < BUFFER_LENGTH) srvBuffer[srvBufferLength++] = TWI_ReadByte(twi); } } if (status == SLAVE_SEND) { if (TWI_STATUS_TXRDY(sr) && !TWI_STATUS_NACK(sr)) { uint8_t c = 'x'; if (srvBufferIndex < srvBufferLength) c = srvBuffer[srvBufferIndex++]; TWI_WriteByte(twi, c); } } } */ #if WIRE_INTERFACES_COUNT > 0 /*static void Wire_Init(void) { pmc_enable_periph_clk(WIRE_INTERFACE_ID); PIO_Configure( g_APinDescription[PIN_WIRE_SDA].pPort, g_APinDescription[PIN_WIRE_SDA].ulPinType, g_APinDescription[PIN_WIRE_SDA].ulPin, g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration); PIO_Configure( g_APinDescription[PIN_WIRE_SCL].pPort, g_APinDescription[PIN_WIRE_SCL].ulPinType, g_APinDescription[PIN_WIRE_SCL].ulPin, g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration); NVIC_DisableIRQ(WIRE_ISR_ID); NVIC_ClearPendingIRQ(WIRE_ISR_ID); NVIC_SetPriority(WIRE_ISR_ID, 0); NVIC_EnableIRQ(WIRE_ISR_ID); }*/ TwoWire Wire(&sercom3); void SERCOM3_Handler(void) { Wire.onService(); } #endif <|endoftext|>
<commit_before>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the FlacAudioSource class. * @see audio/audio_source.hpp */ #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <FLAC++/decoder.h> #include "../../errors.hpp" #include "../../messages.h" #include "../sample_formats.hpp" #include "../audio_source.hpp" #include "flac.hpp" FlacAudioSource::FlacAudioSource(const std::string &path) : AudioSource(path), buffer() { auto err = this->init(path); if (err != FLAC__STREAM_DECODER_INIT_STATUS_OK) { throw FileError("flac: can't open " + path + ": " + FlacAudioSource::InitStrError(err)); } // We need to decode some to get the sample rate etc. // Because libflac is callback-based, we have to spin on waiting for // the sample rate to materialise. do { this->process_single(); } while (this->SampleRate() == 0); Debug() << "flac: sample rate:" << this->SampleRate() << std::endl; Debug() << "flac: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "flac: mono bytes per sample:" << (this->get_bits_per_sample() / 8) << std::endl; Debug() << "flac: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "flac: playd format:" << (int)this->OutputSampleFormat() << std::endl; } FlacAudioSource::~FlacAudioSource() { this->finish(); } /* static */ std::string FlacAudioSource::InitStrError(int err) { switch (err) { case FLAC__STREAM_DECODER_INIT_STATUS_OK: return "success"; case FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER: return "libflac missing support for container"; case FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS: return "internal error: bad callbacks"; case FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR: return "out of memory"; case FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE: return "fopen() failed"; case FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED: return "internal error: already initialised?"; default: return "unknown error"; } } std::uint8_t FlacAudioSource::ChannelCount() const { return static_cast<std::uint8_t>(this->get_channels()); } std::uint32_t FlacAudioSource::SampleRate() const { auto rate = this->get_sample_rate(); assert(0 < rate); assert(rate < UINT32_MAX); return static_cast<std::uint32_t>(rate); } std::uint64_t FlacAudioSource::Seek(std::uint64_t in_samples) { // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(this->get_total_samples()); if (clen < in_samples) { Debug() << "flac: seek at" << in_samples << "past EOF at" << clen << std::endl; throw SeekError(MSG_SEEK_FAIL); } bool seeked = this->seek_absolute(in_samples); if (!seeked || this->get_state() == FLAC__STREAM_DECODER_SEEK_ERROR) { Debug() << "flac: seek failed" << std::endl; this->flush(); throw SeekError(MSG_SEEK_FAIL); } // The actual seek position may not be the same as the requested // position. // get_decode_position() tells us the new position, in bytes. uint64_t new_bytes = 0; if (!this->get_decode_position(&new_bytes)) { Debug() << "flac: seek failed" << std::endl; this->flush(); throw SeekError(MSG_SEEK_FAIL); } // Don't use this->BytesPerSample() here--it returns bytes per *output* // sample. return new_bytes / (this->get_bits_per_sample() / 8); } FlacAudioSource::DecodeResult FlacAudioSource::Decode() { // Have we hit the end of the file? if (this->get_state() == FLAC__STREAM_DECODER_END_OF_STREAM) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } if (!this->process_single()) { // Something went wrong... or we're at end of file. // Let's find out. int s = this->get_state(); if (s == FLAC__STREAM_DECODER_END_OF_STREAM) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } else { Debug() << "flac: decode error" << std::endl; // TODO: handle error correctly return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } } // Else, we're good to go. // The callback will have set up the vector to have precisely the // correct number of bytes in it. uint8_t *begin = reinterpret_cast<uint8_t *>(&*this->buffer.begin()); uint8_t *end = reinterpret_cast<uint8_t *>(&*this->buffer.end()); return std::make_pair(DecodeState::DECODING, DecodeVector(begin, end)); } SampleFormat FlacAudioSource::OutputSampleFormat() const { // All FLAC output formats are signed integer. // See https://xiph.org/flac/api/group__flac__stream__decoder.html. // See write_callback() for an explanation of why this is always 32 // bits. // (This is also why BytesPerSample() is slightly weird.) return SampleFormat::PACKED_SIGNED_INT_32; } FLAC__StreamDecoderWriteStatus FlacAudioSource::write_callback( const FLAC__Frame *frame, const FLAC__int32 *const buf[]) { // Each buffer index contains a full sample, padded up to 32 bits. // These are in planar (per-channel) format. this->buffer.clear(); assert(this->buffer.empty()); size_t nsamples = frame->header.blocksize; if (nsamples == 0) { // No point trying to decode 0 samples. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } size_t nchans = frame->header.channels; // Need to prepare the buffer for writing however many bytes this works // out as. // We need to get the bytes-per-sample from the *frame*, because it may // well be that the global bytes-per-sample count hasn't populated yet. int bits = frame->header.bits_per_sample; this->buffer = std::vector<std::int32_t>(nsamples * nchans, 0); // FLAC returns its samples in planar format, and playd wants them to be // packed. // We do a simple interleaving here. size_t sc = 0; for (size_t s = 0; s < nsamples; s++) { for (size_t c = 0; c < nchans; c++) { std::int32_t samp = buf[c][s]; // Now, we've set up so that we always send 32-bit // samples, but this 32-bit integer may actually contain // an 8, 16, or 24 bit sample. // How do we convert to 32 bit? Simple--left bitshift // up the missing number of bits. this->buffer[sc] = samp << (32 - bits); sc++; } } assert(this->buffer.size() == nchans * nsamples); assert(sc == nchans * nsamples); return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } void FlacAudioSource::error_callback(FLAC__StreamDecoderErrorStatus) { // Currently ignored. // TODO(CaptainHayashi): not ignore these? } <commit_msg>Fix assertion failure.<commit_after>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the FlacAudioSource class. * @see audio/audio_source.hpp */ #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <FLAC++/decoder.h> #include "../../errors.hpp" #include "../../messages.h" #include "../sample_formats.hpp" #include "../audio_source.hpp" #include "flac.hpp" FlacAudioSource::FlacAudioSource(const std::string &path) : AudioSource(path), buffer() { auto err = this->init(path); if (err != FLAC__STREAM_DECODER_INIT_STATUS_OK) { throw FileError("flac: can't open " + path + ": " + FlacAudioSource::InitStrError(err)); } // We need to decode some to get the sample rate etc. // Because libflac is callback-based, we have to spin on waiting for // the sample rate to materialise. do { this->process_single(); } while (this->get_sample_rate() == 0); Debug() << "flac: sample rate:" << this->SampleRate() << std::endl; Debug() << "flac: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "flac: mono bytes per sample:" << (this->get_bits_per_sample() / 8) << std::endl; Debug() << "flac: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "flac: playd format:" << (int)this->OutputSampleFormat() << std::endl; } FlacAudioSource::~FlacAudioSource() { this->finish(); } /* static */ std::string FlacAudioSource::InitStrError(int err) { switch (err) { case FLAC__STREAM_DECODER_INIT_STATUS_OK: return "success"; case FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER: return "libflac missing support for container"; case FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS: return "internal error: bad callbacks"; case FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR: return "out of memory"; case FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE: return "fopen() failed"; case FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED: return "internal error: already initialised?"; default: return "unknown error"; } } std::uint8_t FlacAudioSource::ChannelCount() const { return static_cast<std::uint8_t>(this->get_channels()); } std::uint32_t FlacAudioSource::SampleRate() const { auto rate = this->get_sample_rate(); assert(0 < rate); assert(rate < UINT32_MAX); return static_cast<std::uint32_t>(rate); } std::uint64_t FlacAudioSource::Seek(std::uint64_t in_samples) { // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(this->get_total_samples()); if (clen < in_samples) { Debug() << "flac: seek at" << in_samples << "past EOF at" << clen << std::endl; throw SeekError(MSG_SEEK_FAIL); } bool seeked = this->seek_absolute(in_samples); if (!seeked || this->get_state() == FLAC__STREAM_DECODER_SEEK_ERROR) { Debug() << "flac: seek failed" << std::endl; this->flush(); throw SeekError(MSG_SEEK_FAIL); } // The actual seek position may not be the same as the requested // position. // get_decode_position() tells us the new position, in bytes. uint64_t new_bytes = 0; if (!this->get_decode_position(&new_bytes)) { Debug() << "flac: seek failed" << std::endl; this->flush(); throw SeekError(MSG_SEEK_FAIL); } // Don't use this->BytesPerSample() here--it returns bytes per *output* // sample. return new_bytes / (this->get_bits_per_sample() / 8); } FlacAudioSource::DecodeResult FlacAudioSource::Decode() { // Have we hit the end of the file? if (this->get_state() == FLAC__STREAM_DECODER_END_OF_STREAM) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } if (!this->process_single()) { // Something went wrong... or we're at end of file. // Let's find out. int s = this->get_state(); if (s == FLAC__STREAM_DECODER_END_OF_STREAM) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } else { Debug() << "flac: decode error" << std::endl; // TODO: handle error correctly return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } } // Else, we're good to go. // The callback will have set up the vector to have precisely the // correct number of bytes in it. uint8_t *begin = reinterpret_cast<uint8_t *>(&*this->buffer.begin()); uint8_t *end = reinterpret_cast<uint8_t *>(&*this->buffer.end()); return std::make_pair(DecodeState::DECODING, DecodeVector(begin, end)); } SampleFormat FlacAudioSource::OutputSampleFormat() const { // All FLAC output formats are signed integer. // See https://xiph.org/flac/api/group__flac__stream__decoder.html. // See write_callback() for an explanation of why this is always 32 // bits. // (This is also why BytesPerSample() is slightly weird.) return SampleFormat::PACKED_SIGNED_INT_32; } FLAC__StreamDecoderWriteStatus FlacAudioSource::write_callback( const FLAC__Frame *frame, const FLAC__int32 *const buf[]) { // Each buffer index contains a full sample, padded up to 32 bits. // These are in planar (per-channel) format. this->buffer.clear(); assert(this->buffer.empty()); size_t nsamples = frame->header.blocksize; if (nsamples == 0) { // No point trying to decode 0 samples. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } size_t nchans = frame->header.channels; // Need to prepare the buffer for writing however many bytes this works // out as. // We need to get the bytes-per-sample from the *frame*, because it may // well be that the global bytes-per-sample count hasn't populated yet. int bits = frame->header.bits_per_sample; this->buffer = std::vector<std::int32_t>(nsamples * nchans, 0); // FLAC returns its samples in planar format, and playd wants them to be // packed. // We do a simple interleaving here. size_t sc = 0; for (size_t s = 0; s < nsamples; s++) { for (size_t c = 0; c < nchans; c++) { std::int32_t samp = buf[c][s]; // Now, we've set up so that we always send 32-bit // samples, but this 32-bit integer may actually contain // an 8, 16, or 24 bit sample. // How do we convert to 32 bit? Simple--left bitshift // up the missing number of bits. this->buffer[sc] = samp << (32 - bits); sc++; } } assert(this->buffer.size() == nchans * nsamples); assert(sc == nchans * nsamples); return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } void FlacAudioSource::error_callback(FLAC__StreamDecoderErrorStatus) { // Currently ignored. // TODO(CaptainHayashi): not ignore these? } <|endoftext|>
<commit_before>#ifndef __ET_SOCKET_HANDLER__ #define __ET_SOCKET_HANDLER__ #include "Headers.hpp" #include "SocketEndpoint.hpp" namespace et { class SocketHandler { public: virtual ~SocketHandler() {} virtual bool hasData(int fd) = 0; virtual ssize_t read(int fd, void* buf, size_t count) = 0; virtual ssize_t write(int fd, const void* buf, size_t count) = 0; void readAll(int fd, void* buf, size_t count, bool timeout); int writeAllOrReturn(int fd, const void* buf, size_t count); void writeAllOrThrow(int fd, const void* buf, size_t count, bool timeout); template <typename T> inline T readProto(int fd, bool timeout) { T t; int64_t length; readAll(fd, &length, sizeof(int64_t), timeout); if (length <= 0 || length > 128 * 1024 * 1024) { // If the message is <= 0 or too big, assume this is a bad packet and throw string s = string("Invalid size (<=0 or >128 MB): ") + to_string(length); throw std::runtime_error(s.c_str()); } string s(length, 0); readAll(fd, &s[0], length, timeout); if (!t.ParseFromString(s)) { throw std::runtime_error("Invalid proto"); } return t; } template <typename T> inline void writeProto(int fd, const T& t, bool timeout) { string s; if(!t.SerializeToString(&s)) { LOG(FATAL) << "Serialization of " << t.DebugString() << " failed!"; } int64_t length = s.length(); if (length <= 0 || length > 128*1024*1024) { LOG(FATAL) << "Invalid proto length: " << length << " For proto " << t.DebugString(); } writeAllOrThrow(fd, &length, sizeof(int64_t), timeout); writeAllOrThrow(fd, &s[0], length, timeout); } inline string readMessage(int fd) { int64_t length; readAll(fd, (char*)&length, sizeof(int64_t), false); if (length <= 0 || length > 128 * 1024 * 1024) { // If the message is <= 0 or too big, assume this is a bad packet and throw string s("Invalid size (<=0 or >128 MB): "); s += std::to_string(length); throw std::runtime_error(s.c_str()); } string s(length, 0); readAll(fd, &s[0], length, false); return s; } inline void writeMessage(int fd, const string& s) { int64_t length = s.length(); if (length <= 0 || length > 128*1024*1024) { LOG(FATAL) << "Invalid message length: " << length; } writeAllOrThrow(fd, (const char*)&length, sizeof(int64_t), false); writeAllOrThrow(fd, &s[0], length, false); } inline void writeB64(int fd, const char* buf, size_t count) { int encodedLength = base64::Base64::EncodedLength(count); string s(encodedLength, '\0'); if (!base64::Base64::Encode(buf, count, &s[0], s.length())) { throw runtime_error("b64 decode failed"); } writeAllOrThrow(fd, &s[0], s.length(), false); } inline void readB64(int fd, char* buf, size_t count) { int encodedLength = base64::Base64::EncodedLength(count); string s(encodedLength, '\0'); readAll(fd, &s[0], s.length(), false); if (!base64::Base64::Decode((const char*)&s[0], s.length(), buf, count)) { throw runtime_error("b64 decode failed"); } } inline void readB64EncodedLength(int fd, string* out, size_t encodedLength) { string s(encodedLength, '\0'); readAll(fd, &s[0], s.length(), false); if (!base64::Base64::Decode(s, out)) { throw runtime_error("b64 decode failed"); } } virtual int connect(const SocketEndpoint& endpoint) = 0; virtual set<int> listen(const SocketEndpoint& endpoint) = 0; virtual set<int> getEndpointFds(const SocketEndpoint& endpoint) = 0; virtual int accept(int fd) = 0; virtual void stopListening(const SocketEndpoint& endpoint) = 0; virtual void close(int fd) = 0; virtual vector<int> getActiveSockets() = 0; }; } // namespace et #endif // __ET_SOCKET_HANDLER__ <commit_msg>Handle 0-sized protos<commit_after>#ifndef __ET_SOCKET_HANDLER__ #define __ET_SOCKET_HANDLER__ #include "Headers.hpp" #include "SocketEndpoint.hpp" namespace et { class SocketHandler { public: virtual ~SocketHandler() {} virtual bool hasData(int fd) = 0; virtual ssize_t read(int fd, void* buf, size_t count) = 0; virtual ssize_t write(int fd, const void* buf, size_t count) = 0; void readAll(int fd, void* buf, size_t count, bool timeout); int writeAllOrReturn(int fd, const void* buf, size_t count); void writeAllOrThrow(int fd, const void* buf, size_t count, bool timeout); template <typename T> inline T readProto(int fd, bool timeout) { T t; int64_t length; readAll(fd, &length, sizeof(int64_t), timeout); if (length < 0 || length > 128 * 1024 * 1024) { // If the message is <= 0 or too big, assume this is a bad packet and throw string s = string("Invalid size (<0 or >128 MB): ") + to_string(length); throw std::runtime_error(s.c_str()); } if (length == 0) { return t; } string s(length, '\0'); readAll(fd, &s[0], length, timeout); if (!t.ParseFromString(s)) { throw std::runtime_error("Invalid proto"); } return t; } template <typename T> inline void writeProto(int fd, const T& t, bool timeout) { string s; if(!t.SerializeToString(&s)) { LOG(FATAL) << "Serialization of " << t.DebugString() << " failed!"; } int64_t length = s.length(); if (length < 0 || length > 128*1024*1024) { LOG(FATAL) << "Invalid proto length: " << length << " For proto " << t.DebugString(); } writeAllOrThrow(fd, &length, sizeof(int64_t), timeout); if (length > 0) { writeAllOrThrow(fd, &s[0], length, timeout); } } inline string readMessage(int fd) { int64_t length; readAll(fd, (char*)&length, sizeof(int64_t), false); if (length < 0 || length > 128 * 1024 * 1024) { // If the message is < 0 or too big, assume this is a bad packet and throw string s("Invalid size (<0 or >128 MB): "); s += std::to_string(length); throw std::runtime_error(s.c_str()); } if (length == 0) { return ""; } string s(length, '\0'); readAll(fd, &s[0], length, false); return s; } inline void writeMessage(int fd, const string& s) { int64_t length = s.length(); if (length < 0 || length > 128*1024*1024) { LOG(FATAL) << "Invalid message length: " << length; } writeAllOrThrow(fd, (const char*)&length, sizeof(int64_t), false); if (length) { writeAllOrThrow(fd, &s[0], length, false); } } inline void writeB64(int fd, const char* buf, size_t count) { int encodedLength = base64::Base64::EncodedLength(count); string s(encodedLength, '\0'); if (!base64::Base64::Encode(buf, count, &s[0], s.length())) { throw runtime_error("b64 decode failed"); } writeAllOrThrow(fd, &s[0], s.length(), false); } inline void readB64(int fd, char* buf, size_t count) { int encodedLength = base64::Base64::EncodedLength(count); string s(encodedLength, '\0'); readAll(fd, &s[0], s.length(), false); if (!base64::Base64::Decode((const char*)&s[0], s.length(), buf, count)) { throw runtime_error("b64 decode failed"); } } inline void readB64EncodedLength(int fd, string* out, size_t encodedLength) { string s(encodedLength, '\0'); readAll(fd, &s[0], s.length(), false); if (!base64::Base64::Decode(s, out)) { throw runtime_error("b64 decode failed"); } } virtual int connect(const SocketEndpoint& endpoint) = 0; virtual set<int> listen(const SocketEndpoint& endpoint) = 0; virtual set<int> getEndpointFds(const SocketEndpoint& endpoint) = 0; virtual int accept(int fd) = 0; virtual void stopListening(const SocketEndpoint& endpoint) = 0; virtual void close(int fd) = 0; virtual vector<int> getActiveSockets() = 0; }; } // namespace et #endif // __ET_SOCKET_HANDLER__ <|endoftext|>
<commit_before>/* * libgamelib * * Copyright (C) 2013 Karol Herbst <gamelib@karolherbst.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pch.h" #include "windowsinformation.h" #include <cstdlib> GAMELIB_NAMESPACE_START(core) std::string WindowsInformation::getEnvSeperator() { return ":"; } boost::filesystem::path WindowsInformation::getSystemRoot() { return "/"; } boost::filesystem::path WindowsInformation::getUserPath() { return getEnv("HOME"); } GAMELIB_NAMESPACE_END(core) <commit_msg>core/windowsinformation: I forgot to change the methods<commit_after>/* * libgamelib * * Copyright (C) 2013 Karol Herbst <gamelib@karolherbst.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pch.h" #include "windowsinformation.h" #include <cstdlib> #include <Shlobj.h> GAMELIB_NAMESPACE_START(core) std::string WindowsInformation::getEnvSeperator() { return ";"; } boost::filesystem::path WindowsInformation::getSystemRoot() { return "C:\\"; } boost::filesystem::path WindowsInformation::getUserPath() { TCHAR szPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath); return szPath; } GAMELIB_NAMESPACE_END(core) <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mdialog.h" #include "mdialog_p.h" #include <mbuttonmodel.h> #include <MDebug> #include <MDismissEvent> #include <MHomeButtonPanel> #include <MLocale> #include <MScene> #include <MWindow> #ifdef Q_WS_X11 # include <QX11Info> # include <X11/Xlib.h> #endif #include <QSignalMapper> #include <MApplication> #include <MSceneManager> #include "mwidgetcreator.h" M_REGISTER_WIDGET(MDialog) MDialogPrivate::MDialogPrivate() : clickedButton(0), buttonClickedMapper(0), dumbMode(false), standAloneWindow(0), homeButtonPanel(0), suicideAfterDestroyingStandAloneWindow(false) { } MDialogPrivate::~MDialogPrivate() { if (buttonClickedMapper) { delete buttonClickedMapper; buttonClickedMapper = 0; } if (standAloneWindow) { Q_Q(MDialog); standAloneWindow->scene()->removeItem(q); delete standAloneWindow; standAloneWindow = 0; } } void MDialogPrivate::init() { Q_Q(MDialog); clickedButton = 0; q->setFocusPolicy(Qt::ClickFocus); } void MDialogPrivate::appear(MSceneWindow::DeletionPolicy policy) { Q_Q(MDialog); MWindow *window; if (q->isSystemModal()) { if (prepareStandAloneAppearance(policy)) { q->appear(standAloneWindow); } } else { window = MApplication::activeWindow(); if (window) { q->appear(window, policy); } else { mWarning("MDialog") << "Cannot appear. No MWindow currently active."; } } } void MDialogPrivate::addStandardButtons(M::StandardButtons standardButtons) { Q_Q(MDialog); uint buttonFlag = M::FirstButton; while (buttonFlag <= M::LastButton) { if (standardButtons.testFlag((M::StandardButton)buttonFlag)) { q->model()->addButton((M::StandardButton)buttonFlag); } buttonFlag = buttonFlag << 1; } } void MDialogPrivate::_q_buttonClicked(QObject *obj) { Q_Q(MDialog); MButtonModel *buttonModel = 0; buttonModel = qobject_cast<MButtonModel *>(obj); if (buttonModel) { clickedButton = buttonModel; int result = resultFromStandardButtonId(q->model()->standardButton(buttonModel)); q->done(result); } } void MDialogPrivate::updateStandAloneHomeButtonVisibility() { Q_Q(MDialog); if (q->isSystemModal()) { // Remove the home button if it's there. if (homeButtonPanel) { if (homeButtonPanel->scene() != 0) { Q_ASSERT(homeButtonPanel->scene() == standAloneWindow->scene()); standAloneWindow->sceneManager()->disappearSceneWindowNow(homeButtonPanel); } delete homeButtonPanel; homeButtonPanel = 0; } } else { // Put a home button on the system modal window homeButtonPanel = new MHomeButtonPanel(); standAloneWindow->connect(homeButtonPanel, SIGNAL(buttonClicked()), SLOT(showMinimized())); standAloneWindow->sceneManager()->appearSceneWindowNow(homeButtonPanel); } } void MDialogPrivate::_q_onStandAloneDialogDisappeared() { Q_Q(MDialog); Q_ASSERT(standAloneWindow != 0); q->disconnect(SIGNAL(disappeared()), q, SLOT(_q_onStandAloneDialogDisappeared())); standAloneWindow->setScene(0); standAloneWindow->deleteLater(); standAloneWindow = 0; // Remove dialog from scene otherwise scene will delete dialog // on scene's destructor if (q->scene()) { q->scene()->removeItem(q); } if (homeButtonPanel) { if (homeButtonPanel->sceneManager()) homeButtonPanel->sceneManager()->disappearSceneWindowNow(homeButtonPanel); delete homeButtonPanel; homeButtonPanel = 0; } if (suicideAfterDestroyingStandAloneWindow) { q->deleteLater(); } } bool MDialogPrivate::prepareStandAloneAppearance(MSceneWindow::DeletionPolicy policy) { Q_Q(MDialog); bool ok = true; if (standAloneWindow == 0) { standAloneWindow = new MWindow(new MSceneManager); standAloneWindow->setTranslucentBackground(true); #ifdef Q_WS_X11 standAloneWindow->setAttribute(Qt::WA_X11NetWmWindowTypeDialog, true); QWidget *activeWindow = MApplication::activeWindow(); if (activeWindow && (activeWindow->winId() != standAloneWindow->winId())) { XSetTransientForHint(QX11Info::display(), standAloneWindow->winId(), activeWindow->winId()); } #endif q->connect(q, SIGNAL(disappeared()), SLOT(_q_onStandAloneDialogDisappeared())); } // We only have a home button in the stand-alone window if the // the dialog is supposed to be modeless. updateStandAloneHomeButtonVisibility(); // Dialog will handle its own deletion policy instead of scene manager // since in this case the dialog owns the scene manager and not the other // way around suicideAfterDestroyingStandAloneWindow = (policy == MSceneWindow::DestroyWhenDone); standAloneWindow->show(); // Check whether the dialog is already present in some scene manager if (shown) { if (q->sceneManager() != standAloneWindow->sceneManager()) { q->sceneManager()->disappearSceneWindowNow(q); } else { ok = false; } } return ok; } void MDialogPrivate::updateButtonClickedMappings() { Q_Q(MDialog); if (buttonClickedMapper) { delete buttonClickedMapper; buttonClickedMapper = 0; } buttonClickedMapper = new QSignalMapper(); q->connect(buttonClickedMapper, SIGNAL(mapped(QObject *)), SLOT(_q_buttonClicked(QObject *))); MButtonModel *buttonModel; MDialogButtonsList buttonModelsList = q->model()->buttons(); const int buttonModelsSize = buttonModelsList.size(); for (int i = 0; i < buttonModelsSize; ++i) { buttonModel = buttonModelsList[i]; buttonClickedMapper->connect(buttonModel, SIGNAL(clicked()), SLOT(map())); buttonClickedMapper->setMapping(buttonModel, buttonModel); } } int MDialogPrivate::resultFromStandardButtonId(int buttonId) { switch (buttonId) { case M::NoStandardButton: case M::OkButton: case M::SaveButton: case M::SaveAllButton: case M::OpenButton: case M::YesButton: case M::YesToAllButton: case M::RetryButton: case M::ApplyButton: case M::DoneButton: return MDialog::Accepted; case M::NoButton: case M::NoToAllButton: case M::AbortButton: case M::IgnoreButton: case M::CloseButton: case M::CancelButton: case M::DiscardButton: case M::HelpButton: case M::ResetButton: case M::RestoreDefaultsButton: return MDialog::Rejected; default: //Non-standard buttons should be handled by NoStandardButton case. //This should not happen. return MDialog::Accepted; }; } MDialog::MDialog() : MSceneWindow(new MDialogPrivate(), new MDialogModel(), MSceneWindow::Dialog, QString()) { Q_D(MDialog); d->init(); model()->setResultCode(MDialog::Rejected); } MDialog::MDialog(const QString &title, M::StandardButtons buttons) : MSceneWindow(new MDialogPrivate(), new MDialogModel(), MSceneWindow::Dialog, QString()) { Q_D(MDialog); d->init(); model()->setResultCode(MDialog::Rejected); setTitle(title); d->addStandardButtons(buttons); } MDialog::MDialog(MDialogPrivate *dd, MDialogModel *model, MSceneWindow::WindowType windowType) : MSceneWindow(dd, model, windowType, QString()) { Q_D(MDialog); d->init(); model->setResultCode(MDialog::Rejected); } MDialog::MDialog(MDialogPrivate *dd, M::StandardButtons buttons, MDialogModel *model, MSceneWindow::WindowType windowType) : MSceneWindow(dd, model, windowType, QString()) { Q_D(MDialog); d->init(); model->setResultCode(MDialog::Rejected); d->addStandardButtons(buttons); } MDialog::~MDialog() { } QString MDialog::title() const { return model()->title(); } void MDialog::setTitle(const QString &title) { model()->setTitle(title); } QGraphicsWidget *MDialog::centralWidget() { return model()->centralWidget(); } void MDialog::setCentralWidget(QGraphicsWidget *centralWidget) { if (model()->centralWidget()) delete model()->centralWidget(); model()->setCentralWidget(centralWidget); } void MDialog::addButton(MButtonModel *buttonModel) { model()->addButton(buttonModel); } MButtonModel *MDialog::addButton(const QString &text) { MButtonModel *buttonModel = 0; buttonModel = new MButtonModel; buttonModel->setText(text); model()->addButton(buttonModel); return buttonModel; } MButtonModel *MDialog::addButton(M::StandardButton buttonType) { return model()->addButton(buttonType); } void MDialog::removeButton(MButtonModel *buttonModel) { model()->removeButton(buttonModel); } MButtonModel *MDialog::button(M::StandardButton which) { return model()->button(which); } M::StandardButton MDialog::standardButton(MButtonModel *buttonModel) const { return model()->standardButton(buttonModel); } void MDialog::appear(MSceneWindow::DeletionPolicy policy) { Q_D(MDialog); d->appear(policy); } void MDialog::appear(MWindow *window, MSceneWindow::DeletionPolicy policy) { Q_D(MDialog); if (window) { MSceneWindow::appear(window, policy); } else { d->appear(policy); } } void MDialog::accept() { done(Accepted); } void MDialog::reject() { done(Rejected); } void MDialog::done(int result) { setResult(result); emit finished(result); if (result == MDialog::Accepted) emit accepted(); else if (result == MDialog::Rejected) emit rejected(); if (sceneManager()) sceneManager()->disappearSceneWindow(this); } int MDialog::exec(MWindow *window) { Q_D(MDialog); MSceneManager *targetSceneManager = 0; int result; d->clickedButton = 0; d->policy = MSceneWindow::KeepWhenDone; if (window) { targetSceneManager = window->sceneManager(); } else { if (isSystemModal()) { d->prepareStandAloneAppearance(KeepWhenDone); targetSceneManager = d->standAloneWindow->sceneManager(); } else { window = MApplication::activeWindow(); if (window) { targetSceneManager = window->sceneManager(); } else { mWarning("MDialog") << "Cannot appear. No MWindow currently active."; } } } if (targetSceneManager) { result = targetSceneManager->execDialog(this); } else { result = Rejected; } return result; } MButtonModel *MDialog::clickedButton() const { Q_D(const MDialog); return d->clickedButton; } int MDialog::result() const { return model()->resultCode(); } void MDialog::setResult(int result) { model()->setResultCode(result); } bool MDialog::isButtonBoxVisible() const { return model()->buttonBoxVisible(); } void MDialog::setButtonBoxVisible(bool visible) { model()->setButtonBoxVisible(visible); } bool MDialog::isCloseButtonVisible() const { return model()->closeButtonVisible(); } void MDialog::setCloseButtonVisible(bool visible) { model()->setCloseButtonVisible(visible); } bool MDialog::isProgressIndicatorVisible() const { return model()->progressIndicatorVisible(); } void MDialog::setProgressIndicatorVisible(bool visible) { model()->setProgressIndicatorVisible(visible); } bool MDialog::isTitleBarVisible() const { return model()->titleBarVisible(); } void MDialog::setTitleBarVisible(bool visible) { model()->setTitleBarVisible(visible); } bool MDialog::isSystemModal() const { return model()->systemModal(); } void MDialog::setSystemModal(bool systemModal) { model()->setSystemModal(systemModal); } void MDialog::setLayout(QGraphicsLayout *layout) { Q_D(MDialog); mWarning("MDialog:") << "Please don't change the layout directly."; d->dumbMode = true; QGraphicsWidget::setLayout(layout); } QGraphicsLayout *MDialog::layout() { Q_D(MDialog); mWarning("MDialog:") << "Please don't change the layout directly."; d->dumbMode = true; return QGraphicsWidget::layout(); } void MDialog::updateData(const QList<const char *>& modifications) { MSceneWindow::updateData(modifications); Q_D(MDialog); if (modifications.contains(MDialogModel::Buttons)) { d->updateButtonClickedMappings(); d->clickedButton = 0; } } void MDialog::setupModel() { MSceneWindow::setupModel(); Q_D(MDialog); d->updateButtonClickedMappings(); d->clickedButton = 0; } void MDialog::dismissEvent(MDismissEvent *event) { setResult(Rejected); emit finished(result()); emit rejected(); event->accept(); } #include "moc_mdialog.cpp" <commit_msg>Fixes: NB#168463 - Close button is not behaving properly after we press any other button on dialog RevBy: Tomas<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mdialog.h" #include "mdialog_p.h" #include <mbuttonmodel.h> #include <MDebug> #include <MDismissEvent> #include <MHomeButtonPanel> #include <MLocale> #include <MScene> #include <MWindow> #ifdef Q_WS_X11 # include <QX11Info> # include <X11/Xlib.h> #endif #include <QSignalMapper> #include <MApplication> #include <MSceneManager> #include "mwidgetcreator.h" M_REGISTER_WIDGET(MDialog) MDialogPrivate::MDialogPrivate() : clickedButton(0), buttonClickedMapper(0), dumbMode(false), standAloneWindow(0), homeButtonPanel(0), suicideAfterDestroyingStandAloneWindow(false) { } MDialogPrivate::~MDialogPrivate() { if (buttonClickedMapper) { delete buttonClickedMapper; buttonClickedMapper = 0; } if (standAloneWindow) { Q_Q(MDialog); standAloneWindow->scene()->removeItem(q); delete standAloneWindow; standAloneWindow = 0; } } void MDialogPrivate::init() { Q_Q(MDialog); clickedButton = 0; q->setFocusPolicy(Qt::ClickFocus); } void MDialogPrivate::appear(MSceneWindow::DeletionPolicy policy) { Q_Q(MDialog); MWindow *window; if (q->isSystemModal()) { if (prepareStandAloneAppearance(policy)) { q->appear(standAloneWindow); } } else { window = MApplication::activeWindow(); if (window) { q->appear(window, policy); } else { mWarning("MDialog") << "Cannot appear. No MWindow currently active."; } } } void MDialogPrivate::addStandardButtons(M::StandardButtons standardButtons) { Q_Q(MDialog); uint buttonFlag = M::FirstButton; while (buttonFlag <= M::LastButton) { if (standardButtons.testFlag((M::StandardButton)buttonFlag)) { q->model()->addButton((M::StandardButton)buttonFlag); } buttonFlag = buttonFlag << 1; } } void MDialogPrivate::_q_buttonClicked(QObject *obj) { Q_Q(MDialog); MButtonModel *buttonModel = 0; buttonModel = qobject_cast<MButtonModel *>(obj); if (buttonModel) { clickedButton = buttonModel; int result = resultFromStandardButtonId(q->model()->standardButton(buttonModel)); q->done(result); } } void MDialogPrivate::updateStandAloneHomeButtonVisibility() { Q_Q(MDialog); if (q->isSystemModal()) { // Remove the home button if it's there. if (homeButtonPanel) { if (homeButtonPanel->scene() != 0) { Q_ASSERT(homeButtonPanel->scene() == standAloneWindow->scene()); standAloneWindow->sceneManager()->disappearSceneWindowNow(homeButtonPanel); } delete homeButtonPanel; homeButtonPanel = 0; } } else { // Put a home button on the system modal window homeButtonPanel = new MHomeButtonPanel(); standAloneWindow->connect(homeButtonPanel, SIGNAL(buttonClicked()), SLOT(showMinimized())); standAloneWindow->sceneManager()->appearSceneWindowNow(homeButtonPanel); } } void MDialogPrivate::_q_onStandAloneDialogDisappeared() { Q_Q(MDialog); Q_ASSERT(standAloneWindow != 0); q->disconnect(SIGNAL(disappeared()), q, SLOT(_q_onStandAloneDialogDisappeared())); standAloneWindow->setScene(0); standAloneWindow->deleteLater(); standAloneWindow = 0; // Remove dialog from scene otherwise scene will delete dialog // on scene's destructor if (q->scene()) { q->scene()->removeItem(q); } if (homeButtonPanel) { if (homeButtonPanel->sceneManager()) homeButtonPanel->sceneManager()->disappearSceneWindowNow(homeButtonPanel); delete homeButtonPanel; homeButtonPanel = 0; } if (suicideAfterDestroyingStandAloneWindow) { q->deleteLater(); } } bool MDialogPrivate::prepareStandAloneAppearance(MSceneWindow::DeletionPolicy policy) { Q_Q(MDialog); bool ok = true; if (standAloneWindow == 0) { standAloneWindow = new MWindow(new MSceneManager); standAloneWindow->setTranslucentBackground(true); #ifdef Q_WS_X11 standAloneWindow->setAttribute(Qt::WA_X11NetWmWindowTypeDialog, true); QWidget *activeWindow = MApplication::activeWindow(); if (activeWindow && (activeWindow->winId() != standAloneWindow->winId())) { XSetTransientForHint(QX11Info::display(), standAloneWindow->winId(), activeWindow->winId()); } #endif q->connect(q, SIGNAL(disappeared()), SLOT(_q_onStandAloneDialogDisappeared())); } // We only have a home button in the stand-alone window if the // the dialog is supposed to be modeless. updateStandAloneHomeButtonVisibility(); // Dialog will handle its own deletion policy instead of scene manager // since in this case the dialog owns the scene manager and not the other // way around suicideAfterDestroyingStandAloneWindow = (policy == MSceneWindow::DestroyWhenDone); standAloneWindow->show(); // Check whether the dialog is already present in some scene manager if (shown) { if (q->sceneManager() != standAloneWindow->sceneManager()) { q->sceneManager()->disappearSceneWindowNow(q); } else { ok = false; } } return ok; } void MDialogPrivate::updateButtonClickedMappings() { Q_Q(MDialog); if (buttonClickedMapper) { delete buttonClickedMapper; buttonClickedMapper = 0; } buttonClickedMapper = new QSignalMapper(); q->connect(buttonClickedMapper, SIGNAL(mapped(QObject *)), SLOT(_q_buttonClicked(QObject *))); MButtonModel *buttonModel; MDialogButtonsList buttonModelsList = q->model()->buttons(); const int buttonModelsSize = buttonModelsList.size(); for (int i = 0; i < buttonModelsSize; ++i) { buttonModel = buttonModelsList[i]; buttonClickedMapper->connect(buttonModel, SIGNAL(clicked()), SLOT(map())); buttonClickedMapper->setMapping(buttonModel, buttonModel); } } int MDialogPrivate::resultFromStandardButtonId(int buttonId) { switch (buttonId) { case M::NoStandardButton: case M::OkButton: case M::SaveButton: case M::SaveAllButton: case M::OpenButton: case M::YesButton: case M::YesToAllButton: case M::RetryButton: case M::ApplyButton: case M::DoneButton: return MDialog::Accepted; case M::NoButton: case M::NoToAllButton: case M::AbortButton: case M::IgnoreButton: case M::CloseButton: case M::CancelButton: case M::DiscardButton: case M::HelpButton: case M::ResetButton: case M::RestoreDefaultsButton: return MDialog::Rejected; default: //Non-standard buttons should be handled by NoStandardButton case. //This should not happen. return MDialog::Accepted; }; } MDialog::MDialog() : MSceneWindow(new MDialogPrivate(), new MDialogModel(), MSceneWindow::Dialog, QString()) { Q_D(MDialog); d->init(); model()->setResultCode(MDialog::Rejected); } MDialog::MDialog(const QString &title, M::StandardButtons buttons) : MSceneWindow(new MDialogPrivate(), new MDialogModel(), MSceneWindow::Dialog, QString()) { Q_D(MDialog); d->init(); model()->setResultCode(MDialog::Rejected); setTitle(title); d->addStandardButtons(buttons); } MDialog::MDialog(MDialogPrivate *dd, MDialogModel *model, MSceneWindow::WindowType windowType) : MSceneWindow(dd, model, windowType, QString()) { Q_D(MDialog); d->init(); model->setResultCode(MDialog::Rejected); } MDialog::MDialog(MDialogPrivate *dd, M::StandardButtons buttons, MDialogModel *model, MSceneWindow::WindowType windowType) : MSceneWindow(dd, model, windowType, QString()) { Q_D(MDialog); d->init(); model->setResultCode(MDialog::Rejected); d->addStandardButtons(buttons); } MDialog::~MDialog() { } QString MDialog::title() const { return model()->title(); } void MDialog::setTitle(const QString &title) { model()->setTitle(title); } QGraphicsWidget *MDialog::centralWidget() { return model()->centralWidget(); } void MDialog::setCentralWidget(QGraphicsWidget *centralWidget) { if (model()->centralWidget()) delete model()->centralWidget(); model()->setCentralWidget(centralWidget); } void MDialog::addButton(MButtonModel *buttonModel) { model()->addButton(buttonModel); } MButtonModel *MDialog::addButton(const QString &text) { MButtonModel *buttonModel = 0; buttonModel = new MButtonModel; buttonModel->setText(text); model()->addButton(buttonModel); return buttonModel; } MButtonModel *MDialog::addButton(M::StandardButton buttonType) { return model()->addButton(buttonType); } void MDialog::removeButton(MButtonModel *buttonModel) { model()->removeButton(buttonModel); } MButtonModel *MDialog::button(M::StandardButton which) { return model()->button(which); } M::StandardButton MDialog::standardButton(MButtonModel *buttonModel) const { return model()->standardButton(buttonModel); } void MDialog::appear(MSceneWindow::DeletionPolicy policy) { Q_D(MDialog); d->appear(policy); } void MDialog::appear(MWindow *window, MSceneWindow::DeletionPolicy policy) { Q_D(MDialog); if (window) { MSceneWindow::appear(window, policy); } else { d->appear(policy); } } void MDialog::accept() { done(Accepted); } void MDialog::reject() { Q_D(MDialog); QObject *sender= QObject::sender(); if (sender != 0 && sender->objectName() == "MDialogCloseButton") { d->clickedButton = 0; } done(Rejected); } void MDialog::done(int result) { setResult(result); emit finished(result); if (result == MDialog::Accepted) emit accepted(); else if (result == MDialog::Rejected) emit rejected(); if (sceneManager()) sceneManager()->disappearSceneWindow(this); } int MDialog::exec(MWindow *window) { Q_D(MDialog); MSceneManager *targetSceneManager = 0; int result; d->clickedButton = 0; d->policy = MSceneWindow::KeepWhenDone; if (window) { targetSceneManager = window->sceneManager(); } else { if (isSystemModal()) { d->prepareStandAloneAppearance(KeepWhenDone); targetSceneManager = d->standAloneWindow->sceneManager(); } else { window = MApplication::activeWindow(); if (window) { targetSceneManager = window->sceneManager(); } else { mWarning("MDialog") << "Cannot appear. No MWindow currently active."; } } } if (targetSceneManager) { result = targetSceneManager->execDialog(this); } else { result = Rejected; } return result; } MButtonModel *MDialog::clickedButton() const { Q_D(const MDialog); return d->clickedButton; } int MDialog::result() const { return model()->resultCode(); } void MDialog::setResult(int result) { model()->setResultCode(result); } bool MDialog::isButtonBoxVisible() const { return model()->buttonBoxVisible(); } void MDialog::setButtonBoxVisible(bool visible) { model()->setButtonBoxVisible(visible); } bool MDialog::isCloseButtonVisible() const { return model()->closeButtonVisible(); } void MDialog::setCloseButtonVisible(bool visible) { model()->setCloseButtonVisible(visible); } bool MDialog::isProgressIndicatorVisible() const { return model()->progressIndicatorVisible(); } void MDialog::setProgressIndicatorVisible(bool visible) { model()->setProgressIndicatorVisible(visible); } bool MDialog::isTitleBarVisible() const { return model()->titleBarVisible(); } void MDialog::setTitleBarVisible(bool visible) { model()->setTitleBarVisible(visible); } bool MDialog::isSystemModal() const { return model()->systemModal(); } void MDialog::setSystemModal(bool systemModal) { model()->setSystemModal(systemModal); } void MDialog::setLayout(QGraphicsLayout *layout) { Q_D(MDialog); mWarning("MDialog:") << "Please don't change the layout directly."; d->dumbMode = true; QGraphicsWidget::setLayout(layout); } QGraphicsLayout *MDialog::layout() { Q_D(MDialog); mWarning("MDialog:") << "Please don't change the layout directly."; d->dumbMode = true; return QGraphicsWidget::layout(); } void MDialog::updateData(const QList<const char *>& modifications) { MSceneWindow::updateData(modifications); Q_D(MDialog); if (modifications.contains(MDialogModel::Buttons)) { d->updateButtonClickedMappings(); d->clickedButton = 0; } } void MDialog::setupModel() { MSceneWindow::setupModel(); Q_D(MDialog); d->updateButtonClickedMappings(); d->clickedButton = 0; } void MDialog::dismissEvent(MDismissEvent *event) { setResult(Rejected); emit finished(result()); emit rejected(); event->accept(); } #include "moc_mdialog.cpp" <|endoftext|>
<commit_before>// Copyright (c) 2016-2018 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <bench/bench.h> #include <bloom.h> static void RollingBloom(benchmark::State& state) { CRollingBloomFilter filter(120000, 0.000001); std::vector<unsigned char> data(32); uint32_t count = 0; while (state.KeepRunning()) { count++; data[0] = count; data[1] = count >> 8; data[2] = count >> 16; data[3] = count >> 24; filter.insert(data); data[0] = count >> 24; data[1] = count >> 16; data[2] = count >> 8; data[3] = count; filter.contains(data); } } BENCHMARK(RollingBloom, 1500 * 1000); <commit_msg>Bitcoin: d2dbc7da26e1ca40200521c05a0b1ca75578acd2 (bench: Add benchmark for CRollingBloomFilter::reset).<commit_after>// Copyright (c) 2016-2018 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <bench/bench.h> #include <bloom.h> static void RollingBloom(benchmark::State& state) { CRollingBloomFilter filter(120000, 0.000001); std::vector<unsigned char> data(32); uint32_t count = 0; while (state.KeepRunning()) { count++; data[0] = count; data[1] = count >> 8; data[2] = count >> 16; data[3] = count >> 24; filter.insert(data); data[0] = count >> 24; data[1] = count >> 16; data[2] = count >> 8; data[3] = count; filter.contains(data); } } static void RollingBloomReset(benchmark::State& state) { CRollingBloomFilter filter(120000, 0.000001); while (state.KeepRunning()) { filter.reset(); } } BENCHMARK(RollingBloom, 1500 * 1000); BENCHMARK(RollingBloomReset, 20000); <|endoftext|>
<commit_before>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "regex.h" /* for std::regex, std::regex_match() */ #include "time.h" using namespace xsd; //////////////////////////////////////////////////////////////////////////////// constexpr char time::name[]; constexpr char time::pattern[]; static const std::regex time_regex{time::pattern}; bool time::match(const std::string& literal) noexcept { return std::regex_match(literal, time_regex); } bool time::validate() const noexcept { return time::match(_literal); } bool time::canonicalize() noexcept { return false; // TODO } <commit_msg>Implemented the xsd::time#canonicalize() method.<commit_after>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "const.h" /* for XSD_TIME_CAPTURES */ #include "regex.h" /* for std::regex, std::regex_match() */ #include "time.h" #include <algorithm> /* for std::copy(), std::copy_n() */ #include <cassert> /* for assert() */ #include <cstdio> /* for std::sprintf() */ #include <cstdlib> /* for std::atoi() */ using namespace std::regex_constants; using namespace xsd; //////////////////////////////////////////////////////////////////////////////// constexpr char time::name[]; constexpr char time::pattern[]; static const std::regex time_regex{time::pattern}; bool time::match(const std::string& literal) noexcept { return std::regex_match(literal, time_regex, match_not_null); } bool time::validate() const noexcept { return time::match(_literal); } bool time::canonicalize() noexcept { static auto match_to_int = [](const std::csub_match& match) -> unsigned int { const auto length = match.length(); char buffer[length + 1]; std::copy_n(match.first, length, buffer); buffer[length] = '\0'; return std::atoi(buffer); }; std::cmatch matches; if (!std::regex_match(c_str(), matches, time_regex, match_not_null)) { throw std::invalid_argument{c_str()}; /* invalid literal */ } assert(matches.size() == XSD_TIME_CAPTURES); char buffer[256] = ""; char* output = buffer; /* TZ */ int tz_hour = 0, tz_min = 0; if (matches[5].length()) { const std::string match{matches[5].first, matches[5].second}; const int sign = (match[0] == '-') ? -1 : 1; if (match.compare("Z") != 0 || match.compare("-00:00") != 0 || match.compare("+00:00") != 0) { tz_hour = sign * std::atoi(match.c_str() + 1); tz_min = sign * std::atoi(match.c_str() + 4); } } /* "hh" */ { const unsigned int hour = match_to_int(matches[1]); if (hour >= 24) { throw std::invalid_argument{c_str()}; /* invalid literal */ } output += std::sprintf(output, "%02u", (hour - tz_hour) % 24); } /* "mm" */ { const unsigned int min = match_to_int(matches[2]); if (min >= 60) { throw std::invalid_argument{c_str()}; /* invalid literal */ } output += std::sprintf(output, ":%02u", (min - tz_min) % 60); } /* "ss" */ { const unsigned int sec = match_to_int(matches[3]); if (sec >= 60) { throw std::invalid_argument{c_str()}; /* invalid literal */ } output += std::sprintf(output, ":%02u", sec); } /* ".sss" */ if (matches[4].length()) { const std::string match{matches[4].first, matches[4].second}; // TODO: trim off any trailing zeroes. const unsigned int msec = std::atoi(match.c_str() + 1); output += std::sprintf(output, ".%u", msec); } /* TZ */ if (matches[5].length()) { *output++ = 'Z'; } *output++ = '\0'; if (_literal.compare(buffer) != 0) { _literal.assign(buffer); return true; /* now in canonical form */ } return false; /* already in canonical form */ } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2015 * Versioning. */ #include <Version.h> #include <string> #include <BuildInfo.h> #include <libdevcore/Common.h> using namespace dev; using namespace dev::solidity; using namespace std; char const* dev::solidity::VersionNumber = "0.1.1"; extern string const dev::solidity::VersionString = string(dev::solidity::VersionNumber) + "-" + string(DEV_QUOTED(ETH_COMMIT_HASH)).substr(0, 8) + (ETH_CLEAN_REPO ? "" : "*") + "/" DEV_QUOTED(ETH_BUILD_TYPE) "-" DEV_QUOTED(ETH_BUILD_PLATFORM); <commit_msg>include Version.h under libsolidity<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2015 * Versioning. */ #include <libsolidity/Version.h> #include <string> #include <BuildInfo.h> #include <libdevcore/Common.h> using namespace dev; using namespace dev::solidity; using namespace std; char const* dev::solidity::VersionNumber = "0.1.1"; extern string const dev::solidity::VersionString = string(dev::solidity::VersionNumber) + "-" + string(DEV_QUOTED(ETH_COMMIT_HASH)).substr(0, 8) + (ETH_CLEAN_REPO ? "" : "*") + "/" DEV_QUOTED(ETH_BUILD_TYPE) "-" DEV_QUOTED(ETH_BUILD_PLATFORM); <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "DisplayMenu.h" #include "TextureManager.h" /* system implementation headers */ #include <string> #include <vector> #include <math.h> /* common implementation headers */ #include "BzfDisplay.h" #include "SceneRenderer.h" #include "FontManager.h" #include "OpenGLTexture.h" #include "StateDatabase.h" #include "BZDBCache.h" /* local implementation headers */ #include "MainMenu.h" #include "HUDDialogStack.h" #include "HUDuiControl.h" #include "HUDuiList.h" #include "HUDuiLabel.h" #include "MainWindow.h" /* FIXME - from playing.h */ BzfDisplay* getDisplay(); MainWindow* getMainWindow(); SceneRenderer* getSceneRenderer(); void setSceneDatabase(); DisplayMenu::DisplayMenu() : formatMenu(NULL) { // add controls std::vector<std::string>* options; std::vector<HUDuiControl*>& list = getControls(); HUDuiList* option; // cache font face id int fontFace = MainMenu::getFontFace(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Display Settings"); list.push_back(label); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Dithering:"); option->setCallback(callback, (void*)"1"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Blending:"); option->setCallback(callback, (void*)"2"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Smoothing:"); option->setCallback(callback, (void*)"3"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Lighting:"); option->setCallback(callback, (void*)"4"); options = &option->getList(); options->push_back(std::string("None")); options->push_back(std::string("Fast")); options->push_back(std::string("Best")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Texturing:"); option->setCallback(callback, (void*)"5"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("Nearest")); options->push_back(std::string("Linear")); options->push_back(std::string("Nearest Mipmap Nearest")); options->push_back(std::string("Linear Mipmap Nearest")); options->push_back(std::string("Nearest Mipmap Linear")); options->push_back(std::string("Linear Mipmap Linear")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Quality:"); option->setCallback(callback, (void*)"6"); options = &option->getList(); options->push_back(std::string("Low")); options->push_back(std::string("Medium")); options->push_back(std::string("High")); options->push_back(std::string("Experimental")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Shadows:"); option->setCallback(callback, (void*)"7"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Buffer:"); option->setCallback(callback, (void*)"8"); options = &option->getList(); GLint value; glGetIntegerv(GL_DEPTH_BITS, &value); if (value == 0) { options->push_back(std::string("Not available")); } else { options->push_back(std::string("Off (SLOWER)")); options->push_back(std::string("On")); } option->update(); list.push_back(option); #if defined(DEBUG_RENDERING) option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Hidden Line:"); option->setCallback(callback, (void*)"a"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Wireframe:"); option->setCallback(callback, (void*)"b"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Complexity:"); option->setCallback(callback, (void*)"c"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Culling Tree:"); option->setCallback(callback, (void*)"d"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Collision Tree:"); option->setCallback(callback, (void*)"e"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); #endif BzfWindow* window = getMainWindow()->getWindow(); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Brightness:"); option->setCallback(callback, (void*)"g"); if (window->hasGammaControl()) { option->createSlider(15); } else { options = &option->getList(); options->push_back(std::string("Unavailable")); } option->update(); list.push_back(option); BzfDisplay* display = getDisplay(); int numFormats = display->getNumResolutions(); if (numFormats < 2) { videoFormat = NULL; } else { videoFormat = label = new HUDuiLabel; label->setFontFace(fontFace); label->setLabel("Change Video Format"); list.push_back(label); } initNavigation(list, 1,list.size()-1); } DisplayMenu::~DisplayMenu() { delete formatMenu; } void DisplayMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == videoFormat) { if (!formatMenu) formatMenu = new FormatMenu; HUDDialogStack::get()->push(formatMenu); } } void DisplayMenu::resize(int width, int height) { HUDDialog::resize(width, height); int i; // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 45.0f; FontManager &fm = FontManager::instance(); int fontFace = MainMenu::getFontFace(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " "); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width); y -= 0.6f * titleHeight; const float h = fm.getStrHeight(fontFace, fontSize, " "); const int count = list.size(); for (i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; } i = 1; // load current settings SceneRenderer* renderer = getSceneRenderer(); if (renderer) { TextureManager& tm = TextureManager::instance(); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("blend")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth")); if (BZDBCache::lighting) { if (BZDB.isTrue("tesselation")) { ((HUDuiList*)list[i++])->setIndex(2); } else { ((HUDuiList*)list[i++])->setIndex(1); } } else { ((HUDuiList*)list[i++])->setIndex(0); } ((HUDuiList*)list[i++])->setIndex(tm.getMaxFilter()); ((HUDuiList*)list[i++])->setIndex(renderer->useQuality()); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows")); ((HUDuiList*)list[i++])->setIndex(BZDBCache::zbuffer); #if defined(DEBUG_RENDERING) ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(BZDBCache::showCullingGrid ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(BZDBCache::showCollisionGrid ? 1 : 0); #endif } // brightness BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma())); i++; } int DisplayMenu::gammaToIndex(float gamma) { return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0))); } float DisplayMenu::indexToGamma(int index) { // map index 5 to gamma 1.0 and index 0 to gamma 0.5 return powf(2.0f, (float)index / 5.0f - 1.0f); } void DisplayMenu::callback(HUDuiControl* w, void* data) { HUDuiList* list = (HUDuiList*)w; SceneRenderer* sceneRenderer = getSceneRenderer(); switch (((const char*)data)[0]) { case '1': BZDB.set("dither", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '2': BZDB.set("blend", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '3': BZDB.set("smooth", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '4': { bool oldLighting = BZDBCache::lighting; BZDB.set("lighting", list->getIndex() == 0 ? "0" : "1"); BZDB.set("tesselation", list->getIndex() == 2 ? "1" : "0"); if (oldLighting != BZDBCache::lighting) { BZDB.set("texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("texturereplace", false); sceneRenderer->notifyStyleChange(); } break; } case '5': { TextureManager& tm = TextureManager::instance(); tm.setMaxFilter((OpenGLTexture::Filter)list->getIndex()); BZDB.set("texture", tm.getMaxFilterName()); sceneRenderer->notifyStyleChange(); break; } case '6': sceneRenderer->setQuality(list->getIndex()); if (list->getIndex() > 3) { BZDB.set("zbuffer","1"); setSceneDatabase(); } BZDB.set("texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("texturereplace", false); sceneRenderer->notifyStyleChange(); break; case '7': BZDB.set("shadows", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '8': // FIXME - test for whether the z buffer will work BZDB.set("zbuffer", list->getIndex() ? "1" : "0"); setSceneDatabase(); sceneRenderer->notifyStyleChange(); break; #if defined(DEBUG_RENDERING) case 'a': sceneRenderer->setHiddenLine(list->getIndex() != 0); break; case 'b': sceneRenderer->setWireframe(list->getIndex() != 0); break; case 'c': sceneRenderer->setDepthComplexity(list->getIndex() != 0); break; #endif case 'd': BZDB.setBool("showCullingGrid", list->getIndex() != 0); break; case 'e': BZDB.setBool("showCollisionGrid", list->getIndex() != 0); break; case 'g': BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) window->setGamma(indexToGamma(list->getIndex())); break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>funky gfx with DEBUG_RENDERING or -debug<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "DisplayMenu.h" #include "TextureManager.h" /* system implementation headers */ #include <string> #include <vector> #include <math.h> /* common implementation headers */ #include "BzfDisplay.h" #include "SceneRenderer.h" #include "FontManager.h" #include "OpenGLTexture.h" #include "StateDatabase.h" #include "BZDBCache.h" /* local implementation headers */ #include "MainMenu.h" #include "HUDDialogStack.h" #include "HUDuiControl.h" #include "HUDuiList.h" #include "HUDuiLabel.h" #include "MainWindow.h" /* FIXME - from playing.h */ BzfDisplay* getDisplay(); MainWindow* getMainWindow(); SceneRenderer* getSceneRenderer(); void setSceneDatabase(); DisplayMenu::DisplayMenu() : formatMenu(NULL) { // add controls std::vector<std::string>* options; std::vector<HUDuiControl*>& list = getControls(); HUDuiList* option; // cache font face id int fontFace = MainMenu::getFontFace(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Display Settings"); list.push_back(label); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Dithering:"); option->setCallback(callback, (void*)"1"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Blending:"); option->setCallback(callback, (void*)"2"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Smoothing:"); option->setCallback(callback, (void*)"3"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Lighting:"); option->setCallback(callback, (void*)"4"); options = &option->getList(); options->push_back(std::string("None")); options->push_back(std::string("Fast")); options->push_back(std::string("Best")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Texturing:"); option->setCallback(callback, (void*)"5"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("Nearest")); options->push_back(std::string("Linear")); options->push_back(std::string("Nearest Mipmap Nearest")); options->push_back(std::string("Linear Mipmap Nearest")); options->push_back(std::string("Nearest Mipmap Linear")); options->push_back(std::string("Linear Mipmap Linear")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Quality:"); option->setCallback(callback, (void*)"6"); options = &option->getList(); options->push_back(std::string("Low")); options->push_back(std::string("Medium")); options->push_back(std::string("High")); options->push_back(std::string("Experimental")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Shadows:"); option->setCallback(callback, (void*)"7"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Buffer:"); option->setCallback(callback, (void*)"8"); options = &option->getList(); GLint value; glGetIntegerv(GL_DEPTH_BITS, &value); if (value == 0) { options->push_back(std::string("Not available")); } else { options->push_back(std::string("Off (SLOWER)")); options->push_back(std::string("On")); } option->update(); list.push_back(option); #if !defined(DEBUG_RENDERING) if (debugLevel > 0) { #endif option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Hidden Line:"); option->setCallback(callback, (void*)"a"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Wireframe:"); option->setCallback(callback, (void*)"b"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Complexity:"); option->setCallback(callback, (void*)"c"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Culling Tree:"); option->setCallback(callback, (void*)"d"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Collision Tree:"); option->setCallback(callback, (void*)"e"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); #if !defined(DEBUG_RENDERING) } #endif BzfWindow* window = getMainWindow()->getWindow(); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Brightness:"); option->setCallback(callback, (void*)"g"); if (window->hasGammaControl()) { option->createSlider(15); } else { options = &option->getList(); options->push_back(std::string("Unavailable")); } option->update(); list.push_back(option); BzfDisplay* display = getDisplay(); int numFormats = display->getNumResolutions(); if (numFormats < 2) { videoFormat = NULL; } else { videoFormat = label = new HUDuiLabel; label->setFontFace(fontFace); label->setLabel("Change Video Format"); list.push_back(label); } initNavigation(list, 1,list.size()-1); } DisplayMenu::~DisplayMenu() { delete formatMenu; } void DisplayMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == videoFormat) { if (!formatMenu) formatMenu = new FormatMenu; HUDDialogStack::get()->push(formatMenu); } } void DisplayMenu::resize(int width, int height) { HUDDialog::resize(width, height); int i; // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 45.0f; FontManager &fm = FontManager::instance(); int fontFace = MainMenu::getFontFace(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " "); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width); y -= 0.6f * titleHeight; const float h = fm.getStrHeight(fontFace, fontSize, " "); const int count = list.size(); for (i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; } i = 1; // load current settings SceneRenderer* renderer = getSceneRenderer(); if (renderer) { TextureManager& tm = TextureManager::instance(); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("blend")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth")); if (BZDBCache::lighting) { if (BZDB.isTrue("tesselation")) { ((HUDuiList*)list[i++])->setIndex(2); } else { ((HUDuiList*)list[i++])->setIndex(1); } } else { ((HUDuiList*)list[i++])->setIndex(0); } ((HUDuiList*)list[i++])->setIndex(tm.getMaxFilter()); ((HUDuiList*)list[i++])->setIndex(renderer->useQuality()); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows")); ((HUDuiList*)list[i++])->setIndex(BZDBCache::zbuffer); #if !defined(DEBUG_RENDERING) if (debugLevel > 0) { #endif ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(BZDBCache::showCullingGrid ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(BZDBCache::showCollisionGrid ? 1 : 0); #if !defined(DEBUG_RENDERING) } #endif } // brightness BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma())); i++; } int DisplayMenu::gammaToIndex(float gamma) { return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0))); } float DisplayMenu::indexToGamma(int index) { // map index 5 to gamma 1.0 and index 0 to gamma 0.5 return powf(2.0f, (float)index / 5.0f - 1.0f); } void DisplayMenu::callback(HUDuiControl* w, void* data) { HUDuiList* list = (HUDuiList*)w; SceneRenderer* sceneRenderer = getSceneRenderer(); switch (((const char*)data)[0]) { case '1': BZDB.set("dither", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '2': BZDB.set("blend", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '3': BZDB.set("smooth", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '4': { bool oldLighting = BZDBCache::lighting; BZDB.set("lighting", list->getIndex() == 0 ? "0" : "1"); BZDB.set("tesselation", list->getIndex() == 2 ? "1" : "0"); if (oldLighting != BZDBCache::lighting) { BZDB.set("texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("texturereplace", false); sceneRenderer->notifyStyleChange(); } break; } case '5': { TextureManager& tm = TextureManager::instance(); tm.setMaxFilter((OpenGLTexture::Filter)list->getIndex()); BZDB.set("texture", tm.getMaxFilterName()); sceneRenderer->notifyStyleChange(); break; } case '6': sceneRenderer->setQuality(list->getIndex()); if (list->getIndex() > 3) { BZDB.set("zbuffer","1"); setSceneDatabase(); } BZDB.set("texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("texturereplace", false); sceneRenderer->notifyStyleChange(); break; case '7': BZDB.set("shadows", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '8': // FIXME - test for whether the z buffer will work BZDB.set("zbuffer", list->getIndex() ? "1" : "0"); setSceneDatabase(); sceneRenderer->notifyStyleChange(); break; case 'a': sceneRenderer->setHiddenLine(list->getIndex() != 0); break; case 'b': sceneRenderer->setWireframe(list->getIndex() != 0); break; case 'c': sceneRenderer->setDepthComplexity(list->getIndex() != 0); break; case 'd': BZDB.setBool("showCullingGrid", list->getIndex() != 0); break; case 'e': BZDB.setBool("showCollisionGrid", list->getIndex() != 0); break; case 'g': BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) window->setGamma(indexToGamma(list->getIndex())); break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* Copyright 2016 Nervana Systems 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. */ #include "specgram.hpp" using cv::Mat; using cv::Range; using cv::Size; using namespace std; using std::stringstream; using std::vector; Specgram::Specgram(shared_ptr<const nervana::audio::config> params, int id) : _feature( params->_feature), _clipDuration(params->_clipDuration), _windowSize( params->_windowSize), _stride( params->_stride), _width( params->_width), _numFreqs( params->_windowSize / 2 + 1), _height( params->_height), _samplingFreq(params->_samplingFreq), _numFilts( params->_numFilts), _numCepstra( params->_numCepstra), _window( 0), _rng( id) { assert(_stride != 0); if (powerOfTwo(_windowSize) == false) { throw std::runtime_error("Window size must be a power of 2"); } _maxSignalSize = params->_clipDuration * params->_samplingFreq / 1000; _bufSize = _width * _windowSize * MAX_SAMPLE_SIZE; _buf = new char[_bufSize]; if (params->_window != 0) { _window = new Mat(1, _windowSize, CV_32FC1); createWindow(params->_window); } assert(params->_randomScalePercent >= 0); assert(params->_randomScalePercent < 100); _scaleBy = params->_randomScalePercent / 100.0; _scaleMin = 1.0 - _scaleBy; _scaleMax = 1.0 + _scaleBy; transpose(getFilterbank(_numFilts, _windowSize, _samplingFreq), _fbank); assert(params->_width == (((params->_clipDuration * params->_samplingFreq / 1000) - params->_windowSize) / params->_stride) + 1); } Specgram::~Specgram() { delete _window; delete[] _buf; } int Specgram::generate(shared_ptr<RawMedia> raw, char* buf, int bufSize) { // TODO: get rid of this assumption cout << raw->bytesPerSample() << endl; assert(raw->bytesPerSample() == 2); assert(_width * _height == bufSize); int rows = stridedSignal(raw); assert(rows <= _width); Mat signal(rows, _windowSize, CV_16SC1, (short*) _buf); Mat input; signal.convertTo(input, CV_32FC1); applyWindow(input); Mat planes[] = {input, Mat::zeros(input.size(), CV_32FC1)}; Mat compx; cv::merge(planes, 2, compx); cv::dft(compx, compx, cv::DFT_ROWS); compx = compx(Range::all(), Range(0, _numFreqs)); cv::split(compx, planes); cv::magnitude(planes[0], planes[1], planes[0]); Mat mag; if (_feature == SPECGRAM) { mag = planes[0]; } else { extractFeatures(planes[0], mag); } Mat feats; // Rotate by 90 degrees. cv::transpose(mag, feats); cv::flip(feats, feats, 0); cv::normalize(feats, feats, 0, 255, CV_MINMAX, CV_8UC1); Mat result(feats.rows, _width, CV_8UC1, buf); feats.copyTo(result(Range(0, feats.rows), Range(0, feats.cols))); // Pad the rest with zeros. result(Range::all(), Range(feats.cols, result.cols)) = cv::Scalar::all(0); randomize(result); // Return the percentage of valid columns. return feats.cols * 100 / result.cols; } void Specgram::randomize(Mat& img) { if (_scaleBy > 0) { float fx = _rng.uniform(_scaleMin, _scaleMax); resize(img, fx); } } void Specgram::resize(Mat& img, float fx) { Mat dst; int inter = (fx > 1.0) ? CV_INTER_CUBIC : CV_INTER_AREA; cv::resize(img, dst, Size(), fx, 1.0, inter); assert(img.rows == dst.rows); if (img.cols > dst.cols) { dst.copyTo(img(Range::all(), Range(0, dst.cols))); img(Range::all(), Range(dst.cols, img.cols)) = cv::Scalar::all(0); } else { dst(Range::all(), Range(0, img.cols)).copyTo(img); } } bool Specgram::powerOfTwo(int num) { while (((num % 2) == 0) && (num > 1)) { num /= 2; } return (num == 1); } void Specgram::none(int) { } void Specgram::hann(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.5 - 0.5 * cos((2.0 * PI * i) / steps); } } void Specgram::blackman(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.42 - 0.5 * cos((2.0 * PI * i) / steps) + 0.08 * cos(4.0 * PI * i / steps); } } void Specgram::hamming(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.54 - 0.46 * cos((2.0 * PI * i) / steps); } } void Specgram::bartlett(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 1.0 - 2.0 * fabs(i - steps / 2.0) / steps; } } void Specgram::createWindow(int windowType) { typedef void(Specgram::*winFunc)(int); winFunc funcs[] = {&Specgram::none, &Specgram::hann, &Specgram::blackman, &Specgram::hamming, &Specgram::bartlett}; assert(windowType >= 0); if (windowType >= (int) (sizeof(funcs) / sizeof(funcs[0]))) { throw std::runtime_error("Unsupported window function"); } int steps = _windowSize - 1; assert(steps > 0); (this->*(funcs[windowType]))(steps); } void Specgram::applyWindow(Mat& signal) { if (_window == 0) { return; } for (int i = 0; i < signal.rows; i++) { signal.row(i) = signal.row(i).mul((*_window)); } } int Specgram::stridedSignal(shared_ptr<RawMedia> raw) { // read from raw in strided windows of length `_windowSize` // with at every `_stride` samples. // truncate data in raw if larger than _maxSignalSize int numSamples = raw->numSamples(); if (numSamples > _maxSignalSize) { numSamples = _maxSignalSize; } // assert that there is more than 1 window of data in raw assert(numSamples >= _windowSize); // count is the number of windows to capture int count = ((numSamples - _windowSize) / _stride) + 1; // ensure the numver of windows will fit in output buffer of // width `_width` assert(count <= _width); char* src = raw->getBuf(0); char* dst = _buf; int windowSizeInBytes = _windowSize * raw->bytesPerSample(); int strideInBytes = _stride * raw->bytesPerSample(); assert(count * strideInBytes <= numSamples * raw->bytesPerSample()); assert(count * windowSizeInBytes <= _bufSize); for (int i = 0; i < count; i++) { memcpy(dst, src, windowSizeInBytes); dst += windowSizeInBytes; src += strideInBytes; } return count; } double Specgram::hzToMel(double freqInHz) { return 2595 * std::log10(1 + freqInHz/700.0); } double Specgram::melToHz(double freqInMels) { return 700 * (std::pow(10, freqInMels/2595.0)-1); } vector<double> Specgram::linspace(double a, double b, int n) { vector<double> interval; double delta = (b-a)/(n-1); while (a <= b) { interval.push_back(a); a += delta; } interval.push_back(a); return interval; } Mat Specgram::getFilterbank(int filts, int ffts, double samplingRate) { double minFreq = 0.0; double maxFreq = samplingRate / 2.0; double minMelFreq = hzToMel(minFreq); double maxMelFreq = hzToMel(maxFreq); vector<double> melInterval = linspace(minMelFreq, maxMelFreq, filts + 2); vector<int> bins; for (int k=0; k<filts+2; ++k) { bins.push_back(std::floor((1+ffts)*melToHz(melInterval[k])/samplingRate)); } Mat fbank = Mat::zeros(filts, 1 + ffts / 2, CV_32F); for (int j=0; j<filts; ++j) { for (int i=bins[j]; i<bins[j+1]; ++i) { fbank.at<float>(j, i) = (i - bins[j]) / (1.0*(bins[j + 1] - bins[j])); } for (int i=bins[j+1]; i<bins[j+2]; ++i) { fbank.at<float>(j, i) = (bins[j+2]-i) / (1.0*(bins[j + 2] - bins[j+1])); } } return fbank; } void Specgram::extractFeatures(Mat& spectrogram, Mat& features) { Mat powspec = spectrogram.mul(spectrogram); powspec *= 1.0 / _windowSize; Mat cepsgram = powspec*_fbank; log(cepsgram, cepsgram); if (_feature == MFSC) { features = cepsgram; return; } int pad_cols = cepsgram.cols; int pad_rows = cepsgram.rows; if (cepsgram.cols % 2 != 0) { pad_cols = 1 + cepsgram.cols; } if (cepsgram.rows % 2 != 0) { pad_rows = 1 + cepsgram.rows; } Mat padcepsgram = Mat::zeros(pad_rows, pad_cols, CV_32F); cepsgram.copyTo(padcepsgram(Range(0, cepsgram.rows), Range(0, cepsgram.cols))); dct(padcepsgram, padcepsgram, cv::DFT_ROWS); cepsgram = padcepsgram(Range(0, cepsgram.rows), Range(0, cepsgram.cols)); features = cepsgram(Range::all(), Range(0, _numCepstra)); } <commit_msg>rename rows -> numWindows<commit_after>/* Copyright 2016 Nervana Systems 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. */ #include "specgram.hpp" using cv::Mat; using cv::Range; using cv::Size; using namespace std; using std::stringstream; using std::vector; Specgram::Specgram(shared_ptr<const nervana::audio::config> params, int id) : _feature( params->_feature), _clipDuration(params->_clipDuration), _windowSize( params->_windowSize), _stride( params->_stride), _width( params->_width), _numFreqs( params->_windowSize / 2 + 1), _height( params->_height), _samplingFreq(params->_samplingFreq), _numFilts( params->_numFilts), _numCepstra( params->_numCepstra), _window( 0), _rng( id) { assert(_stride != 0); if (powerOfTwo(_windowSize) == false) { throw std::runtime_error("Window size must be a power of 2"); } _maxSignalSize = params->_clipDuration * params->_samplingFreq / 1000; _bufSize = _width * _windowSize * MAX_SAMPLE_SIZE; _buf = new char[_bufSize]; if (params->_window != 0) { _window = new Mat(1, _windowSize, CV_32FC1); createWindow(params->_window); } assert(params->_randomScalePercent >= 0); assert(params->_randomScalePercent < 100); _scaleBy = params->_randomScalePercent / 100.0; _scaleMin = 1.0 - _scaleBy; _scaleMax = 1.0 + _scaleBy; transpose(getFilterbank(_numFilts, _windowSize, _samplingFreq), _fbank); assert(params->_width == (((params->_clipDuration * params->_samplingFreq / 1000) - params->_windowSize) / params->_stride) + 1); } Specgram::~Specgram() { delete _window; delete[] _buf; } int Specgram::generate(shared_ptr<RawMedia> raw, char* buf, int bufSize) { // TODO: get rid of this assumption cout << raw->bytesPerSample() << endl; assert(raw->bytesPerSample() == 2); assert(_width * _height == bufSize); int numWindows = stridedSignal(raw); assert(numWindows <= _width); Mat signal(numWindows, _windowSize, CV_16SC1, (short*) _buf); Mat input; signal.convertTo(input, CV_32FC1); applyWindow(input); Mat planes[] = {input, Mat::zeros(input.size(), CV_32FC1)}; Mat compx; cv::merge(planes, 2, compx); cv::dft(compx, compx, cv::DFT_ROWS); compx = compx(Range::all(), Range(0, _numFreqs)); cv::split(compx, planes); cv::magnitude(planes[0], planes[1], planes[0]); Mat mag; if (_feature == SPECGRAM) { mag = planes[0]; } else { extractFeatures(planes[0], mag); } Mat feats; // Rotate by 90 degrees. cv::transpose(mag, feats); cv::flip(feats, feats, 0); cv::normalize(feats, feats, 0, 255, CV_MINMAX, CV_8UC1); Mat result(feats.rows, _width, CV_8UC1, buf); feats.copyTo(result(Range(0, feats.rows), Range(0, feats.cols))); // Pad the rest with zeros. result(Range::all(), Range(feats.cols, result.cols)) = cv::Scalar::all(0); randomize(result); // Return the percentage of valid columns. return feats.cols * 100 / result.cols; } void Specgram::randomize(Mat& img) { if (_scaleBy > 0) { float fx = _rng.uniform(_scaleMin, _scaleMax); resize(img, fx); } } void Specgram::resize(Mat& img, float fx) { Mat dst; int inter = (fx > 1.0) ? CV_INTER_CUBIC : CV_INTER_AREA; cv::resize(img, dst, Size(), fx, 1.0, inter); assert(img.rows == dst.rows); if (img.cols > dst.cols) { dst.copyTo(img(Range::all(), Range(0, dst.cols))); img(Range::all(), Range(dst.cols, img.cols)) = cv::Scalar::all(0); } else { dst(Range::all(), Range(0, img.cols)).copyTo(img); } } bool Specgram::powerOfTwo(int num) { while (((num % 2) == 0) && (num > 1)) { num /= 2; } return (num == 1); } void Specgram::none(int) { } void Specgram::hann(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.5 - 0.5 * cos((2.0 * PI * i) / steps); } } void Specgram::blackman(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.42 - 0.5 * cos((2.0 * PI * i) / steps) + 0.08 * cos(4.0 * PI * i / steps); } } void Specgram::hamming(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 0.54 - 0.46 * cos((2.0 * PI * i) / steps); } } void Specgram::bartlett(int steps) { for (int i = 0; i <= steps; i++) { _window->at<float>(0, i) = 1.0 - 2.0 * fabs(i - steps / 2.0) / steps; } } void Specgram::createWindow(int windowType) { typedef void(Specgram::*winFunc)(int); winFunc funcs[] = {&Specgram::none, &Specgram::hann, &Specgram::blackman, &Specgram::hamming, &Specgram::bartlett}; assert(windowType >= 0); if (windowType >= (int) (sizeof(funcs) / sizeof(funcs[0]))) { throw std::runtime_error("Unsupported window function"); } int steps = _windowSize - 1; assert(steps > 0); (this->*(funcs[windowType]))(steps); } void Specgram::applyWindow(Mat& signal) { if (_window == 0) { return; } for (int i = 0; i < signal.rows; i++) { signal.row(i) = signal.row(i).mul((*_window)); } } int Specgram::stridedSignal(shared_ptr<RawMedia> raw) { // read from raw in strided windows of length `_windowSize` // with at every `_stride` samples. // truncate data in raw if larger than _maxSignalSize int numSamples = raw->numSamples(); if (numSamples > _maxSignalSize) { numSamples = _maxSignalSize; } // assert that there is more than 1 window of data in raw assert(numSamples >= _windowSize); // count is the number of windows to capture int count = ((numSamples - _windowSize) / _stride) + 1; // ensure the numver of windows will fit in output buffer of // width `_width` assert(count <= _width); char* src = raw->getBuf(0); char* dst = _buf; int windowSizeInBytes = _windowSize * raw->bytesPerSample(); int strideInBytes = _stride * raw->bytesPerSample(); assert(count * strideInBytes <= numSamples * raw->bytesPerSample()); assert(count * windowSizeInBytes <= _bufSize); for (int i = 0; i < count; i++) { memcpy(dst, src, windowSizeInBytes); dst += windowSizeInBytes; src += strideInBytes; } return count; } double Specgram::hzToMel(double freqInHz) { return 2595 * std::log10(1 + freqInHz/700.0); } double Specgram::melToHz(double freqInMels) { return 700 * (std::pow(10, freqInMels/2595.0)-1); } vector<double> Specgram::linspace(double a, double b, int n) { vector<double> interval; double delta = (b-a)/(n-1); while (a <= b) { interval.push_back(a); a += delta; } interval.push_back(a); return interval; } Mat Specgram::getFilterbank(int filts, int ffts, double samplingRate) { double minFreq = 0.0; double maxFreq = samplingRate / 2.0; double minMelFreq = hzToMel(minFreq); double maxMelFreq = hzToMel(maxFreq); vector<double> melInterval = linspace(minMelFreq, maxMelFreq, filts + 2); vector<int> bins; for (int k=0; k<filts+2; ++k) { bins.push_back(std::floor((1+ffts)*melToHz(melInterval[k])/samplingRate)); } Mat fbank = Mat::zeros(filts, 1 + ffts / 2, CV_32F); for (int j=0; j<filts; ++j) { for (int i=bins[j]; i<bins[j+1]; ++i) { fbank.at<float>(j, i) = (i - bins[j]) / (1.0*(bins[j + 1] - bins[j])); } for (int i=bins[j+1]; i<bins[j+2]; ++i) { fbank.at<float>(j, i) = (bins[j+2]-i) / (1.0*(bins[j + 2] - bins[j+1])); } } return fbank; } void Specgram::extractFeatures(Mat& spectrogram, Mat& features) { Mat powspec = spectrogram.mul(spectrogram); powspec *= 1.0 / _windowSize; Mat cepsgram = powspec*_fbank; log(cepsgram, cepsgram); if (_feature == MFSC) { features = cepsgram; return; } int pad_cols = cepsgram.cols; int pad_rows = cepsgram.rows; if (cepsgram.cols % 2 != 0) { pad_cols = 1 + cepsgram.cols; } if (cepsgram.rows % 2 != 0) { pad_rows = 1 + cepsgram.rows; } Mat padcepsgram = Mat::zeros(pad_rows, pad_cols, CV_32F); cepsgram.copyTo(padcepsgram(Range(0, cepsgram.rows), Range(0, cepsgram.cols))); dct(padcepsgram, padcepsgram, cv::DFT_ROWS); cepsgram = padcepsgram(Range(0, cepsgram.rows), Range(0, cepsgram.cols)); features = cepsgram(Range::all(), Range(0, _numCepstra)); } <|endoftext|>
<commit_before>#ifndef MYVECTOR_HPP #define MYVECTOR_HPP 1 #include <algorithm> #include <cstddef> #include <iostream> #include <memory> namespace sandsnip3r { template<typename Type> class MyVectorIterator { private: }; template<typename Type> class MyVector { public: typedef Type value_type; typedef std::allocator<value_type> allocator_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; typedef const Type* const_pointer; //iterator //const_iterator //reverse_iterator //const_reverse_iterator private: std::allocator<value_type> vectorAllocator; std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData; size_t vectorSize{0}; size_t vectorCapacity{0}; void reallocate(size_type newCapacity) { //Allocate memory for the new data if (newCapacity > this->max_size()) { throw std::length_error("MyVector::reallocate() newCapacity (which is "+std::to_string(newCapacity)+") > max_size (which is "+std::to_string(this->max_size())+")"); } // store it in a unique_ptr std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){ vectorAllocator.deallocate(ptr, newCapacity); }); //Move the old data into out new storage chunk const auto &dataBegin = vectorData.get(); std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get()); //Assign the new data to be the current vectorData = std::move(newData); //Update the capacity vectorCapacity = newCapacity; } public: //constructor ~MyVector() { this->clear(); } //operator= //assign allocator_type get_allocator() const { return vectorAllocator; } reference at(size_type pos) { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->at(pos)); } const_reference at(size_type pos) const { if (!(pos < this->size())) { throw std::out_of_range("MyVector::at() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")"); } return vectorData[pos]; } reference operator[](size_type pos) { return vectorData[pos]; } const_reference operator[](size_type pos) const { return vectorData[pos]; } reference front() { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->front()); } const_reference front() const { if (this->empty()) { throw std::out_of_range("MyVector::front(), but it's empty"); } return vectorData[0]; } reference back() { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->back()); } const_reference back() const { if (this->empty()) { throw std::out_of_range("MyVector::back(), but it's empty"); } return vectorData[this->size()-1]; } pointer data() { return vectorData.get(); } const_pointer data() const { return vectorData.get(); } //begin, cbegin //end, cend //rbegin, crbegin //rend, crend bool empty() const { return (this->size() == 0); } size_type size() const { return vectorSize; } //max_size size_type max_size() const { return std::numeric_limits<decltype(vectorSize)>::max(); } void reserve(size_type newCapacity) { if (this->capacity() < newCapacity) { reallocate(newCapacity); } } size_type capacity() const { return vectorCapacity; } void shrink_to_fit() { if (this->size() < this->capacity()) { reallocate(vectorSize); } } void clear() { for (size_type i=0; i<this->size(); ++i) { vectorData[i].~value_type(); --vectorSize; } } //insert //emplace //erase void push_back(const value_type &obj) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{obj}; ++vectorSize; } void push_back(value_type &&obj) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{std::move(obj)}; ++vectorSize; } template<class... Args> void emplace_back(Args&&... args) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...}; ++vectorSize; } void pop_back() { if (!this->empty()) { vectorData[this->size()-1].~value_type(); --vectorSize; } } void resize(size_type count) { if (this->size() < count) { if (this->capacity() < count) { //need to allocate more reallocate(count); } while (vectorSize < count) { //Fill with default constructed elements new(vectorData.get()+vectorSize) value_type{}; ++vectorSize; } } else if (this->size() > count) { for (size_type i=this->size()-1; i>=count; --i) { vectorData[i].~value_type(); --vectorSize; } } } void resize(size_type count, const value_type &value) { if (this->size() < count) { if (this->capacity() < count) { //need to allocate more reallocate(count); } while (vectorSize < count) { //Fill with default constructed elements new(vectorData.get()+vectorSize) value_type{value}; ++vectorSize; } } else if (this->size() > count) { for (size_type i=this->size()-1; i>=count; --i) { vectorData[i].~value_type(); --vectorSize; } } } //swap //operators: // == // != // < // <= // > // >= //std::swap }; } #endif //MYVECTOR_HPP<commit_msg>updated clear()<commit_after>#ifndef MYVECTOR_HPP #define MYVECTOR_HPP 1 #include <algorithm> #include <cstddef> #include <iostream> #include <memory> namespace sandsnip3r { template<typename Type> class MyVectorIterator { private: }; template<typename Type> class MyVector { public: typedef Type value_type; typedef std::allocator<value_type> allocator_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; typedef const Type* const_pointer; //iterator //const_iterator //reverse_iterator //const_reverse_iterator private: std::allocator<value_type> vectorAllocator; std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData; size_t vectorSize{0}; size_t vectorCapacity{0}; void reallocate(size_type newCapacity) { //Allocate memory for the new data if (newCapacity > this->max_size()) { throw std::length_error("MyVector::reallocate() newCapacity (which is "+std::to_string(newCapacity)+") > max_size (which is "+std::to_string(this->max_size())+")"); } // store it in a unique_ptr std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){ vectorAllocator.deallocate(ptr, newCapacity); }); //Move the old data into out new storage chunk const auto &dataBegin = vectorData.get(); std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get()); //Assign the new data to be the current vectorData = std::move(newData); //Update the capacity vectorCapacity = newCapacity; } public: //constructor ~MyVector() { this->clear(); } //operator= //assign allocator_type get_allocator() const { return vectorAllocator; } reference at(size_type pos) { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->at(pos)); } const_reference at(size_type pos) const { if (!(pos < this->size())) { throw std::out_of_range("MyVector::at() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")"); } return vectorData[pos]; } reference operator[](size_type pos) { return vectorData[pos]; } const_reference operator[](size_type pos) const { return vectorData[pos]; } reference front() { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->front()); } const_reference front() const { if (this->empty()) { throw std::out_of_range("MyVector::front(), but it's empty"); } return vectorData[0]; } reference back() { return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->back()); } const_reference back() const { if (this->empty()) { throw std::out_of_range("MyVector::back(), but it's empty"); } return vectorData[this->size()-1]; } pointer data() { return vectorData.get(); } const_pointer data() const { return vectorData.get(); } //begin, cbegin //end, cend //rbegin, crbegin //rend, crend bool empty() const { return (this->size() == 0); } size_type size() const { return vectorSize; } //max_size size_type max_size() const { return std::numeric_limits<decltype(vectorSize)>::max(); } void reserve(size_type newCapacity) { if (this->capacity() < newCapacity) { reallocate(newCapacity); } } size_type capacity() const { return vectorCapacity; } void shrink_to_fit() { if (this->size() < this->capacity()) { reallocate(vectorSize); } } void clear() { for (size_type i=0; i<this->size(); ++i) { vectorData[i].~value_type(); } vectorSize = 0; } //insert //emplace //erase void push_back(const value_type &obj) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{obj}; ++vectorSize; } void push_back(value_type &&obj) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{std::move(obj)}; ++vectorSize; } template<class... Args> void emplace_back(Args&&... args) { if (this->size() == this->capacity()) { //Need to reallocate to make space auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2); reserve(newCapacity); } new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...}; ++vectorSize; } void pop_back() { if (!this->empty()) { vectorData[this->size()-1].~value_type(); --vectorSize; } } void resize(size_type count) { if (this->size() < count) { if (this->capacity() < count) { //need to allocate more reallocate(count); } while (vectorSize < count) { //Fill with default constructed elements new(vectorData.get()+vectorSize) value_type{}; ++vectorSize; } } else if (this->size() > count) { for (size_type i=this->size()-1; i>=count; --i) { vectorData[i].~value_type(); --vectorSize; } } } void resize(size_type count, const value_type &value) { if (this->size() < count) { if (this->capacity() < count) { //need to allocate more reallocate(count); } while (vectorSize < count) { //Fill with default constructed elements new(vectorData.get()+vectorSize) value_type{value}; ++vectorSize; } } else if (this->size() > count) { for (size_type i=this->size()-1; i>=count; --i) { vectorData[i].~value_type(); --vectorSize; } } } //swap //operators: // == // != // < // <= // > // >= //std::swap }; } #endif //MYVECTOR_HPP<|endoftext|>
<commit_before>/* Time.cpp (c)2005 Palestar, Richard Lyle */ #include "String.h" #include "Time.h" #include "Bits.h" #include "Debug/SafeThread.h" #include <time.h> #include <sys/timeb.h> //! Define to non-zero to enable the use of QueryPerformanceCount() for Time::milliseconds().. #define ENABLE_QPC 1 //! Define to non-zero to enable the use of winmm for Time::milliseconds()... #define ENABLE_WINMM 0 #if defined(_WIN32) #include <windows.h> #include <intrin.h> #pragma intrinsic(__rdtsc) qword rdtsc() { return __rdtsc(); } #else qword rdtsc() { unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi)); return ((uint64_t)hi << 32) | lo; } #endif #pragma warning( disable : 4996 ) // warning C4996: 'localtime' was declared deprecated #if ENABLE_QPC && defined(_WIN32) class QPCThread : public SafeThread { public: QPCThread() : SafeThread(CRITICAL), m_bActive(true), m_nMilliseconds(0) {} virtual ~QPCThread() { m_bActive = false; } virtual int run() { DWORD_PTR nProcessAffin = 0; DWORD_PTR nSystemAffin = 0; if (!GetProcessAffinityMask(GetCurrentProcess(), &nProcessAffin, &nSystemAffin)) THROW_EXCEPTION("Call failed to GetProcessAffinityMask()"); // force this thread to run on the first core assigned to our process.. DWORD nProcessor = GetFirstBit((nProcessAffin & nSystemAffin)); if (!SetThreadAffinityMask(GetCurrentThread(), 1 << nProcessor)) THROW_EXCEPTION("Call failed to SetThreadAffinityMask()"); while (m_bActive) { LARGE_INTEGER f, t; if (!QueryPerformanceFrequency(&f)) THROW_EXCEPTION("Call failed to QueryPerformanceFrequency()"); if (! QueryPerformanceCounter( &t ) ) THROW_EXCEPTION("Call failed to QueryPerformanceCounter()"); m_nMilliseconds = (dword)((1000LL * t.QuadPart) / f.QuadPart); // sleep for 1 millisecond .. Sleep(1); } return 0; } volatile bool m_bActive; volatile dword m_nMilliseconds; }; static QPCThread s_QPCThread; #endif //---------------------------------------------------------------------------- const int MAX_TIME_FORMAT_STRING = 256; //---------------------------------------------------------------------------- qword Time::CPU() { return rdtsc(); } dword Time::seconds() { #if defined(_WIN32) return (dword)::_time32(NULL); #else return (dword)::time(NULL); #endif } dword Time::milliseconds() { #if defined(_WIN32) #if ENABLE_QPC if (s_QPCThread.suspended()) { s_QPCThread.resume(); Sleep(1); // let the first calculation occur.. } return s_QPCThread.m_nMilliseconds; #elif ENABLE_WINMM static DWORD(WINAPI * pTimeGetTime)() = (DWORD(WINAPI *)())GetProcAddress(LoadLibrary("winmm"), "timeGetTime");; if (pTimeGetTime != NULL) return pTimeGetTime(); #endif return GetTickCount(); #else static dword nStartTime = Time::seconds(); timeb t; ftime(&t); return ((t.time - nStartTime) * 1000) + t.millitm; #endif // #if defined(_WIN32) } WideString Time::format(dword nTime, const wchar * pFormat) { wchar sOut[MAX_TIME_FORMAT_STRING]; #if defined(_WIN32) wcsftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, _localtime32((__time32_t *)&nTime)); #else wcsftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, localtime((time_t *)&nTime)); #endif return WideString(sOut); } CharString Time::format(dword nTime, const char * pFormat) { char sOut[MAX_TIME_FORMAT_STRING]; #if defined(_WIN32) strftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, _localtime32((__time32_t *)&nTime)); #else strftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, localtime((time_t *)&nTime)); #endif return CharString(sOut); } static bool CheckMaskPart(const char * pMask, int n) { if (pMask[0] == '*') return true; if (pMask[0] == 0) return false; const char * pSplit = strchr(pMask, '-'); if (pSplit != NULL && pSplit > pMask) { // range k-j int k = atoi(pMask); int j = atoi(pSplit + 1); return n >= k && n <= j; } int k = atoi(pMask); if (pMask[0] == '+' && k != 0) return (n % k) == 0; else return k == n; } // mask is formated as "MON/DAY/YEAR HOUR:MIN:SEC" bool Time::isTime(dword nSeconds, const char * pMask) { CharString sMask = pMask; if (sMask.length() == 0) return false; // get the mask parts CharString sParts[6]; for (int i = 0; i < 6 && sMask.tokenize(sParts[i], " /:"); i++); #if defined(_WIN32) tm * pTime = _localtime32((const __time32_t *)&nSeconds); #else tm * pTime = localtime((const time_t *)&nSeconds); #endif if (!CheckMaskPart(sParts[0], (pTime->tm_mon + 1))) return false; if (!CheckMaskPart(sParts[1], pTime->tm_mday)) return false; if (!CheckMaskPart(sParts[2], pTime->tm_year + 1900) && !CheckMaskPart(sParts[2], pTime->tm_year - 100)) return false; if (!CheckMaskPart(sParts[3], pTime->tm_hour)) return false; if (!CheckMaskPart(sParts[4], pTime->tm_min)) return false; if (!CheckMaskPart(sParts[5], pTime->tm_sec)) return false; return true; } CharString Time::time(dword nSeconds) { #if defined(_WIN32) return _ctime32((__time32_t *)&nSeconds); #else return ctime((time_t *)&nSeconds); #endif } bool Time::setTime(dword nSeconds) { #if defined(_WIN32) tm * gm = _gmtime32((__time32_t *)&nSeconds); SYSTEMTIME time; time.wYear = gm->tm_year + 1900; time.wMonth = gm->tm_mon + 1; time.wDayOfWeek = 0; // this is ignored by SetSystemTime() time.wDay = gm->tm_mday; time.wHour = gm->tm_hour; time.wMinute = gm->tm_min; time.wSecond = gm->tm_sec; time.wMilliseconds = 0; return SetSystemTime(&time) != 0; #else return false; #endif } //---------------------------------------------------------------------------- // EOF <commit_msg>Need to include <cstdint> for uint64_t on Linux...<commit_after>/* Time.cpp (c)2005 Palestar, Richard Lyle */ #include "String.h" #include "Time.h" #include "Bits.h" #include "Debug/SafeThread.h" #include <time.h> #include <sys/timeb.h> //! Define to non-zero to enable the use of QueryPerformanceCount() for Time::milliseconds().. #define ENABLE_QPC 1 //! Define to non-zero to enable the use of winmm for Time::milliseconds()... #define ENABLE_WINMM 0 #if defined(_WIN32) #include <windows.h> #include <intrin.h> #pragma intrinsic(__rdtsc) qword rdtsc() { return __rdtsc(); } #else #include <cstdint> qword rdtsc() { uint32_t hi, lo; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); return ((uint64_t)lo) | (((uint64_t)hi) << 32); } #endif #pragma warning( disable : 4996 ) // warning C4996: 'localtime' was declared deprecated #if ENABLE_QPC && defined(_WIN32) class QPCThread : public SafeThread { public: QPCThread() : SafeThread(CRITICAL), m_bActive(true), m_nMilliseconds(0) {} virtual ~QPCThread() { m_bActive = false; } virtual int run() { DWORD_PTR nProcessAffin = 0; DWORD_PTR nSystemAffin = 0; if (!GetProcessAffinityMask(GetCurrentProcess(), &nProcessAffin, &nSystemAffin)) THROW_EXCEPTION("Call failed to GetProcessAffinityMask()"); // force this thread to run on the first core assigned to our process.. DWORD nProcessor = GetFirstBit((nProcessAffin & nSystemAffin)); if (!SetThreadAffinityMask(GetCurrentThread(), 1 << nProcessor)) THROW_EXCEPTION("Call failed to SetThreadAffinityMask()"); while (m_bActive) { LARGE_INTEGER f, t; if (!QueryPerformanceFrequency(&f)) THROW_EXCEPTION("Call failed to QueryPerformanceFrequency()"); if (! QueryPerformanceCounter( &t ) ) THROW_EXCEPTION("Call failed to QueryPerformanceCounter()"); m_nMilliseconds = (dword)((1000LL * t.QuadPart) / f.QuadPart); // sleep for 1 millisecond .. Sleep(1); } return 0; } volatile bool m_bActive; volatile dword m_nMilliseconds; }; static QPCThread s_QPCThread; #endif //---------------------------------------------------------------------------- const int MAX_TIME_FORMAT_STRING = 256; //---------------------------------------------------------------------------- qword Time::CPU() { return rdtsc(); } dword Time::seconds() { #if defined(_WIN32) return (dword)::_time32(NULL); #else return (dword)::time(NULL); #endif } dword Time::milliseconds() { #if defined(_WIN32) #if ENABLE_QPC if (s_QPCThread.suspended()) { s_QPCThread.resume(); Sleep(1); // let the first calculation occur.. } return s_QPCThread.m_nMilliseconds; #elif ENABLE_WINMM static DWORD(WINAPI * pTimeGetTime)() = (DWORD(WINAPI *)())GetProcAddress(LoadLibrary("winmm"), "timeGetTime");; if (pTimeGetTime != NULL) return pTimeGetTime(); #endif return GetTickCount(); #else static dword nStartTime = Time::seconds(); timeb t; ftime(&t); return ((t.time - nStartTime) * 1000) + t.millitm; #endif // #if defined(_WIN32) } WideString Time::format(dword nTime, const wchar * pFormat) { wchar sOut[MAX_TIME_FORMAT_STRING]; #if defined(_WIN32) wcsftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, _localtime32((__time32_t *)&nTime)); #else wcsftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, localtime((time_t *)&nTime)); #endif return WideString(sOut); } CharString Time::format(dword nTime, const char * pFormat) { char sOut[MAX_TIME_FORMAT_STRING]; #if defined(_WIN32) strftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, _localtime32((__time32_t *)&nTime)); #else strftime(sOut, MAX_TIME_FORMAT_STRING, pFormat, localtime((time_t *)&nTime)); #endif return CharString(sOut); } static bool CheckMaskPart(const char * pMask, int n) { if (pMask[0] == '*') return true; if (pMask[0] == 0) return false; const char * pSplit = strchr(pMask, '-'); if (pSplit != NULL && pSplit > pMask) { // range k-j int k = atoi(pMask); int j = atoi(pSplit + 1); return n >= k && n <= j; } int k = atoi(pMask); if (pMask[0] == '+' && k != 0) return (n % k) == 0; else return k == n; } // mask is formated as "MON/DAY/YEAR HOUR:MIN:SEC" bool Time::isTime(dword nSeconds, const char * pMask) { CharString sMask = pMask; if (sMask.length() == 0) return false; // get the mask parts CharString sParts[6]; for (int i = 0; i < 6 && sMask.tokenize(sParts[i], " /:"); i++); #if defined(_WIN32) tm * pTime = _localtime32((const __time32_t *)&nSeconds); #else tm * pTime = localtime((const time_t *)&nSeconds); #endif if (!CheckMaskPart(sParts[0], (pTime->tm_mon + 1))) return false; if (!CheckMaskPart(sParts[1], pTime->tm_mday)) return false; if (!CheckMaskPart(sParts[2], pTime->tm_year + 1900) && !CheckMaskPart(sParts[2], pTime->tm_year - 100)) return false; if (!CheckMaskPart(sParts[3], pTime->tm_hour)) return false; if (!CheckMaskPart(sParts[4], pTime->tm_min)) return false; if (!CheckMaskPart(sParts[5], pTime->tm_sec)) return false; return true; } CharString Time::time(dword nSeconds) { #if defined(_WIN32) return _ctime32((__time32_t *)&nSeconds); #else return ctime((time_t *)&nSeconds); #endif } bool Time::setTime(dword nSeconds) { #if defined(_WIN32) tm * gm = _gmtime32((__time32_t *)&nSeconds); SYSTEMTIME time; time.wYear = gm->tm_year + 1900; time.wMonth = gm->tm_mon + 1; time.wDayOfWeek = 0; // this is ignored by SetSystemTime() time.wDay = gm->tm_mday; time.wHour = gm->tm_hour; time.wMinute = gm->tm_min; time.wSecond = gm->tm_sec; time.wMilliseconds = 0; return SetSystemTime(&time) != 0; #else return false; #endif } //---------------------------------------------------------------------------- // EOF <|endoftext|>
<commit_before>#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); if (spot > 9 && spot != 14) { // non equip items TODO: put that magic value somewhere else return false; } return item.type == spot; } inline bool is_spot_equipped(size_t spot) { return spot > 9 && spot != 14; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; uint8_t type = 0; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[from])); entitySystem.send_nearby(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); } void add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); } bool remove_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.zuly < zuly) { return false; } inv.zuly -= zuly; entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); if (to == 0) { // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, from); } else { equip_item(entitySystem, entity, from, to); } } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index < 1 || index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } const auto item = remove_item(entitySystem, entity, index, quantity); const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); } <commit_msg>Update inventory.cpp<commit_after>#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); if (spot > 9 && spot != 14) { // non equip items TODO: put that magic value somewhere else return false; } return item.type == spot; } inline bool is_spot_equipped(size_t spot) { return spot > 9 && spot != 14; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; uint8_t type = 0; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[from])); entitySystem.send_nearby(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); } bool add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (zuly < 0 && inv.zuly + zuly < 0) { return false; } else if (zuly < 0) { inv.zuly += zuly; } else { inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); } entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); if (to == 0) { // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, from); } else { equip_item(entitySystem, entity, from, to); } } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index < 1 || index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } const auto item = remove_item(entitySystem, entity, index, quantity); const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); } <|endoftext|>
<commit_before>#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { // only for items, not cart/castle gear inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); const EquippedPosition pos = static_cast<EquippedPosition>(spot); if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) { return true; // we don't care of the spot if we are not equipping anything } switch (item.type) { case ItemType::ITEM_GOGGLES: return pos == EquippedPosition::GOGGLES; case ItemType::ITEM_HELMET: return pos == EquippedPosition::HELMET; case ItemType::ITEM_ARMOR: return pos == EquippedPosition::ARMOR; case ItemType::ITEM_GAUNTLET: return pos == EquippedPosition::GAUNTLET; case ItemType::ITEM_BOOTS: return pos == EquippedPosition::BOOTS; case ItemType::ITEM_BACKPACK: return pos == EquippedPosition::BACKPACK; case ItemType::ITEM_RING: return pos == EquippedPosition::RING; case ItemType::ITEM_WEAPON_R: return pos == EquippedPosition::WEAPON_R; case ItemType::ITEM_WEAPON_L: return pos == EquippedPosition::WEAPON_L; default: return false; } } inline bool is_spot_equipped(size_t spot) { return spot < EquippedPosition::MAX_EQUIP_ITEMS; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; ItemType type = ItemType::NONE; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {}); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item({}); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) { entitySystem.delete_entity(item); }); } void Items::pickup_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const float x = entitySystem.get_component<Component::Position>(item).x; const float y = entitySystem.get_component<Component::Position>(item).y; const auto* owner = entitySystem.try_get_component<Component::Owner>(item); if (owner && owner->owner != entity) { return; } entitySystem.remove_component<Component::Position>(item); entitySystem.remove_component<Component::BasicInfo>(item); entitySystem.remove_component<Component::Owner>(item); if (Items::add_item(entitySystem, entity, item) != ReturnValue::OK) { const RoseCommon::Entity o = owner ? owner->owner : entt::null; Items::drop_item(entitySystem, item, x, y, o); } } bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (zuly < 0 && inv.zuly + zuly < 0) { return false; } else if (zuly < 0) { inv.zuly += zuly; } else { inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); } entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, to): equip_item(entitySystem, entity, from, to); (void) res; } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } RoseCommon::Entity item = entt::null; if (index == 0) { // we drop zulies if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) { item = entitySystem.create_zuly(packet.get_quantity()); } else { return; // we don't have enough zuly to remove } } else { item = remove_item(entitySystem, entity, index, quantity); } const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); } <commit_msg>Added 2min timer for ownership<commit_after>#include "items/inventory.h" #include "entity_system.h" #include "dataconsts.h" #include "random.h" #include "components/basic_info.h" #include "components/inventory.h" #include "components/item.h" #include "components/lua.h" #include "components/position.h" #include "components/owner.h" #include "itemdb.h" #include "srv_equip_item.h" #include "srv_set_item.h" #include "srv_set_money.h" #include <limits> using namespace RoseCommon; using namespace Items; namespace { // only for items, not cart/castle gear inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) { const auto& item = entitySystem.get_component<ItemDef>(entity); const EquippedPosition pos = static_cast<EquippedPosition>(spot); if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) { return true; // we don't care of the spot if we are not equipping anything } switch (item.type) { case ItemType::ITEM_GOGGLES: return pos == EquippedPosition::GOGGLES; case ItemType::ITEM_HELMET: return pos == EquippedPosition::HELMET; case ItemType::ITEM_ARMOR: return pos == EquippedPosition::ARMOR; case ItemType::ITEM_GAUNTLET: return pos == EquippedPosition::GAUNTLET; case ItemType::ITEM_BOOTS: return pos == EquippedPosition::BOOTS; case ItemType::ITEM_BACKPACK: return pos == EquippedPosition::BACKPACK; case ItemType::ITEM_RING: return pos == EquippedPosition::RING; case ItemType::ITEM_WEAPON_R: return pos == EquippedPosition::WEAPON_R; case ItemType::ITEM_WEAPON_L: return pos == EquippedPosition::WEAPON_L; default: return false; } } inline bool is_spot_equipped(size_t spot) { return spot < EquippedPosition::MAX_EQUIP_ITEMS; } } size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); size_t res = decltype(inv.getInventory())::offset(); bool stackable = false; ItemType type = ItemType::NONE; uint16_t id = 0; if (item != entt::null) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); stackable = i.is_stackable; type = i.type; id = i.id; } for (const auto item : inv.getInventory()) { if (item == entt::null) { return res; } else if (stackable) { const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item); const auto& it = entitySystem.get_component<Component::Item>(item); if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) { return res; } } ++res; } return 0; } ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const size_t pos = get_first_available_spot(entitySystem, entity, item); if (pos == 0) { return ReturnValue::NO_SPACE; } auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (inv.items[pos] == entt::null) { inv.items[pos] = item; } else { // add the stack auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]); auto& it = entitySystem.get_component<Component::Item>(item); if (i.count + it.count < RoseCommon::MAX_STACK) { // below max stack i.count += it.count; } else { // split the stack in two or more const uint32_t stack_tmp1 = i.count; const uint32_t stack_tmp2 = it.count; it.count -= RoseCommon::MAX_STACK - i.count; i.count = RoseCommon::MAX_STACK; if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) { it.count = stack_tmp2; i.count = stack_tmp1; return ReturnValue::NO_SPACE; } } } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); RoseCommon::Entity item = inv.items[pos]; auto& i = entitySystem.get_component<Component::Item>(item); const auto& it = entitySystem.get_component<ItemDef>(item); if (i.count < quantity) { return entt::null; } if (i.count > quantity) { const auto type = it.type; const auto id = it.id; i.count -= quantity; RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity); RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return newItem; } if (is_spot_equipped(pos)) { const auto& lua = entitySystem.get_component<Component::ItemLua>(item); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(item)) { return entt::null; } } } inv.items[pos] = entt::null; RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); entitySystem.send_to(entity, packet); return item; } void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); std::swap(inv.items[pos1], inv.items[pos2]); } ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) { const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) { return ReturnValue::WRONG_INDEX; } if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[to]; const RoseCommon::Entity to_equip = inv.items[from]; if (!is_spot_correct(entitySystem, to_equip, to)) { return ReturnValue::REQUIREMENTS_NOT_MET; } if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } if (from != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_equip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to, entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to])); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) { const size_t to = get_first_available_spot(entitySystem, entity); if (to == 0) { return ReturnValue::NO_SPACE; } const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) { return ReturnValue::WRONG_INDEX; } const RoseCommon::Entity equipped = inv.items[from]; if (equipped != entt::null) { const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped); if (const auto tmp = lua.api.lock(); tmp) { if (!tmp->on_unequip(entity)) { //return ReturnValue::REQUIREMENTS_NOT_MET; } } } swap_item(entitySystem, entity, from, to); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); { const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {}); entitySystem.send_nearby(entity, packet); } RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to); index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped)); auto packet = RoseCommon::Packet::SrvSetItem::create(); packet.add_items(index); index.set_index(from); index.set_item({}); packet.add_items(index); entitySystem.send_to(entity, packet); return ReturnValue::OK; } void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) { Component::BasicInfo bi; bi.id = entitySystem.get_free_id(); if (owner != entt::null) { const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner); bi.teamId = basicInfo.teamId; auto& Cowner = entitySystem.add_component<Component::Owner>(item); Cowner.owner = owner; } else { bi.teamId = bi.id; } entitySystem.add_component(item, std::move(bi)); entitySystem.update_position(item, x, y); entitySystem.add_timer(2min, [item](EntitySystem& entitySystem) { if (entitySystem.has_component<Component::Owner>(item)) { entitySystem.remove_component<Component::Owner>(item); auto& basic = entitySystem.get_component<Component::BasicInfo>(item); basic.teamId = basic.id; } }); entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) { if (entitySystem.has_component<Component::Position>(item)) { entitySystem.delete_entity(item); } }); } void Items::pickup_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) { const float x = entitySystem.get_component<Component::Position>(item).x; const float y = entitySystem.get_component<Component::Position>(item).y; const auto* owner = entitySystem.try_get_component<Component::Owner>(item); if (owner && owner->owner != entity) { return; } entitySystem.remove_component<Component::Position>(item); entitySystem.remove_component<Component::BasicInfo>(item); entitySystem.remove_component<Component::Owner>(item); if (Items::add_item(entitySystem, entity, item) != ReturnValue::OK) { const RoseCommon::Entity o = owner ? owner->owner : entt::null; Items::drop_item(entitySystem, item, x, y, o); } } bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) { auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (zuly < 0 && inv.zuly + zuly < 0) { return false; } else if (zuly < 0) { inv.zuly += zuly; } else { inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly), static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))); } entitySystem.send_to(entity, RoseCommon::Packet::SrvSetMoney::create(inv.zuly)); return true; } void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo()); const auto from = packet.get_slotFrom(); const auto to = packet.get_slotTo(); const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag unequip_item(entitySystem, entity, to): equip_item(entitySystem, entity, from, to); (void) res; } void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("equip_item_packet()"); logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity()); const auto index = packet.get_index(); const auto quantity = packet.get_quantity(); const auto& inv = entitySystem.get_component<Component::Inventory>(entity); if (index > inv.items.size()) { logger->warn("wrong index {} for item drop, client {}", index, entity); return; } RoseCommon::Entity item = entt::null; if (index == 0) { // we drop zulies if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) { item = entitySystem.create_zuly(packet.get_quantity()); } else { return; // we don't have enough zuly to remove } } else { item = remove_item(entitySystem, entity, index, quantity); } const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE); drop_item(entitySystem, item, x, y, entity); } <|endoftext|>
<commit_before>#include <class_loader/class_loader.h> #include <utexas_guidance/mdp/guidance_model.h> #include <utexas_guidance/mdp/single_robot_solver.h> #include <utexas_planning/common/exceptions.h> namespace utexas_guidance { class ActionEquals { public: explicit ActionEquals(const Action& a) : a_(a) {} inline bool operator() (const utexas_planning::Action::ConstPtr& action_base) const { Action::ConstPtr action = boost::dynamic_pointer_cast<const Action>(action_base); if (!action) { throw utexas_planning::DowncastException("utexas_planning::Action", "utexas_guidance::Action"); } return (*action == a_); } private: Action a_; }; SingleRobotSolver::~SingleRobotSolver() {} void SingleRobotSolver::init(const utexas_planning::GenerativeModel::ConstPtr& model_base, const YAML::Node& params, const std::string& output_directory, const boost::shared_ptr<RNG>& rng, bool verbose) { model_ = boost::dynamic_pointer_cast<const GuidanceModel>(model_base); if (!model_) { throw utexas_planning::DowncastException("utexas_planning::GenerativeModel", "utexas_guidance::GuidanceModel"); } model_->getUnderlyingGraph(graph_); rng_ = rng; getAllAdjacentVertices(adjacent_vertices_map_, graph_); getAllShortestPaths(shortest_distances_, shortest_paths_, graph_); } void SingleRobotSolver::performEpisodeStartProcessing(const utexas_planning::State::ConstPtr& start_state, float timeout) {} utexas_planning::Action::ConstPtr SingleRobotSolver::getBestAction(const utexas_planning::State::ConstPtr& state_base) const { State::ConstPtr state = boost::dynamic_pointer_cast<const State>(state_base); if (!state) { throw utexas_planning::DowncastException("utexas_planning::State", "utexas_guidance::State"); } std::vector<utexas_planning::Action::ConstPtr> actions; model_->getActionsAtState(state, actions); // Lead via shortest path. std::vector<std::pair<int, int> > robot_request_ids; getColocatedRobotRequestIds(*state, robot_request_ids); for (unsigned int idx_num = 0; idx_num < robot_request_ids.size(); ++idx_num) { int robot_id = robot_request_ids[idx_num].first; int request_id = robot_request_ids[idx_num].second; const RequestState& request = state->requests[request_id]; Action a(LEAD_PERSON, robot_id, shortest_paths_[request.loc_node][request.goal][0], request_id); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } int num_assigned_robots = 0; for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE) { ++num_assigned_robots; } } /* This logic isn't the best as the default policy, but better than nothing to prevent unnecessary robots. */ if (num_assigned_robots > state->requests.size()) { for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE && !(state->robots[robot_idx].is_leading_person)) { Action a(RELEASE_ROBOT, robot_idx); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } } } return Action::ConstPtr(new Action(WAIT)); } void SingleRobotSolver::performPreActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& prev_action, float timeout) { std::cout << timeout << std::endl; boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } void SingleRobotSolver::performPostActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& action, float timeout) { std::cout << timeout << std::endl; boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } std::string SingleRobotSolver::getName() const { return std::string("SingleRobot"); } } /* utexas_guidance */ CLASS_LOADER_REGISTER_CLASS(utexas_guidance::SingleRobotSolver, utexas_planning::AbstractPlanner) <commit_msg>removed stray printouts.<commit_after>#include <class_loader/class_loader.h> #include <utexas_guidance/mdp/guidance_model.h> #include <utexas_guidance/mdp/single_robot_solver.h> #include <utexas_planning/common/exceptions.h> namespace utexas_guidance { class ActionEquals { public: explicit ActionEquals(const Action& a) : a_(a) {} inline bool operator() (const utexas_planning::Action::ConstPtr& action_base) const { Action::ConstPtr action = boost::dynamic_pointer_cast<const Action>(action_base); if (!action) { throw utexas_planning::DowncastException("utexas_planning::Action", "utexas_guidance::Action"); } return (*action == a_); } private: Action a_; }; SingleRobotSolver::~SingleRobotSolver() {} void SingleRobotSolver::init(const utexas_planning::GenerativeModel::ConstPtr& model_base, const YAML::Node& params, const std::string& output_directory, const boost::shared_ptr<RNG>& rng, bool verbose) { model_ = boost::dynamic_pointer_cast<const GuidanceModel>(model_base); if (!model_) { throw utexas_planning::DowncastException("utexas_planning::GenerativeModel", "utexas_guidance::GuidanceModel"); } model_->getUnderlyingGraph(graph_); rng_ = rng; getAllAdjacentVertices(adjacent_vertices_map_, graph_); getAllShortestPaths(shortest_distances_, shortest_paths_, graph_); } void SingleRobotSolver::performEpisodeStartProcessing(const utexas_planning::State::ConstPtr& start_state, float timeout) {} utexas_planning::Action::ConstPtr SingleRobotSolver::getBestAction(const utexas_planning::State::ConstPtr& state_base) const { State::ConstPtr state = boost::dynamic_pointer_cast<const State>(state_base); if (!state) { throw utexas_planning::DowncastException("utexas_planning::State", "utexas_guidance::State"); } std::vector<utexas_planning::Action::ConstPtr> actions; model_->getActionsAtState(state, actions); // Lead via shortest path. std::vector<std::pair<int, int> > robot_request_ids; getColocatedRobotRequestIds(*state, robot_request_ids); for (unsigned int idx_num = 0; idx_num < robot_request_ids.size(); ++idx_num) { int robot_id = robot_request_ids[idx_num].first; int request_id = robot_request_ids[idx_num].second; const RequestState& request = state->requests[request_id]; Action a(LEAD_PERSON, robot_id, shortest_paths_[request.loc_node][request.goal][0], request_id); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } int num_assigned_robots = 0; for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE) { ++num_assigned_robots; } } /* This logic isn't the best as the default policy, but better than nothing to prevent unnecessary robots. */ if (num_assigned_robots > state->requests.size()) { for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE && !(state->robots[robot_idx].is_leading_person)) { Action a(RELEASE_ROBOT, robot_idx); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } } } return Action::ConstPtr(new Action(WAIT)); } void SingleRobotSolver::performPreActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& prev_action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } void SingleRobotSolver::performPostActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } std::string SingleRobotSolver::getName() const { return std::string("SingleRobot"); } } /* utexas_guidance */ CLASS_LOADER_REGISTER_CLASS(utexas_guidance::SingleRobotSolver, utexas_planning::AbstractPlanner) <|endoftext|>
<commit_before>#include "widget.h" void Widget::CreateTrayIcon() { QMenu* pTrayIconMenu = new QMenu(this); pTrayIconMenu->addAction(m_pOpenAction); pTrayIconMenu->addSeparator(); pTrayIconMenu->addAction(m_pPostponeAction); pTrayIconMenu->addSeparator(); pTrayIconMenu->addAction(m_pQuitAction); if(m_pTrayIcon) { m_pTrayIcon->setContextMenu(pTrayIconMenu); } } void Widget::SetTrayIcon(QString strIcon) { if(strIcon != m_strSetTrayIcon && m_pTrayIcon) { QIcon icon(strIcon); m_pTrayIcon->setIcon(icon); m_pTrayIcon->setVisible(true); m_strSetTrayIcon = strIcon; } } void Widget::LoadValues() { m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this); qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName(); UserTimeSettings::SetWorkTime_s(m_pAppSettings->value("work_time", UserTimeSettings::WorkTime_s()).toInt()); UserTimeSettings::SetRestTime_s(m_pAppSettings->value("rest_time", UserTimeSettings::RestTime_s()).toInt()); UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value("tolerance_time", UserTimeSettings::ToleranceTime_s()).toInt()); } void Widget::CreateLayout() { QVBoxLayout* pTimeLayout = new QVBoxLayout; // work spin box QHBoxLayout* pWorkLayout = new QHBoxLayout; QLabel* pWorkLabel = new QLabel(tr("Work time [mins]")); QSpinBox* pSpinWorkTime_s = new QSpinBox(this); // TODO - má tu být this? Nemá tu být některý child? pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() / 60); pSpinWorkTime_s->setMaximum(999); connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetWorkTime_s(nNewValue * 60); m_pAppSettings->setValue("work_time", UserTimeSettings::WorkTime_s()); }); pWorkLayout->addWidget(pWorkLabel); pWorkLayout->addWidget(pSpinWorkTime_s); // rest spin box QHBoxLayout* pRestLayout = new QHBoxLayout; QLabel* pRestLabel = new QLabel(tr("Rest time [mins]")); QSpinBox* pSpinRestTime_s = new QSpinBox(this); pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() / 60); pSpinRestTime_s->setMaximum(999); connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetRestTime_s(nNewValue * 60); m_pAppSettings->setValue("rest_time", UserTimeSettings::RestTime_s()); }); pRestLayout->addWidget(pRestLabel); pRestLayout->addWidget(pSpinRestTime_s); // tolerance spin box QHBoxLayout* pToleranceLayout = new QHBoxLayout; QLabel* pToleranceLabel = new QLabel(tr("Tolerance time [s]")); QSpinBox* pSpinToleranceTime_s = new QSpinBox(this); pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s()); pSpinToleranceTime_s->setMaximum(999); connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetToleranceTime_s(nNewValue); m_pAppSettings->setValue("tolerance_time", UserTimeSettings::ToleranceTime_s()); }); pToleranceLayout->addWidget(pToleranceLabel); pToleranceLayout->addWidget(pSpinToleranceTime_s); // add all to vertical layout pTimeLayout->addLayout(pWorkLayout); pTimeLayout->addLayout(pRestLayout); pTimeLayout->addLayout(pToleranceLayout); // add label with info m_pLabel = new QLabel; QVBoxLayout* pMainLayout = new QVBoxLayout; pMainLayout->addLayout(pTimeLayout); m_pPassedToleranceBar = new QProgressBar(this); m_pPassedToleranceBar->setMaximum(0); m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000); // m_pPassedToleranceBar->setFormat(QString::number(LastUserInput::PassedTolerance_ms())); m_pPassedToleranceBar->setTextVisible(false); pMainLayout->addWidget(m_pPassedToleranceBar); pMainLayout->addWidget(m_pLabel); this->setLayout(pMainLayout); } void Widget::CreateActions() { m_pOpenAction = new QAction(tr("&Open"), this); connect(m_pOpenAction, &QAction::triggered, this, &Widget::OpenWindow); m_pPostponeAction = new QAction(tr("&Postpone the break"), this); connect(m_pOpenAction, &QAction::triggered, this, &Widget::PostponeTheBreak); m_pQuitAction = new QAction(tr("&Quit"), this); connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit); } void Widget::OpenWindow() { this->setWindowState(this->windowState() & ~Qt::WindowMinimized); this->show(); this->activateWindow(); } void Widget::PostponeTheBreak() { // TODO } void Widget::SetIconByTime() { if(LastUserInput::UserIdleTime_ms() > UserTimeSettings::RestTime_s()) { SetTrayIcon(":/go_icon.png"); } if(LastUserInput::UserActiveTime_ms() / 1000 < UserTimeSettings::WorkTime_s() && LastUserInput::UserActiveTime_ms() / 1000 > (UserTimeSettings::WorkTime_s() - UserTimeSettings::WarningTime_s())) { SetTrayIcon(":/ready_icon.png"); } if(LastUserInput::UserActiveTime_ms() / 1000 > UserTimeSettings::WorkTime_s()) { SetTrayIcon(":/stop_icon.png"); } } Widget::Widget(QWidget *parent) : QWidget(parent) { m_pTrayIcon = new QSystemTrayIcon(this); CreateActions(); CreateTrayIcon(); SetTrayIcon(":/go_icon.png"); LoadValues(); CreateLayout(); if(QSystemTrayIcon::isSystemTrayAvailable()) { qDebug() << "tray is avaible"; } connect(m_pTrayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason eReason) { qDebug() << eReason; switch (eReason) { case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::Trigger: OpenWindow(); break; default: break; } }); connect(&m_oBeepTimer, &QTimer::timeout, [=]() { if(LastUserInput::UserActiveTime_ms() / 1000 > UserTimeSettings::WorkTime_s()) { if(LastUserInput::UserIdleTime_ms() < 500) { QApplication::beep(); } } }); connect(&m_oTimer, &QTimer::timeout, [=]() { SetIconByTime(); LastUserInput::UpdateLastUserInput(); m_pPassedToleranceBar->setValue(LastUserInput::PassedTolerance_ms()); m_pLabel->setText(QString("User idle time\t\t%1\nUser active time\t\t%2") .arg(QDateTime::fromTime_t(LastUserInput::UserIdleTime_ms() / 1000).toUTC().toString("mm:ss")).arg(QDateTime::fromTime_t(LastUserInput::UserActiveTime_ms() / 1000).toUTC().toString("mm:ss"))); m_pTrayIcon->setToolTip(QString(tr("Work time is %1 mins")).arg(LastUserInput::UserActiveTime_ms() / (1000 * 60))); }); m_oTimer.start(100); m_oBeepTimer.start(1100); } void Widget::closeEvent(QCloseEvent *event) { if(m_pTrayIcon->isVisible()) { hide(); event->ignore(); } } <commit_msg>bugfix (multipling by 1000 is better)<commit_after>#include "widget.h" void Widget::CreateTrayIcon() { QMenu* pTrayIconMenu = new QMenu(this); pTrayIconMenu->addAction(m_pOpenAction); pTrayIconMenu->addSeparator(); pTrayIconMenu->addAction(m_pPostponeAction); pTrayIconMenu->addSeparator(); pTrayIconMenu->addAction(m_pQuitAction); if(m_pTrayIcon) { m_pTrayIcon->setContextMenu(pTrayIconMenu); } } void Widget::SetTrayIcon(QString strIcon) { if(strIcon != m_strSetTrayIcon && m_pTrayIcon) { QIcon icon(strIcon); m_pTrayIcon->setIcon(icon); m_pTrayIcon->setVisible(true); m_strSetTrayIcon = strIcon; } } void Widget::LoadValues() { m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this); qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName(); UserTimeSettings::SetWorkTime_s(m_pAppSettings->value("work_time", UserTimeSettings::WorkTime_s()).toInt()); UserTimeSettings::SetRestTime_s(m_pAppSettings->value("rest_time", UserTimeSettings::RestTime_s()).toInt()); UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value("tolerance_time", UserTimeSettings::ToleranceTime_s()).toInt()); } void Widget::CreateLayout() { QVBoxLayout* pTimeLayout = new QVBoxLayout; // work spin box QHBoxLayout* pWorkLayout = new QHBoxLayout; QLabel* pWorkLabel = new QLabel(tr("Work time [mins]")); QSpinBox* pSpinWorkTime_s = new QSpinBox(this); // TODO - má tu být this? Nemá tu být některý child? pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() / 60); pSpinWorkTime_s->setMaximum(999); connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetWorkTime_s(nNewValue * 60); m_pAppSettings->setValue("work_time", UserTimeSettings::WorkTime_s()); }); pWorkLayout->addWidget(pWorkLabel); pWorkLayout->addWidget(pSpinWorkTime_s); // rest spin box QHBoxLayout* pRestLayout = new QHBoxLayout; QLabel* pRestLabel = new QLabel(tr("Rest time [mins]")); QSpinBox* pSpinRestTime_s = new QSpinBox(this); pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() / 60); pSpinRestTime_s->setMaximum(999); connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetRestTime_s(nNewValue * 60); m_pAppSettings->setValue("rest_time", UserTimeSettings::RestTime_s()); }); pRestLayout->addWidget(pRestLabel); pRestLayout->addWidget(pSpinRestTime_s); // tolerance spin box QHBoxLayout* pToleranceLayout = new QHBoxLayout; QLabel* pToleranceLabel = new QLabel(tr("Tolerance time [s]")); QSpinBox* pSpinToleranceTime_s = new QSpinBox(this); pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s()); pSpinToleranceTime_s->setMaximum(999); connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [=](const int &nNewValue) { UserTimeSettings::SetToleranceTime_s(nNewValue); m_pAppSettings->setValue("tolerance_time", UserTimeSettings::ToleranceTime_s()); }); pToleranceLayout->addWidget(pToleranceLabel); pToleranceLayout->addWidget(pSpinToleranceTime_s); // add all to vertical layout pTimeLayout->addLayout(pWorkLayout); pTimeLayout->addLayout(pRestLayout); pTimeLayout->addLayout(pToleranceLayout); // add label with info m_pLabel = new QLabel; QVBoxLayout* pMainLayout = new QVBoxLayout; pMainLayout->addLayout(pTimeLayout); m_pPassedToleranceBar = new QProgressBar(this); m_pPassedToleranceBar->setMaximum(0); m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000); // m_pPassedToleranceBar->setFormat(QString::number(LastUserInput::PassedTolerance_ms())); m_pPassedToleranceBar->setTextVisible(false); pMainLayout->addWidget(m_pPassedToleranceBar); pMainLayout->addWidget(m_pLabel); this->setLayout(pMainLayout); } void Widget::CreateActions() { m_pOpenAction = new QAction(tr("&Open"), this); connect(m_pOpenAction, &QAction::triggered, this, &Widget::OpenWindow); m_pPostponeAction = new QAction(tr("&Postpone the break"), this); connect(m_pOpenAction, &QAction::triggered, this, &Widget::PostponeTheBreak); m_pQuitAction = new QAction(tr("&Quit"), this); connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit); } void Widget::OpenWindow() { this->setWindowState(this->windowState() & ~Qt::WindowMinimized); this->show(); this->activateWindow(); } void Widget::PostponeTheBreak() { // TODO } void Widget::SetIconByTime() { if(LastUserInput::UserIdleTime_ms() > UserTimeSettings::RestTime_s()) { SetTrayIcon(":/go_icon.png"); } if(LastUserInput::UserActiveTime_ms() < UserTimeSettings::WorkTime_s() * 1000 && LastUserInput::UserActiveTime_ms() > (UserTimeSettings::WorkTime_s() - UserTimeSettings::WarningTime_s()) * 1000) { SetTrayIcon(":/ready_icon.png"); } if(LastUserInput::UserActiveTime_ms() > UserTimeSettings::WorkTime_s() * 1000) { SetTrayIcon(":/stop_icon.png"); } } Widget::Widget(QWidget *parent) : QWidget(parent) { m_pTrayIcon = new QSystemTrayIcon(this); CreateActions(); CreateTrayIcon(); SetTrayIcon(":/go_icon.png"); LoadValues(); CreateLayout(); if(QSystemTrayIcon::isSystemTrayAvailable()) { qDebug() << "tray is avaible"; } connect(m_pTrayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason eReason) { qDebug() << eReason; switch (eReason) { case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::Trigger: OpenWindow(); break; default: break; } }); connect(&m_oBeepTimer, &QTimer::timeout, [=]() { if(LastUserInput::UserActiveTime_ms() > UserTimeSettings::WorkTime_s() * 1000) { if(LastUserInput::UserIdleTime_ms() < 500) { QApplication::beep(); } } }); connect(&m_oTimer, &QTimer::timeout, [=]() { SetIconByTime(); LastUserInput::UpdateLastUserInput(); m_pPassedToleranceBar->setValue(LastUserInput::PassedTolerance_ms() > m_pPassedToleranceBar->maximum() ? m_pPassedToleranceBar->maximum() : LastUserInput::PassedTolerance_ms()); m_pLabel->setText(QString("User idle time\t\t%1\nUser active time\t\t%2") .arg(QDateTime::fromTime_t(LastUserInput::UserIdleTime_ms() / 1000).toUTC().toString("mm:ss")).arg(QDateTime::fromTime_t(LastUserInput::UserActiveTime_ms() / 1000).toUTC().toString("mm:ss"))); m_pTrayIcon->setToolTip(QString(tr("Work time is %1 mins")).arg(LastUserInput::UserActiveTime_ms() / (1000 * 60))); }); m_oTimer.start(100); m_oBeepTimer.start(1100); } void Widget::closeEvent(QCloseEvent *event) { if(m_pTrayIcon->isVisible()) { hide(); event->ignore(); } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testOpensense.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ayman Habib, Ajay Seth * * * * 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. * * -------------------------------------------------------------------------- */ // INCLUDES #include <OpenSim/Simulation/OpenSense/OpenSenseUtilities.h> #include <OpenSim/Simulation/OpenSense/InverseKinematicsStudy.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; int main() { // Calibrate model and compare result to standard Model model = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "imuOrientations.sto", "pelvis_imu", SimTK::ZAxis, false); // Previous line produces a model with same name but "calibrated_" prefix. Model stdModel{ "std_calibrated_subject07.osim" }; ASSERT(model == stdModel); // Calibrate model from two different standing trials facing // opposite directions to verify that heading correction is working Model facingX = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "MT_012005D6_009-quaternions_calibration_trial_Facing_X.sto", "pelvis_imu", SimTK::ZAxis, false); facingX.setName("calibrated_FacingX"); facingX.finalizeFromProperties(); InverseKinematicsStudy ik_hjc("setup_track_HJC_trial.xml"); ik_hjc.setModel(facingX); ik_hjc.set_results_directory("ik_hjc_" + facingX.getName()); ik_hjc.run(false); // Now facing the opposite direction (negative X) Model facingNegX = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "MT_012005D6_009-quaternions_calibration_trial_Facing_negX.sto", "pelvis_imu", SimTK::ZAxis, false); facingNegX.setName("calibrated_FacingNegX"); facingNegX.finalizeFromProperties(); ik_hjc.setModel(facingNegX); ik_hjc.set_results_directory("ik_hjc_" + facingNegX.getName()); ik_hjc.run(false); Storage ik_X("ik_hjc_" + facingX.getName() + "/ik_MT_012005D6_009-quaternions_RHJCSwinger.mot"); Storage ik_negX("ik_hjc_" + facingNegX.getName() + "/ik_MT_012005D6_009-quaternions_RHJCSwinger.mot"); // calibration should only result in errors due to smallish (<10degs) // differences in static pose an should be unaffected by the large // (90+ degs) change in heading CHECK_STORAGE_AGAINST_STANDARD(ik_X, ik_negX, std::vector<double>(23, 10.0), __FILE__, __LINE__, "testOpenSense::IK solutions differed due to heading."); std::cout << "Done. All testOpensense cases passed." << endl; return 0; } <commit_msg>Make sure tolerances for comparison are adequately sized otherwise test will segfault,<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testOpensense.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ayman Habib, Ajay Seth * * * * 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. * * -------------------------------------------------------------------------- */ // INCLUDES #include <OpenSim/Simulation/OpenSense/OpenSenseUtilities.h> #include <OpenSim/Simulation/OpenSense/InverseKinematicsStudy.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; int main() { // Calibrate model and compare result to standard Model model = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "imuOrientations.sto", "pelvis_imu", SimTK::ZAxis, false); // Previous line produces a model with same name but "calibrated_" prefix. Model stdModel{ "std_calibrated_subject07.osim" }; ASSERT(model == stdModel); // Calibrate model from two different standing trials facing // opposite directions to verify that heading correction is working Model facingX = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "MT_012005D6_009-quaternions_calibration_trial_Facing_X.sto", "pelvis_imu", SimTK::ZAxis, false); facingX.setName("calibrated_FacingX"); facingX.finalizeFromProperties(); InverseKinematicsStudy ik_hjc("setup_track_HJC_trial.xml"); ik_hjc.setModel(facingX); ik_hjc.set_results_directory("ik_hjc_" + facingX.getName()); ik_hjc.run(false); // Now facing the opposite direction (negative X) Model facingNegX = OpenSenseUtilities::calibrateModelFromOrientations( "subject07.osim", "MT_012005D6_009-quaternions_calibration_trial_Facing_negX.sto", "pelvis_imu", SimTK::ZAxis, false); facingNegX.setName("calibrated_FacingNegX"); facingNegX.finalizeFromProperties(); ik_hjc.setModel(facingNegX); ik_hjc.set_results_directory("ik_hjc_" + facingNegX.getName()); ik_hjc.run(false); Storage ik_X("ik_hjc_" + facingX.getName() + "/ik_MT_012005D6_009-quaternions_RHJCSwinger.mot"); Storage ik_negX("ik_hjc_" + facingNegX.getName() + "/ik_MT_012005D6_009-quaternions_RHJCSwinger.mot"); int nc = ik_X.getColumnLabels().size(); // calibration should only result in errors due to smallish (<10degs) // differences in static pose an should be unaffected by the large // (90+ degs) change in heading CHECK_STORAGE_AGAINST_STANDARD(ik_X, ik_negX, std::vector<double>(nc, 10.0), __FILE__, __LINE__, "testOpenSense::IK solutions differed due to heading."); std::cout << "Done. All testOpensense cases passed." << endl; return 0; } <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/Vtk.h" #include "mirtk/PointSetIO.h" #include "vtkSmartPointer.h" #include "vtkPolyData.h" #include "vtkPolyDataReader.h" #include "vtkPolyDataWriter.h" #include "vtkPolyDataConnectivityFilter.h" #include "vtkCleanPolyData.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << endl; cout << "Usage: " << name << " <input> <output> [options]" << endl; cout << endl; cout << "Description:" << endl; cout << " Extract (largest) connected components of the input point set." << endl; cout << " The connected components are sorted by size, where the largest" << endl; cout << " connected component has index 0." << endl; cout << endl; cout << "Arguments:" << endl; cout << " input Input point set." << endl; cout << " output Output point set." << endl; cout << endl; cout << "Optional arguments:" << endl; cout << " -m <m> Index of first connected component to extract. (default: 0)" << endl; cout << " -n <n> Extract (at most) n components. (default: 1)" << endl; cout << " -[no]compress Write XML VTK with compression enabled/disabled. (default: on)" << endl; cout << " -ascii Write legacy VTK in ASCII format. (default: off)" << endl; cout << " -binary Write legacy VTK in binary format. (default: on)" << endl; PrintStandardOptions(cout); cout << endl; } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { EXPECTS_POSARGS(2); const char *input_name = POSARG(1); const char *output_name = POSARG(2); int m = 0; int n = 1; FileOption fopt = FO_Default; for (ALL_OPTIONS) { if (OPTION("-m")) PARSE_ARGUMENT(m); else if (OPTION("-n")) PARSE_ARGUMENT(n); else HANDLE_POINTSETIO_OPTION(fopt); else HANDLE_STANDARD_OR_UNKNOWN_OPTION(); } vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, fopt); if (verbose) cout << "Analyzing connected components...", cout.flush(); vtkNew<vtkPolyDataConnectivityFilter> lcc; SetVTKInput(lcc, input); lcc->SetExtractionModeToAllRegions(); lcc->Update(); lcc->SetExtractionModeToSpecifiedRegions(); const int npoints = static_cast<int>(input->GetNumberOfPoints()); const int nregions = lcc->GetNumberOfExtractedRegions(); if (verbose) { cout << " done\n"; cout << "No. of input points: " << npoints << "\n"; cout << "No. of connected components: " << nregions << "\n"; cout.flush(); } if (m >= nregions) { FatalError("Start index -m is greater or equal than the total no. of components!"); } if (m + n > nregions) n = nregions - m; if (verbose) cout << "Extracting " << n << " components starting with component " << m+1 << "...", cout.flush(); for (int i = 0; i < nregions; ++i) { lcc->DeleteSpecifiedRegion(i); } for (int i = m; i < m + n; ++i) { lcc->AddSpecifiedRegion(i); } lcc->Update(); if (verbose) cout << " done" << endl; if (verbose) cout << "Cleaning extracted components...", cout.flush(); vtkNew<vtkCleanPolyData> cleaner; SetVTKInput(cleaner, lcc->GetOutput()); cleaner->Update(); if (verbose) cout << " done" << endl; if (!WritePointSet(output_name, cleaner->GetOutput(), fopt)) { FatalError("Failed to write components to file " << output_name); } return 0; } <commit_msg>fix: Sort extract-connected-points components by decreasing size [Applications] (#446)<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/Vtk.h" #include "mirtk/PointSetIO.h" #include "vtkSmartPointer.h" #include "vtkPolyData.h" #include "vtkPolyDataReader.h" #include "vtkPolyDataWriter.h" #include "vtkPolyDataConnectivityFilter.h" #include "vtkCleanPolyData.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << endl; cout << "Usage: " << name << " <input> <output> [options]" << endl; cout << endl; cout << "Description:" << endl; cout << " Extract (largest) connected components of the input point set." << endl; cout << " The connected components are sorted by size, where the largest" << endl; cout << " connected component has index 0." << endl; cout << endl; cout << "Arguments:" << endl; cout << " input Input point set." << endl; cout << " output Output point set." << endl; cout << endl; cout << "Optional arguments:" << endl; cout << " -m <m> Index of first connected component to extract. (default: 0)" << endl; cout << " -n <n> Extract (at most) n components. (default: 1)" << endl; cout << " -[no]compress Write XML VTK with compression enabled/disabled. (default: on)" << endl; cout << " -ascii Write legacy VTK in ASCII format. (default: off)" << endl; cout << " -binary Write legacy VTK in binary format. (default: on)" << endl; PrintStandardOptions(cout); cout << endl; } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { EXPECTS_POSARGS(2); const char *input_name = POSARG(1); const char *output_name = POSARG(2); int m = 0; int n = 1; FileOption fopt = FO_Default; for (ALL_OPTIONS) { if (OPTION("-m")) PARSE_ARGUMENT(m); else if (OPTION("-n")) PARSE_ARGUMENT(n); else HANDLE_POINTSETIO_OPTION(fopt); else HANDLE_STANDARD_OR_UNKNOWN_OPTION(); } vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, fopt); if (verbose) cout << "Analyzing connected components...", cout.flush(); vtkNew<vtkPolyDataConnectivityFilter> lcc; SetVTKInput(lcc, input); lcc->SetExtractionModeToAllRegions(); lcc->Update(); lcc->SetExtractionModeToSpecifiedRegions(); const int npoints = static_cast<int>(input->GetNumberOfPoints()); const int nregions = lcc->GetNumberOfExtractedRegions(); if (verbose) { cout << " done\n"; cout << "No. of input points: " << npoints << "\n"; cout << "No. of connected components: " << nregions << "\n"; cout.flush(); } Array<vtkIdType> sizes(nregions, 0); for (int i = 0; i < nregions; ++i) { sizes[i] = lcc->GetRegionSizes()->GetValue(i); } Array<int> order = DecreasingOrder(sizes); if (m >= nregions) { FatalError("Start index -m is greater or equal than the total no. of components!"); } if (m + n > nregions) n = nregions - m; if (verbose) cout << "Extracting " << n << " components starting with component " << m+1 << "...", cout.flush(); for (int i = 0; i < nregions; ++i) { lcc->DeleteSpecifiedRegion(order[i]); } for (int i = m; i < m + n; ++i) { lcc->AddSpecifiedRegion(order[i]); } lcc->Update(); if (verbose) cout << " done" << endl; if (verbose) cout << "Cleaning extracted components...", cout.flush(); vtkNew<vtkCleanPolyData> cleaner; SetVTKInput(cleaner, lcc->GetOutput()); cleaner->Update(); if (verbose) cout << " done" << endl; if (!WritePointSet(output_name, cleaner->GetOutput(), fopt)) { FatalError("Failed to write components to file " << output_name); } return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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 <OpenNI.h> #include "Viewer.h" int main(int argc, char** argv) { openni::Status rc = openni::STATUS_OK; openni::Device device; openni::VideoStream depth, color; const char* deviceURI = openni::ANY_DEVICE; if (argc > 1) { deviceURI = argv[1]; } rc = openni::OpenNI::initialize(); printf("After initialization:\n%s\n", openni::OpenNI::getExtendedError()); rc = device.open(deviceURI); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Device open failed:\n%s\n", openni::OpenNI::getExtendedError()); openni::OpenNI::shutdown(); return 1; } rc = depth.create(device, openni::SENSOR_DEPTH); if (rc == openni::STATUS_OK) { rc = depth.start(); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Couldn't start depth stream:\n%s\n", openni::OpenNI::getExtendedError()); depth.destroy(); } } else { printf("SimpleViewer: Couldn't find depth stream:\n%s\n", openni::OpenNI::getExtendedError()); } rc = color.create(device, openni::SENSOR_COLOR); if (rc == openni::STATUS_OK) { rc = color.start(); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Couldn't start color stream:\n%s\n", openni::OpenNI::getExtendedError()); color.destroy(); } } else { printf("SimpleViewer: Couldn't find color stream:\n%s\n", openni::OpenNI::getExtendedError()); } if (!depth.isValid() || !color.isValid()) { printf("SimpleViewer: No valid streams. Exiting\n"); openni::OpenNI::shutdown(); return 2; } SampleViewer sampleViewer("Simple Viewer", device, depth, color); rc = sampleViewer.init(argc, argv); if (rc != openni::STATUS_OK) { openni::OpenNI::shutdown(); return 3; } sampleViewer.run(); }<commit_msg>Tweak SimpleViewer demo mimic our use case<commit_after>/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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 <OpenNI.h> #include "Viewer.h" using namespace openni; int main(int argc, char** argv) { openni::Status rc = openni::STATUS_OK; openni::Device device; openni::VideoStream depth, color; const char* deviceURI = openni::ANY_DEVICE; if (argc > 1) { deviceURI = argv[1]; } setenv("OPENNI2_DRIVERS_PATH","./",1); rc = openni::OpenNI::initialize(); printf("After initialization:\n%s\n", openni::OpenNI::getExtendedError()); rc = device.open(deviceURI); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Device open failed:\n%s\n", openni::OpenNI::getExtendedError()); openni::OpenNI::shutdown(); return 1; } rc = depth.create(device, openni::SENSOR_DEPTH); if (rc == openni::STATUS_OK) { printf("SimpleViewer: Couldn't find depth stream:\n%s\n", openni::OpenNI::getExtendedError()); } rc = color.create(device, openni::SENSOR_COLOR); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Couldn't find color stream:\n%s\n", openni::OpenNI::getExtendedError()); } const SensorInfo& depth_info = depth.getSensorInfo(); const Array<VideoMode>& dmodes = depth_info.getSupportedVideoModes(); for( int i=0; i < dmodes.getSize(); i++ ) { VideoMode bla = dmodes[i]; if(dmodes[i].getResolutionX() == 640 && dmodes[i].getResolutionY() == 480 && dmodes[i].getPixelFormat() == PIXEL_FORMAT_DEPTH_1_MM) { rc = depth.setVideoMode(dmodes[i]); if(rc != STATUS_OK) { printf("Failed to set depth video mode"); return -1; } break; } else if(i == dmodes.getSize()-1) { printf("Failed to find a supported depth mode"); return -1; } } const SensorInfo& color_info = color.getSensorInfo(); const Array<VideoMode>& cmodes = color_info.getSupportedVideoModes(); for( int i=0; i < cmodes.getSize(); i++ ) { if(cmodes[i].getResolutionX() == 640 && cmodes[i].getResolutionY() == 480 && cmodes[i].getPixelFormat() == PIXEL_FORMAT_RGB888) { rc = color.setVideoMode(cmodes[i]); if(rc != STATUS_OK) { printf("Failed to set color video mode\n"); return -1; } break; } else if(i == cmodes.getSize()-1) { printf("Failed to find a supported color mode\n"); return -1; } } rc = device.setDepthColorSyncEnabled(TRUE); if(rc != STATUS_OK) { printf("Unable to enable depth-color sync\n"); return -1; } rc = device.setImageRegistrationMode(IMAGE_REGISTRATION_DEPTH_TO_COLOR); if(rc != STATUS_OK) { printf("Failed to set image registration mode\n"); return -1; } rc = depth.start(); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Couldn't start depth stream:\n%s\n", openni::OpenNI::getExtendedError()); depth.destroy(); } rc = color.start(); if (rc != openni::STATUS_OK) { printf("SimpleViewer: Couldn't start color stream:\n%s\n", openni::OpenNI::getExtendedError()); color.destroy(); } if (!depth.isValid() || !color.isValid()) { printf("SimpleViewer: No valid streams. Exiting\n"); openni::OpenNI::shutdown(); return 2; } SampleViewer sampleViewer("Simple Viewer", device, depth, color); rc = sampleViewer.init(argc, argv); if (rc != openni::STATUS_OK) { openni::OpenNI::shutdown(); return 3; } sampleViewer.run(); }<|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @date 2012.02.18 * @brief Implementation of the Text Message Gerät. */ #include <cstring> #include "text_message_geraet.hxx" using namespace std; const NetworkConnection::geraet_num TextMessageInputGeraet::num = NetworkConnection::registerGeraetCreator(&creator, 3); InputNetworkGeraet* TextMessageInputGeraet::creator(NetworkConnection* cxn) { return new TextMessageInputGeraet(cxn->aag); } TextMessageOutputGeraet::TextMessageOutputGeraet(AsyncAckGeraet* aag) : ReliableSender(aag) { } void TextMessageOutputGeraet::put(const char* str) { static byte buff[1024] = {0}; strncpy((char*)(buff+NetworkConnection::headerSize), str, sizeof(buff)-1-NetworkConnection::headerSize); send(buff, strlen(str)+NetworkConnection::headerSize); } TextMessageInputGeraet::TextMessageInputGeraet(AsyncAckGeraet* aag) : AAGReceiver(aag) { } void TextMessageInputGeraet::receiveAccepted(NetworkConnection::seq_t, const byte* dat, unsigned len) throw() { /* Since the packet is not necessarily NUL-terminated (and usually isn't, * since TextMessageOutputGeraet::put() doesn't send the NUL), we need * to copy into a temporary buffer first. * * Initialise the buffer to zero at static load time, then strncpy() up to * one less than its length into the buffer (obviously only copying up to * the length of the packet). * * Then post the buffer to local global chat. */ static char buff[1024] = {0}; if (len > sizeof(buff)-1) len = sizeof(buff)-1; strncpy(buff, (const char*)dat, len); global_chat::postLocal(buff); } <commit_msg>Fix failure to build when debugging disabled.<commit_after>/** * @file * @author Jason Lingle * @date 2012.02.18 * @brief Implementation of the Text Message Gerät. */ #include <cstring> #include "text_message_geraet.hxx" using namespace std; const NetworkConnection::geraet_num TextMessageInputGeraet::num = NetworkConnection::registerGeraetCreator(&creator, 3); InputNetworkGeraet* TextMessageInputGeraet::creator(NetworkConnection* cxn) { return new TextMessageInputGeraet(cxn->aag); } TextMessageOutputGeraet::TextMessageOutputGeraet(AsyncAckGeraet* aag) : ReliableSender(aag) { } void TextMessageOutputGeraet::put(const char* str) noth { static byte buff[1024] = {0}; strncpy((char*)(buff+NetworkConnection::headerSize), str, sizeof(buff)-1-NetworkConnection::headerSize); send(buff, strlen(str)+NetworkConnection::headerSize); } TextMessageInputGeraet::TextMessageInputGeraet(AsyncAckGeraet* aag) : AAGReceiver(aag) { } void TextMessageInputGeraet::receiveAccepted(NetworkConnection::seq_t, const byte* dat, unsigned len) throw() { /* Since the packet is not necessarily NUL-terminated (and usually isn't, * since TextMessageOutputGeraet::put() doesn't send the NUL), we need * to copy into a temporary buffer first. * * Initialise the buffer to zero at static load time, then strncpy() up to * one less than its length into the buffer (obviously only copying up to * the length of the packet). * * Then post the buffer to local global chat. */ static char buff[1024] = {0}; if (len > sizeof(buff)-1) len = sizeof(buff)-1; strncpy(buff, (const char*)dat, len); global_chat::postLocal(buff); } <|endoftext|>
<commit_before>/* Copyright 2016 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 "nnet_language_identifier.h" #include <math.h> #include <algorithm> #include <limits> #include <string> #include "base.h" #include "embedding_network.h" #include "registry.h" #include "script_span/generated_ulscript.h" #include "script_span/getonescriptspan.h" #include "script_span/text_processing.h" #include "cld_3/protos/sentence.pb.h" #include "sentence_features.h" #include "task_context.h" #include "workspace.h" namespace chrome_lang_id { namespace { // Struct for accumulating stats for a language as text subsequences of the same // script are processed. struct LangChunksStats { // Sum of probabilities across subsequences. float prob_sum = 0.0; // Total number of bytes corresponding to the language. int byte_sum = 0; // Number chunks corresponding to the language. int num_chunks = 0; }; // Compares two pairs based on their values. bool OrderBySecondDescending(const std::pair<string, float> &x, const std::pair<string, float> &y) { if (x.second == y.second) { return x.first < y.first; } else { return x.second > y.second; } } } // namespace const int NNetLanguageIdentifier::kMinNumBytesToConsider = 100; const int NNetLanguageIdentifier::kMaxNumBytesToConsider = 512; const int NNetLanguageIdentifier::kMaxNumInputBytesToConsider = 10000; const char NNetLanguageIdentifier::kUnknown[] = "unknown"; const float NNetLanguageIdentifier::kReliabilityThreshold = 0.7f; const float NNetLanguageIdentifier::kReliabilityHrBsThreshold = 0.5f; const string LanguageIdEmbeddingFeatureExtractor::ArgPrefix() const { return "language_identifier"; } NNetLanguageIdentifier::NNetLanguageIdentifier() : NNetLanguageIdentifier(kMinNumBytesToConsider, kMaxNumBytesToConsider) {} static WholeSentenceFeature *cbog_factory() { return new ContinuousBagOfNgramsFunction; } NNetLanguageIdentifier::NNetLanguageIdentifier(int min_num_bytes, int max_num_bytes) : num_languages_(TaskContextParams::GetNumLanguages()), network_(&nn_params_), min_num_bytes_(min_num_bytes), max_num_bytes_(max_num_bytes) { if (WholeSentenceFeature::registry() == nullptr) { // Create registry for our WholeSentenceFeature(s). RegisterableClass<WholeSentenceFeature>::CreateRegistry( "sentence feature function", "WholeSentenceFeature", __FILE__, __LINE__); } // Register our WholeSentenceFeature(s). // Register ContinuousBagOfNgramsFunction feature function. static WholeSentenceFeature::Registry::Registrar cbog_registrar( WholeSentenceFeature::registry(), "continuous-bag-of-ngrams", "ContinuousBagOfNgramsFunction", __FILE__, __LINE__, cbog_factory); // Get the model parameters, set up and initialize the model. TaskContext context; TaskContextParams::ToTaskContext(&context); Setup(&context); Init(&context); } NNetLanguageIdentifier::~NNetLanguageIdentifier() {} void NNetLanguageIdentifier::Setup(TaskContext *context) { feature_extractor_.Setup(context); } void NNetLanguageIdentifier::Init(TaskContext *context) { feature_extractor_.Init(context); feature_extractor_.RequestWorkspaces(&workspace_registry_); } void NNetLanguageIdentifier::GetFeatures( Sentence *sentence, vector<FeatureVector> *features) const { // Feature workspace set. WorkspaceSet workspace; workspace.Reset(workspace_registry_); feature_extractor_.Preprocess(&workspace, sentence); feature_extractor_.ExtractFeatures(workspace, *sentence, features); } // Returns the language name corresponding to the given id. string NNetLanguageIdentifier::GetLanguageName(int language_id) const { CLD3_CHECK(language_id >= 0); CLD3_CHECK(language_id < num_languages_); return TaskContextParams::language_names(language_id); } NNetLanguageIdentifier::Result NNetLanguageIdentifier::FindLanguage( const string &text) { const int num_bytes_to_process = std::min(static_cast<int>(text.size()), max_num_bytes_); const int num_valid_bytes = CLD2::SpanInterchangeValid(text.c_str(), num_bytes_to_process); // Iterate over the input with ScriptScanner to clean up the text (e.g., // removing digits, punctuation, brackets). // TODO(abakalov): Extract the code that does the clean-up out of // ScriptScanner. CLD2::ScriptScanner ss(text.c_str(), num_valid_bytes, /*is_plain_text=*/true); CLD2::LangSpan script_span; std::string cleaned; while (ss.GetOneScriptSpan(&script_span)) { // script_span has spaces at the beginning and the end, so there is no need // for a delimiter. cleaned.append(script_span.text, script_span.text_bytes); } if (static_cast<int>(cleaned.size()) < min_num_bytes_) { return Result(); } // Copy to a vector because a non-const char* will be needed. std::vector<char> text_to_process; for (size_t i = 0; i < cleaned.size(); ++i) { text_to_process.push_back(cleaned[i]); } text_to_process.push_back('\0'); // Remove repetitive chunks or ones containing mostly spaces. const int chunk_size = 0; // Use the default. char *text_start = &text_to_process[0]; const int new_length = CLD2::CheapSqueezeInplace( text_start, text_to_process.size() - 1, chunk_size); if (new_length < min_num_bytes_) { return Result(); } std::string squeezed_text_to_process(text_start, new_length); return FindLanguageOfValidUTF8(squeezed_text_to_process); } NNetLanguageIdentifier::Result NNetLanguageIdentifier::FindLanguageOfValidUTF8( const string &text) { // Create a Sentence storing the input text. Sentence sentence; sentence.set_text(text); // Predict language. // TODO(salcianu): reuse vector<FeatureVector>. vector<FeatureVector> features(feature_extractor_.NumEmbeddings()); GetFeatures(&sentence, &features); EmbeddingNetwork::Vector scores; network_.ComputeFinalScores(features, &scores); int prediction_id = -1; float max_val = -std::numeric_limits<float>::infinity(); for (size_t i = 0; i < scores.size(); ++i) { if (scores[i] > max_val) { prediction_id = i; max_val = scores[i]; } } // Compute probability. Result result; float diff_sum = 0.0; for (size_t i = 0; i < scores.size(); ++i) { diff_sum += exp(scores[i] - max_val); } const float log_sum_exp = max_val + log(diff_sum); result.probability = exp(max_val - log_sum_exp); result.language = GetLanguageName(prediction_id); result.is_reliable = (result.probability >= kReliabilityThreshold); result.proportion = 1.0; return result; } std::vector<NNetLanguageIdentifier::Result> NNetLanguageIdentifier::FindTopNMostFreqLangs(const string &text, int num_langs) { std::vector<Result> results; // Truncate the input text if it is too long and find the span containing // interchange-valid UTF8. const int num_valid_bytes = CLD2::SpanInterchangeValid( text.c_str(), std::min(kMaxNumInputBytesToConsider, static_cast<int>(text.size()))); if (num_valid_bytes == 0) { while (num_langs-- > 0) { results.emplace_back(); } return results; } // Process each subsequence of the same script. CLD2::ScriptScanner ss(text.c_str(), num_valid_bytes, /*is_plain_text=*/true); CLD2::LangSpan script_span; std::unordered_map<string, LangChunksStats> lang_stats; int total_num_bytes = 0; Result result; string language; int chunk_size = 0; // Use the default. while (ss.GetOneScriptSpan(&script_span)) { const int num_original_span_bytes = script_span.text_bytes; // Remove repetitive chunks or ones containing mostly spaces. const int new_length = CLD2::CheapSqueezeInplace( script_span.text, script_span.text_bytes, chunk_size); script_span.text_bytes = new_length; if (script_span.text_bytes < min_num_bytes_) { continue; } total_num_bytes += num_original_span_bytes; // If the text is longer than max_num_bytes_, find the middle snippet of // length max_num_bytes_. std::string span_text; if (script_span.text_bytes > max_num_bytes_) { // Offset of the middle snippet. Using SpanInterchangeValid to ensure that // we are not splitting a character in two. This function is used on the // following line for the same reason. const int offset = CLD2::SpanInterchangeValid( script_span.text, (script_span.text_bytes - max_num_bytes_) / 2); const int num_valid_snippet_bytes = CLD2::SpanInterchangeValid(script_span.text + offset, max_num_bytes_); const std::string middle_snippet(script_span.text + offset, num_valid_snippet_bytes); span_text = middle_snippet; } else { const std::string snippet(script_span.text, script_span.text_bytes); span_text = snippet; } result = FindLanguageOfValidUTF8(span_text); language = result.language; lang_stats[language].byte_sum += num_original_span_bytes; lang_stats[language].prob_sum += result.probability * num_original_span_bytes; lang_stats[language].num_chunks++; } // Sort the languages based on the number of bytes associated with them. // TODO(abakalov): Consider alternative possibly more efficient portable // approaches for finding the top N languages. Given that on average, there // aren't that many languages in the input, it's likely that the benefits will // be negligible (if any). std::vector<std::pair<string, float>> langs_and_byte_counts; for (const auto &entry : lang_stats) { langs_and_byte_counts.emplace_back(entry.first, entry.second.byte_sum); } std::sort(langs_and_byte_counts.begin(), langs_and_byte_counts.end(), OrderBySecondDescending); const float byte_sum = static_cast<float>(total_num_bytes); const int num_langs_to_save = std::min(num_langs, static_cast<int>(langs_and_byte_counts.size())); for (int indx = 0; indx < num_langs_to_save; ++indx) { Result result; const string &language = langs_and_byte_counts.at(indx).first; const LangChunksStats &stats = lang_stats.at(language); result.language = language; result.probability = stats.prob_sum / stats.byte_sum; result.proportion = stats.byte_sum / byte_sum; if (language == "hr" || language == "bs") { result.is_reliable = (result.probability >= kReliabilityHrBsThreshold); } else { result.is_reliable = (result.probability >= kReliabilityThreshold); } results.push_back(result); } int padding_size = num_langs - langs_and_byte_counts.size(); while (padding_size-- > 0) { results.emplace_back(); } return results; } } // namespace chrome_lang_id <commit_msg>Increasing the threshold for min number of bytes<commit_after>/* Copyright 2016 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 "nnet_language_identifier.h" #include <math.h> #include <algorithm> #include <limits> #include <string> #include "base.h" #include "embedding_network.h" #include "registry.h" #include "script_span/generated_ulscript.h" #include "script_span/getonescriptspan.h" #include "script_span/text_processing.h" #include "cld_3/protos/sentence.pb.h" #include "sentence_features.h" #include "task_context.h" #include "workspace.h" namespace chrome_lang_id { namespace { // Struct for accumulating stats for a language as text subsequences of the same // script are processed. struct LangChunksStats { // Sum of probabilities across subsequences. float prob_sum = 0.0; // Total number of bytes corresponding to the language. int byte_sum = 0; // Number chunks corresponding to the language. int num_chunks = 0; }; // Compares two pairs based on their values. bool OrderBySecondDescending(const std::pair<string, float> &x, const std::pair<string, float> &y) { if (x.second == y.second) { return x.first < y.first; } else { return x.second > y.second; } } } // namespace const int NNetLanguageIdentifier::kMinNumBytesToConsider = 150; const int NNetLanguageIdentifier::kMaxNumBytesToConsider = 512; const int NNetLanguageIdentifier::kMaxNumInputBytesToConsider = 10000; const char NNetLanguageIdentifier::kUnknown[] = "unknown"; const float NNetLanguageIdentifier::kReliabilityThreshold = 0.7f; const float NNetLanguageIdentifier::kReliabilityHrBsThreshold = 0.5f; const string LanguageIdEmbeddingFeatureExtractor::ArgPrefix() const { return "language_identifier"; } NNetLanguageIdentifier::NNetLanguageIdentifier() : NNetLanguageIdentifier(kMinNumBytesToConsider, kMaxNumBytesToConsider) {} static WholeSentenceFeature *cbog_factory() { return new ContinuousBagOfNgramsFunction; } NNetLanguageIdentifier::NNetLanguageIdentifier(int min_num_bytes, int max_num_bytes) : num_languages_(TaskContextParams::GetNumLanguages()), network_(&nn_params_), min_num_bytes_(min_num_bytes), max_num_bytes_(max_num_bytes) { if (WholeSentenceFeature::registry() == nullptr) { // Create registry for our WholeSentenceFeature(s). RegisterableClass<WholeSentenceFeature>::CreateRegistry( "sentence feature function", "WholeSentenceFeature", __FILE__, __LINE__); } // Register our WholeSentenceFeature(s). // Register ContinuousBagOfNgramsFunction feature function. static WholeSentenceFeature::Registry::Registrar cbog_registrar( WholeSentenceFeature::registry(), "continuous-bag-of-ngrams", "ContinuousBagOfNgramsFunction", __FILE__, __LINE__, cbog_factory); // Get the model parameters, set up and initialize the model. TaskContext context; TaskContextParams::ToTaskContext(&context); Setup(&context); Init(&context); } NNetLanguageIdentifier::~NNetLanguageIdentifier() {} void NNetLanguageIdentifier::Setup(TaskContext *context) { feature_extractor_.Setup(context); } void NNetLanguageIdentifier::Init(TaskContext *context) { feature_extractor_.Init(context); feature_extractor_.RequestWorkspaces(&workspace_registry_); } void NNetLanguageIdentifier::GetFeatures( Sentence *sentence, vector<FeatureVector> *features) const { // Feature workspace set. WorkspaceSet workspace; workspace.Reset(workspace_registry_); feature_extractor_.Preprocess(&workspace, sentence); feature_extractor_.ExtractFeatures(workspace, *sentence, features); } // Returns the language name corresponding to the given id. string NNetLanguageIdentifier::GetLanguageName(int language_id) const { CLD3_CHECK(language_id >= 0); CLD3_CHECK(language_id < num_languages_); return TaskContextParams::language_names(language_id); } NNetLanguageIdentifier::Result NNetLanguageIdentifier::FindLanguage( const string &text) { const int num_bytes_to_process = std::min(static_cast<int>(text.size()), max_num_bytes_); const int num_valid_bytes = CLD2::SpanInterchangeValid(text.c_str(), num_bytes_to_process); // Iterate over the input with ScriptScanner to clean up the text (e.g., // removing digits, punctuation, brackets). // TODO(abakalov): Extract the code that does the clean-up out of // ScriptScanner. CLD2::ScriptScanner ss(text.c_str(), num_valid_bytes, /*is_plain_text=*/true); CLD2::LangSpan script_span; std::string cleaned; while (ss.GetOneScriptSpan(&script_span)) { // script_span has spaces at the beginning and the end, so there is no need // for a delimiter. cleaned.append(script_span.text, script_span.text_bytes); } if (static_cast<int>(cleaned.size()) < min_num_bytes_) { return Result(); } // Copy to a vector because a non-const char* will be needed. std::vector<char> text_to_process; for (size_t i = 0; i < cleaned.size(); ++i) { text_to_process.push_back(cleaned[i]); } text_to_process.push_back('\0'); // Remove repetitive chunks or ones containing mostly spaces. const int chunk_size = 0; // Use the default. char *text_start = &text_to_process[0]; const int new_length = CLD2::CheapSqueezeInplace( text_start, text_to_process.size() - 1, chunk_size); if (new_length < min_num_bytes_) { return Result(); } std::string squeezed_text_to_process(text_start, new_length); return FindLanguageOfValidUTF8(squeezed_text_to_process); } NNetLanguageIdentifier::Result NNetLanguageIdentifier::FindLanguageOfValidUTF8( const string &text) { // Create a Sentence storing the input text. Sentence sentence; sentence.set_text(text); // Predict language. // TODO(salcianu): reuse vector<FeatureVector>. vector<FeatureVector> features(feature_extractor_.NumEmbeddings()); GetFeatures(&sentence, &features); EmbeddingNetwork::Vector scores; network_.ComputeFinalScores(features, &scores); int prediction_id = -1; float max_val = -std::numeric_limits<float>::infinity(); for (size_t i = 0; i < scores.size(); ++i) { if (scores[i] > max_val) { prediction_id = i; max_val = scores[i]; } } // Compute probability. Result result; float diff_sum = 0.0; for (size_t i = 0; i < scores.size(); ++i) { diff_sum += exp(scores[i] - max_val); } const float log_sum_exp = max_val + log(diff_sum); result.probability = exp(max_val - log_sum_exp); result.language = GetLanguageName(prediction_id); result.is_reliable = (result.probability >= kReliabilityThreshold); result.proportion = 1.0; return result; } std::vector<NNetLanguageIdentifier::Result> NNetLanguageIdentifier::FindTopNMostFreqLangs(const string &text, int num_langs) { std::vector<Result> results; // Truncate the input text if it is too long and find the span containing // interchange-valid UTF8. const int num_valid_bytes = CLD2::SpanInterchangeValid( text.c_str(), std::min(kMaxNumInputBytesToConsider, static_cast<int>(text.size()))); if (num_valid_bytes == 0) { while (num_langs-- > 0) { results.emplace_back(); } return results; } // Process each subsequence of the same script. CLD2::ScriptScanner ss(text.c_str(), num_valid_bytes, /*is_plain_text=*/true); CLD2::LangSpan script_span; std::unordered_map<string, LangChunksStats> lang_stats; int total_num_bytes = 0; Result result; string language; int chunk_size = 0; // Use the default. while (ss.GetOneScriptSpan(&script_span)) { const int num_original_span_bytes = script_span.text_bytes; // Remove repetitive chunks or ones containing mostly spaces. const int new_length = CLD2::CheapSqueezeInplace( script_span.text, script_span.text_bytes, chunk_size); script_span.text_bytes = new_length; if (script_span.text_bytes < min_num_bytes_) { continue; } total_num_bytes += num_original_span_bytes; // If the text is longer than max_num_bytes_, find the middle snippet of // length max_num_bytes_. std::string span_text; if (script_span.text_bytes > max_num_bytes_) { // Offset of the middle snippet. Using SpanInterchangeValid to ensure that // we are not splitting a character in two. This function is used on the // following line for the same reason. const int offset = CLD2::SpanInterchangeValid( script_span.text, (script_span.text_bytes - max_num_bytes_) / 2); const int num_valid_snippet_bytes = CLD2::SpanInterchangeValid(script_span.text + offset, max_num_bytes_); const std::string middle_snippet(script_span.text + offset, num_valid_snippet_bytes); span_text = middle_snippet; } else { const std::string snippet(script_span.text, script_span.text_bytes); span_text = snippet; } result = FindLanguageOfValidUTF8(span_text); language = result.language; lang_stats[language].byte_sum += num_original_span_bytes; lang_stats[language].prob_sum += result.probability * num_original_span_bytes; lang_stats[language].num_chunks++; } // Sort the languages based on the number of bytes associated with them. // TODO(abakalov): Consider alternative possibly more efficient portable // approaches for finding the top N languages. Given that on average, there // aren't that many languages in the input, it's likely that the benefits will // be negligible (if any). std::vector<std::pair<string, float>> langs_and_byte_counts; for (const auto &entry : lang_stats) { langs_and_byte_counts.emplace_back(entry.first, entry.second.byte_sum); } std::sort(langs_and_byte_counts.begin(), langs_and_byte_counts.end(), OrderBySecondDescending); const float byte_sum = static_cast<float>(total_num_bytes); const int num_langs_to_save = std::min(num_langs, static_cast<int>(langs_and_byte_counts.size())); for (int indx = 0; indx < num_langs_to_save; ++indx) { Result result; const string &language = langs_and_byte_counts.at(indx).first; const LangChunksStats &stats = lang_stats.at(language); result.language = language; result.probability = stats.prob_sum / stats.byte_sum; result.proportion = stats.byte_sum / byte_sum; if (language == "hr" || language == "bs") { result.is_reliable = (result.probability >= kReliabilityHrBsThreshold); } else { result.is_reliable = (result.probability >= kReliabilityThreshold); } results.push_back(result); } int padding_size = num_langs - langs_and_byte_counts.size(); while (padding_size-- > 0) { results.emplace_back(); } return results; } } // namespace chrome_lang_id <|endoftext|>
<commit_before>extern "C" { #include <sys/types.h> #include <stdio.h> #include <jpeglib.h> } #include <setjmp.h> #include <graphics/format/JPEG.h> #include <system/System.h> namespace lime { struct ErrorData { struct jpeg_error_mgr base; jmp_buf on_error; }; static void OnOutput (j_common_ptr cinfo) {} static void OnError (j_common_ptr cinfo) { ErrorData * err = (ErrorData *)cinfo->err; longjmp (err->on_error, 1); } struct MySrcManager { MySrcManager (const JOCTET *inData, int inLen) : mData (inData), mLen (inLen) { pub.init_source = my_init_source; pub.fill_input_buffer = my_fill_input_buffer; pub.skip_input_data = my_skip_input_data; pub.resync_to_restart = my_resync_to_restart; pub.term_source = my_term_source; pub.next_input_byte = 0; pub.bytes_in_buffer = 0; mUsed = false; mEOI[0] = 0xff; mEOI[1] = JPEG_EOI; } struct jpeg_source_mgr pub; /* public fields */ const JOCTET * mData; size_t mLen; bool mUsed; unsigned char mEOI[2]; static void my_init_source (j_decompress_ptr cinfo) { MySrcManager *man = (MySrcManager *)cinfo->src; man->mUsed = false; } static boolean my_fill_input_buffer (j_decompress_ptr cinfo) { MySrcManager *man = (MySrcManager *)cinfo->src; if (man->mUsed) { man->pub.next_input_byte = man->mEOI; man->pub.bytes_in_buffer = 2; } else { man->pub.next_input_byte = man->mData; man->pub.bytes_in_buffer = man->mLen; man->mUsed = true; } return true; } static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes) { MySrcManager *man = (MySrcManager *)cinfo->src; man->pub.next_input_byte += num_bytes; man->pub.bytes_in_buffer -= num_bytes; // was < 0 and was always false PJK 16JUN12 if (man->pub.bytes_in_buffer == 0) { man->pub.next_input_byte = man->mEOI; man->pub.bytes_in_buffer = 2; } } static boolean my_resync_to_restart (j_decompress_ptr cinfo, int desired) { MySrcManager *man = (MySrcManager *)cinfo->src; man->mUsed = false; return true; } static void my_term_source (j_decompress_ptr cinfo) {} }; struct MyDestManager { enum { BUF_SIZE = 4096 }; struct jpeg_destination_mgr pub; /* public fields */ QuickVec<unsigned char> mOutput; unsigned char mTmpBuf[BUF_SIZE]; MyDestManager () { pub.init_destination = init_buffer; pub.empty_output_buffer = copy_buffer; pub.term_destination = term_buffer; pub.next_output_byte = mTmpBuf; pub.free_in_buffer = BUF_SIZE; } void CopyBuffer () { mOutput.append (mTmpBuf, BUF_SIZE); pub.next_output_byte = mTmpBuf; pub.free_in_buffer = BUF_SIZE; } void TermBuffer () { mOutput.append (mTmpBuf, BUF_SIZE - pub.free_in_buffer); } static void init_buffer (jpeg_compress_struct* cinfo) {} static boolean copy_buffer (jpeg_compress_struct* cinfo) { MyDestManager *man = (MyDestManager *)cinfo->dest; man->CopyBuffer (); return TRUE; } static void term_buffer (jpeg_compress_struct* cinfo) { MyDestManager *man = (MyDestManager *)cinfo->dest; man->TermBuffer (); } }; bool JPEG::Decode (Resource *resource, ImageBuffer* imageBuffer, bool decodeData) { struct jpeg_decompress_struct cinfo; //struct jpeg_error_mgr jerr; //cinfo.err = jpeg_std_error (&jerr); struct ErrorData jpegError; cinfo.err = jpeg_std_error (&jpegError.base); jpegError.base.error_exit = OnError; jpegError.base.output_message = OnOutput; FILE_HANDLE *file = NULL; if (resource->path) { file = lime::fopen (resource->path, "rb"); if (!file) { return false; } } if (setjmp (jpegError.on_error)) { if (file) { lime::fclose (file); } jpeg_destroy_decompress (&cinfo); return false; } jpeg_create_decompress (&cinfo); if (file) { if (file->isFile ()) { jpeg_stdio_src (&cinfo, file->getFile ()); } else { Bytes data = Bytes (resource->path); MySrcManager manager (data.Data (), data.Length ()); cinfo.src = &manager.pub; } } else { MySrcManager manager (resource->data->Data (), resource->data->Length ()); cinfo.src = &manager.pub; } bool decoded = false; if (jpeg_read_header (&cinfo, TRUE) == JPEG_HEADER_OK) { cinfo.out_color_space = JCS_RGB; if (decodeData) { jpeg_start_decompress (&cinfo); int components = cinfo.num_components; imageBuffer->Resize (cinfo.output_width, cinfo.output_height, 32); unsigned char *bytes = imageBuffer->data->Data (); unsigned char *scanline = new unsigned char [imageBuffer->width * imageBuffer->height * components]; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines (&cinfo, &scanline, 1); // convert 24-bit scanline to 32-bit const unsigned char *line = scanline; const unsigned char *const end = line + imageBuffer->width * components; while (line != end) { *bytes++ = *line++; *bytes++ = *line++; *bytes++ = *line++; *bytes++ = 0xFF; } } delete[] scanline; jpeg_finish_decompress (&cinfo); } else { imageBuffer->width = cinfo.image_width; imageBuffer->height = cinfo.image_height; } decoded = true; } if (file) { lime::fclose (file); } jpeg_destroy_decompress (&cinfo); return decoded; } bool JPEG::Encode (ImageBuffer *imageBuffer, Bytes *bytes, int quality) { struct jpeg_compress_struct cinfo; struct ErrorData jpegError; cinfo.err = jpeg_std_error (&jpegError.base); jpegError.base.error_exit = OnError; jpegError.base.output_message = OnOutput; MyDestManager dest; int w = imageBuffer->width; int h = imageBuffer->height; QuickVec<unsigned char> row_buf (w * 3); jpeg_create_compress (&cinfo); if (setjmp (jpegError.on_error)) { jpeg_destroy_compress (&cinfo); return false; } cinfo.dest = (jpeg_destination_mgr *)&dest; cinfo.image_width = w; cinfo.image_height = h; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults (&cinfo); jpeg_set_quality (&cinfo, quality, true); jpeg_start_compress (&cinfo, true); JSAMPROW row_pointer = &row_buf[0]; unsigned char* imageData = imageBuffer->data->Data(); int stride = imageBuffer->Stride (); while (cinfo.next_scanline < cinfo.image_height) { const unsigned char *src = (const unsigned char *)(imageData + (stride * cinfo.next_scanline)); unsigned char *dest = &row_buf[0]; for(int x = 0; x < w; x++) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest += 3; src += 4; } jpeg_write_scanlines (&cinfo, &row_pointer, 1); } jpeg_finish_compress (&cinfo); bytes->Set (dest.mOutput); return true; } }<commit_msg>fix loading of greyscale JPEGs<commit_after>extern "C" { #include <sys/types.h> #include <stdio.h> #include <jpeglib.h> } #include <setjmp.h> #include <graphics/format/JPEG.h> #include <system/System.h> namespace lime { struct ErrorData { struct jpeg_error_mgr base; jmp_buf on_error; }; static void OnOutput (j_common_ptr cinfo) {} static void OnError (j_common_ptr cinfo) { ErrorData * err = (ErrorData *)cinfo->err; longjmp (err->on_error, 1); } struct MySrcManager { MySrcManager (const JOCTET *inData, int inLen) : mData (inData), mLen (inLen) { pub.init_source = my_init_source; pub.fill_input_buffer = my_fill_input_buffer; pub.skip_input_data = my_skip_input_data; pub.resync_to_restart = my_resync_to_restart; pub.term_source = my_term_source; pub.next_input_byte = 0; pub.bytes_in_buffer = 0; mUsed = false; mEOI[0] = 0xff; mEOI[1] = JPEG_EOI; } struct jpeg_source_mgr pub; /* public fields */ const JOCTET * mData; size_t mLen; bool mUsed; unsigned char mEOI[2]; static void my_init_source (j_decompress_ptr cinfo) { MySrcManager *man = (MySrcManager *)cinfo->src; man->mUsed = false; } static boolean my_fill_input_buffer (j_decompress_ptr cinfo) { MySrcManager *man = (MySrcManager *)cinfo->src; if (man->mUsed) { man->pub.next_input_byte = man->mEOI; man->pub.bytes_in_buffer = 2; } else { man->pub.next_input_byte = man->mData; man->pub.bytes_in_buffer = man->mLen; man->mUsed = true; } return true; } static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes) { MySrcManager *man = (MySrcManager *)cinfo->src; man->pub.next_input_byte += num_bytes; man->pub.bytes_in_buffer -= num_bytes; // was < 0 and was always false PJK 16JUN12 if (man->pub.bytes_in_buffer == 0) { man->pub.next_input_byte = man->mEOI; man->pub.bytes_in_buffer = 2; } } static boolean my_resync_to_restart (j_decompress_ptr cinfo, int desired) { MySrcManager *man = (MySrcManager *)cinfo->src; man->mUsed = false; return true; } static void my_term_source (j_decompress_ptr cinfo) {} }; struct MyDestManager { enum { BUF_SIZE = 4096 }; struct jpeg_destination_mgr pub; /* public fields */ QuickVec<unsigned char> mOutput; unsigned char mTmpBuf[BUF_SIZE]; MyDestManager () { pub.init_destination = init_buffer; pub.empty_output_buffer = copy_buffer; pub.term_destination = term_buffer; pub.next_output_byte = mTmpBuf; pub.free_in_buffer = BUF_SIZE; } void CopyBuffer () { mOutput.append (mTmpBuf, BUF_SIZE); pub.next_output_byte = mTmpBuf; pub.free_in_buffer = BUF_SIZE; } void TermBuffer () { mOutput.append (mTmpBuf, BUF_SIZE - pub.free_in_buffer); } static void init_buffer (jpeg_compress_struct* cinfo) {} static boolean copy_buffer (jpeg_compress_struct* cinfo) { MyDestManager *man = (MyDestManager *)cinfo->dest; man->CopyBuffer (); return TRUE; } static void term_buffer (jpeg_compress_struct* cinfo) { MyDestManager *man = (MyDestManager *)cinfo->dest; man->TermBuffer (); } }; bool JPEG::Decode (Resource *resource, ImageBuffer* imageBuffer, bool decodeData) { struct jpeg_decompress_struct cinfo; //struct jpeg_error_mgr jerr; //cinfo.err = jpeg_std_error (&jerr); struct ErrorData jpegError; cinfo.err = jpeg_std_error (&jpegError.base); jpegError.base.error_exit = OnError; jpegError.base.output_message = OnOutput; FILE_HANDLE *file = NULL; if (resource->path) { file = lime::fopen (resource->path, "rb"); if (!file) { return false; } } if (setjmp (jpegError.on_error)) { if (file) { lime::fclose (file); } jpeg_destroy_decompress (&cinfo); return false; } jpeg_create_decompress (&cinfo); if (file) { if (file->isFile ()) { jpeg_stdio_src (&cinfo, file->getFile ()); } else { Bytes data = Bytes (resource->path); MySrcManager manager (data.Data (), data.Length ()); cinfo.src = &manager.pub; } } else { MySrcManager manager (resource->data->Data (), resource->data->Length ()); cinfo.src = &manager.pub; } bool decoded = false; if (jpeg_read_header (&cinfo, TRUE) == JPEG_HEADER_OK) { cinfo.out_color_space = JCS_RGB; if (decodeData) { jpeg_start_decompress (&cinfo); int components = cinfo.output_components; imageBuffer->Resize (cinfo.output_width, cinfo.output_height, 32); unsigned char *bytes = imageBuffer->data->Data (); unsigned char *scanline = new unsigned char [imageBuffer->width * components]; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines (&cinfo, &scanline, 1); // convert 24-bit scanline to 32-bit const unsigned char *line = scanline; const unsigned char *const end = line + imageBuffer->width * components; while (line < end) { *bytes++ = *line++; *bytes++ = *line++; *bytes++ = *line++; *bytes++ = 0xFF; } } delete[] scanline; jpeg_finish_decompress (&cinfo); } else { imageBuffer->width = cinfo.image_width; imageBuffer->height = cinfo.image_height; } decoded = true; } if (file) { lime::fclose (file); } jpeg_destroy_decompress (&cinfo); return decoded; } bool JPEG::Encode (ImageBuffer *imageBuffer, Bytes *bytes, int quality) { struct jpeg_compress_struct cinfo; struct ErrorData jpegError; cinfo.err = jpeg_std_error (&jpegError.base); jpegError.base.error_exit = OnError; jpegError.base.output_message = OnOutput; MyDestManager dest; int w = imageBuffer->width; int h = imageBuffer->height; QuickVec<unsigned char> row_buf (w * 3); jpeg_create_compress (&cinfo); if (setjmp (jpegError.on_error)) { jpeg_destroy_compress (&cinfo); return false; } cinfo.dest = (jpeg_destination_mgr *)&dest; cinfo.image_width = w; cinfo.image_height = h; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults (&cinfo); jpeg_set_quality (&cinfo, quality, true); jpeg_start_compress (&cinfo, true); JSAMPROW row_pointer = &row_buf[0]; unsigned char* imageData = imageBuffer->data->Data(); int stride = imageBuffer->Stride (); while (cinfo.next_scanline < cinfo.image_height) { const unsigned char *src = (const unsigned char *)(imageData + (stride * cinfo.next_scanline)); unsigned char *dest = &row_buf[0]; for(int x = 0; x < w; x++) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest += 3; src += 4; } jpeg_write_scanlines (&cinfo, &row_pointer, 1); } jpeg_finish_compress (&cinfo); bytes->Set (dest.mOutput); return true; } } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cc/position.h" #include <set> #include <string> #include <utility> #include <vector> #include "absl/strings/ascii.h" #include "cc/constants.h" #include "cc/test_utils.h" #include "gtest/gtest.h" namespace minigo { namespace { TEST(BoardVisitorTest, TestEpochRollover) { for (int j = 0; j <= 256; ++j) { BoardVisitor bv; for (int i = 0; i < j; ++i) { bv.Begin(); } for (int i = 0; i < kN * kN; ++i) { auto c = Coord(i); ASSERT_TRUE(bv.Visit(c)); ASSERT_EQ(c, bv.Next()); ASSERT_FALSE(bv.Visit(c)); } } } TEST(GroupVisitorTest, TestEpochRollover) { for (int j = 0; j <= 256; ++j) { GroupVisitor gv; for (int i = 0; i < j; ++i) { gv.Begin(); } for (int i = 0; i < Group::kMaxNumGroups; ++i) { auto g = GroupId(i); ASSERT_TRUE(gv.Visit(g)); ASSERT_FALSE(gv.Visit(g)); } } } TEST(PositionTest, TestIsKoish) { auto board = TestablePosition(R"( .X.O.O.O. X...O...O ...O..... X.O.O...O .X.O...X. X.O..X... .X.OX.X.. X.O..X..O XX.....X.)"); std::set<std::string> expected_black_kos = {"A9", "A5", "A3", "F3"}; std::set<std::string> expected_white_kos = {"E9", "J9", "D6"}; for (int row = 0; row < kN; ++row) { for (int col = 0; col < kN; ++col) { auto c = Coord(row, col).ToKgs(); Color expected; Color actual = board.IsKoish(c); if (expected_white_kos.find(c) != expected_white_kos.end()) { expected = Color::kWhite; } else if (expected_black_kos.find(c) != expected_black_kos.end()) { expected = Color::kBlack; } else { expected = Color::kEmpty; } EXPECT_EQ(expected, actual) << c; } } } TEST(PositionTest, TestMergeGroups1) { auto board = TestablePosition(R"( .X. X.X .X.)"); EXPECT_EQ(3, board.GroupAt("B9").num_liberties); EXPECT_EQ(3, board.GroupAt("A8").num_liberties); EXPECT_EQ(4, board.GroupAt("C8").num_liberties); EXPECT_EQ(4, board.GroupAt("B7").num_liberties); board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( .X. XXX .X.)"), board.ToSimpleString()); auto group = board.GroupAt("B8"); EXPECT_EQ(5, group.size); EXPECT_EQ(6, group.num_liberties); } TEST(PositionTest, TestMergeGroups2) { auto board = TestablePosition(R"( ......... ......... ......... ......... ......... ..O..O... ..O..O... ..O..O... ..OOO....)"); EXPECT_EQ(10, board.GroupAt("C1").num_liberties); EXPECT_EQ(8, board.GroupAt("F2").num_liberties); board.PlayMove("F1", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( ......... ......... ......... ......... ......... ..O..O... ..O..O... ..O..O... ..OOOO...)"), board.ToSimpleString()); auto group = board.GroupAt("F4"); EXPECT_EQ(10, group.size); EXPECT_EQ(16, group.num_liberties); } TEST(PositionTest, TestCaptureStone) { auto board = TestablePosition(R"( ......... ......... ......... ......... ......... ......... .......O. ......OX. .......O.)"); board.PlayMove("J2", Color::kWhite); std::array<int, 2> expected_captures = {0, 1}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ......... ......... ......... ......... ......... ......... .......O. ......O.O .......O.)"), board.ToSimpleString()); } TEST(PositionTest, TestCaptureMany1) { auto board = TestablePosition(R"( ..... ..... ..XX. .XOO. ..XX.)"); EXPECT_EQ(4, board.GroupAt("C7").num_liberties); EXPECT_EQ(3, board.GroupAt("B6").num_liberties); EXPECT_EQ(1, board.GroupAt("C6").num_liberties); EXPECT_EQ(4, board.GroupAt("D5").num_liberties); board.PlayMove("E6", Color::kBlack); std::array<int, 2> expected_captures = {2, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ..... ..... ..XX. .X..X ..XX.)"), board.ToSimpleString()); EXPECT_EQ(6, board.GroupAt("C7").num_liberties); EXPECT_EQ(4, board.GroupAt("B6").num_liberties); EXPECT_EQ(4, board.GroupAt("E6").num_liberties); EXPECT_EQ(6, board.GroupAt("D5").num_liberties); } TEST(PositionTest, TestCaptureMany2) { auto board = TestablePosition(R"( ..X.. .XOX. XO.OX .XOX. ..X..)"); board.PlayMove("C7", Color::kBlack); std::array<int, 2> expected_captures = {4, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ..X.. .X.X. X.X.X .X.X. ..X..)"), board.ToSimpleString()); EXPECT_EQ(3, board.GroupAt("C9").num_liberties); EXPECT_EQ(4, board.GroupAt("B8").num_liberties); EXPECT_EQ(4, board.GroupAt("D8").num_liberties); EXPECT_EQ(3, board.GroupAt("A7").num_liberties); EXPECT_EQ(4, board.GroupAt("B6").num_liberties); EXPECT_EQ(4, board.GroupAt("D6").num_liberties); EXPECT_EQ(4, board.GroupAt("C5").num_liberties); } TEST(PositionTest, TestCaptureMultipleGroups) { auto board = TestablePosition(R"( .OX OXX XX.)"); board.PlayMove("A9", Color::kBlack); std::array<int, 2> expected_captures = {2, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( X.X .XX XX.)"), board.ToSimpleString()); EXPECT_EQ(2, board.GroupAt("A9").num_liberties); EXPECT_EQ(7, board.GroupAt("B8").num_liberties); } TEST(PositionTest, TestSameFriendlyGroupNeighboringTwice) { auto board = TestablePosition(R"( OO O.)"); board.PlayMove("B8", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( OO OO)"), board.ToSimpleString()); auto group = board.GroupAt("A9"); EXPECT_EQ(4, group.size); EXPECT_EQ(4, group.num_liberties); } TEST(PositionTest, TestSameOpponentGroupNeighboringTwice) { auto board = TestablePosition(R"( OO O.)"); board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( OO OX)"), board.ToSimpleString()); auto white_group = board.GroupAt("A9"); EXPECT_EQ(3, white_group.size); EXPECT_EQ(2, white_group.num_liberties); auto black_group = board.GroupAt("B8"); EXPECT_EQ(1, black_group.size); EXPECT_EQ(2, black_group.num_liberties); } TEST(PositionTest, IsMoveSuicidal) { auto board = TestablePosition(R"( ...O.O... ....O.... XO.....O. OXO...OXO O.XO.OX.O OXOOOOOOX XOOX.XO.. ...OOOXXO .....XOO.)"); std::vector<std::string> suicidal_moves = {"E9", "H5", "E3"}; for (const auto& c : suicidal_moves) { EXPECT_TRUE(board.IsMoveSuicidal(c, Color::kBlack)); } std::vector<std::string> nonsuicidal_moves = {"B5", "J1", "A9"}; for (const auto& c : nonsuicidal_moves) { EXPECT_FALSE(board.IsMoveSuicidal(c, Color::kBlack)); } } // Tests ko tracking. TEST(PositionTest, TestKoTracking) { auto board = TestablePosition(R"( XOXO..... .........)"); // Capturing a stone in a non-koish coord shouldn't create a ko. board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( X.XO..... .X.......)"), board.ToSimpleString()); // Capturing a stone in a koish coord should create a ko. board.PlayMove("C8", Color::kWhite); board.PlayMove("B9", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( XO*O..... .XO......)"), board.ToSimpleString()); // Playing a move should clear the ko. board.PlayMove("J9", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( XO.O....X .XO......)"), board.ToSimpleString()); // Test ko when capturing white as well. board.PlayMove("C9", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( X*XO....X .XO......)"), board.ToSimpleString()); // Playing a move should clear the ko. board.PlayMove("H9", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( X.XO...OX .XO......)"), board.ToSimpleString()); } TEST(PositionTest, TestSeki) { auto board = TestablePosition(R"( O....XXXX .....XOOO .....XOX. .....XO.X .....XOOX ......XOO ......XXX)"); // All empty squares are neutral points and black has 5 more stones than // white. EXPECT_EQ(5, board.CalculateScore(0)); } TEST(PositionTest, TestScoring) { EXPECT_EQ(0, TestablePosition("").CalculateScore(0)); EXPECT_EQ(-42, TestablePosition("").CalculateScore(42)); EXPECT_EQ(kN * kN, TestablePosition("X").CalculateScore(0)); EXPECT_EQ(-kN * kN, TestablePosition("O").CalculateScore(0)); { auto board = TestablePosition(R"( .X. X.O)"); EXPECT_EQ(2, board.CalculateScore(0)); } { auto board = TestablePosition(R"( .XX...... OOXX..... OOOX...X. OXX...... OOXXXXXX. OOOXOXOXX .O.OOXOOX .O.O.OOXX ......OOO)"); EXPECT_EQ(1.5, board.CalculateScore(6.5)); } { auto board = TestablePosition(R"( XXX...... OOXX..... OOOX...X. OXX...... OOXXXXXX. OOOXOXOXX .O.OOXOOX .O.O.OOXX ......OOO)"); EXPECT_EQ(2.5, board.CalculateScore(6.5)); } } // Plays through an example game and verifies that the outcome is as expected. TEST(PositionTest, PlayGame) { std::vector<std::string> moves = { "ge", "de", "cg", "ff", "ed", "dd", "ec", "dc", "eg", "df", "dg", "fe", "gc", "gd", "fd", "hd", "he", "bf", "bg", "fg", "cf", "be", "ce", "cd", "af", "hc", "hb", "gb", "ic", "bd", "fh", "gh", "fi", "eh", "dh", "di", "ci", "fc", "id", "ch", "ei", "eb", "gc", "fb", "gg", "gf", "hg", "hf", "if", "hh", "ig", "ih", "ie", "ha", "ga", "gd", "hd", "fa", "ib", "ae", "ag", "ee", "gd", "cb", "gi", "ga", "hi", "ia", "ii", "ef", "bh", "db", "hh", "ba", "ai", "ac", "bi", "da", "di", "ab", "eh", "bc", "gh", }; TestablePosition board(""); for (const auto& move : moves) { board.PlayMove(move); // std::cout << board.ToPrettyString() << std::endl; } EXPECT_EQ(CleanBoardString(R"( .O.O.OOOO O.OOOOOXX OO.OXOX.X .OOOXXXXX OOXOOOXXX XOXOOOOOX XXXXXOXXX .X.XXXXX. XXXXXXXXX)"), board.ToSimpleString()); std::array<int, 2> expected_captures = {10, 2}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(-0.5, board.CalculateScore(kDefaultKomi)); } } // namespace } // namespace minigo <commit_msg>Fix flaky position_test<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cc/position.h" #include <set> #include <string> #include <utility> #include <vector> #include "absl/strings/ascii.h" #include "cc/constants.h" #include "cc/test_utils.h" #include "gtest/gtest.h" namespace minigo { namespace { TEST(BoardVisitorTest, TestEpochRollover) { for (int j = 0; j <= 256; ++j) { BoardVisitor bv; for (int i = 0; i <= j; ++i) { bv.Begin(); } for (int i = 0; i < kN * kN; ++i) { auto c = Coord(i); ASSERT_TRUE(bv.Visit(c)); ASSERT_EQ(c, bv.Next()); ASSERT_FALSE(bv.Visit(c)); } } } TEST(GroupVisitorTest, TestEpochRollover) { for (int j = 0; j <= 256; ++j) { GroupVisitor gv; for (int i = 0; i <= j; ++i) { gv.Begin(); } for (int i = 0; i < Group::kMaxNumGroups; ++i) { auto g = GroupId(i); ASSERT_TRUE(gv.Visit(g)); ASSERT_FALSE(gv.Visit(g)); } } } TEST(PositionTest, TestIsKoish) { auto board = TestablePosition(R"( .X.O.O.O. X...O...O ...O..... X.O.O...O .X.O...X. X.O..X... .X.OX.X.. X.O..X..O XX.....X.)"); std::set<std::string> expected_black_kos = {"A9", "A5", "A3", "F3"}; std::set<std::string> expected_white_kos = {"E9", "J9", "D6"}; for (int row = 0; row < kN; ++row) { for (int col = 0; col < kN; ++col) { auto c = Coord(row, col).ToKgs(); Color expected; Color actual = board.IsKoish(c); if (expected_white_kos.find(c) != expected_white_kos.end()) { expected = Color::kWhite; } else if (expected_black_kos.find(c) != expected_black_kos.end()) { expected = Color::kBlack; } else { expected = Color::kEmpty; } EXPECT_EQ(expected, actual) << c; } } } TEST(PositionTest, TestMergeGroups1) { auto board = TestablePosition(R"( .X. X.X .X.)"); EXPECT_EQ(3, board.GroupAt("B9").num_liberties); EXPECT_EQ(3, board.GroupAt("A8").num_liberties); EXPECT_EQ(4, board.GroupAt("C8").num_liberties); EXPECT_EQ(4, board.GroupAt("B7").num_liberties); board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( .X. XXX .X.)"), board.ToSimpleString()); auto group = board.GroupAt("B8"); EXPECT_EQ(5, group.size); EXPECT_EQ(6, group.num_liberties); } TEST(PositionTest, TestMergeGroups2) { auto board = TestablePosition(R"( ......... ......... ......... ......... ......... ..O..O... ..O..O... ..O..O... ..OOO....)"); EXPECT_EQ(10, board.GroupAt("C1").num_liberties); EXPECT_EQ(8, board.GroupAt("F2").num_liberties); board.PlayMove("F1", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( ......... ......... ......... ......... ......... ..O..O... ..O..O... ..O..O... ..OOOO...)"), board.ToSimpleString()); auto group = board.GroupAt("F4"); EXPECT_EQ(10, group.size); EXPECT_EQ(16, group.num_liberties); } TEST(PositionTest, TestCaptureStone) { auto board = TestablePosition(R"( ......... ......... ......... ......... ......... ......... .......O. ......OX. .......O.)"); board.PlayMove("J2", Color::kWhite); std::array<int, 2> expected_captures = {0, 1}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ......... ......... ......... ......... ......... ......... .......O. ......O.O .......O.)"), board.ToSimpleString()); } TEST(PositionTest, TestCaptureMany1) { auto board = TestablePosition(R"( ..... ..... ..XX. .XOO. ..XX.)"); EXPECT_EQ(4, board.GroupAt("C7").num_liberties); EXPECT_EQ(3, board.GroupAt("B6").num_liberties); EXPECT_EQ(1, board.GroupAt("C6").num_liberties); EXPECT_EQ(4, board.GroupAt("D5").num_liberties); board.PlayMove("E6", Color::kBlack); std::array<int, 2> expected_captures = {2, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ..... ..... ..XX. .X..X ..XX.)"), board.ToSimpleString()); EXPECT_EQ(6, board.GroupAt("C7").num_liberties); EXPECT_EQ(4, board.GroupAt("B6").num_liberties); EXPECT_EQ(4, board.GroupAt("E6").num_liberties); EXPECT_EQ(6, board.GroupAt("D5").num_liberties); } TEST(PositionTest, TestCaptureMany2) { auto board = TestablePosition(R"( ..X.. .XOX. XO.OX .XOX. ..X..)"); board.PlayMove("C7", Color::kBlack); std::array<int, 2> expected_captures = {4, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( ..X.. .X.X. X.X.X .X.X. ..X..)"), board.ToSimpleString()); EXPECT_EQ(3, board.GroupAt("C9").num_liberties); EXPECT_EQ(4, board.GroupAt("B8").num_liberties); EXPECT_EQ(4, board.GroupAt("D8").num_liberties); EXPECT_EQ(3, board.GroupAt("A7").num_liberties); EXPECT_EQ(4, board.GroupAt("B6").num_liberties); EXPECT_EQ(4, board.GroupAt("D6").num_liberties); EXPECT_EQ(4, board.GroupAt("C5").num_liberties); } TEST(PositionTest, TestCaptureMultipleGroups) { auto board = TestablePosition(R"( .OX OXX XX.)"); board.PlayMove("A9", Color::kBlack); std::array<int, 2> expected_captures = {2, 0}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(CleanBoardString(R"( X.X .XX XX.)"), board.ToSimpleString()); EXPECT_EQ(2, board.GroupAt("A9").num_liberties); EXPECT_EQ(7, board.GroupAt("B8").num_liberties); } TEST(PositionTest, TestSameFriendlyGroupNeighboringTwice) { auto board = TestablePosition(R"( OO O.)"); board.PlayMove("B8", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( OO OO)"), board.ToSimpleString()); auto group = board.GroupAt("A9"); EXPECT_EQ(4, group.size); EXPECT_EQ(4, group.num_liberties); } TEST(PositionTest, TestSameOpponentGroupNeighboringTwice) { auto board = TestablePosition(R"( OO O.)"); board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( OO OX)"), board.ToSimpleString()); auto white_group = board.GroupAt("A9"); EXPECT_EQ(3, white_group.size); EXPECT_EQ(2, white_group.num_liberties); auto black_group = board.GroupAt("B8"); EXPECT_EQ(1, black_group.size); EXPECT_EQ(2, black_group.num_liberties); } TEST(PositionTest, IsMoveSuicidal) { auto board = TestablePosition(R"( ...O.O... ....O.... XO.....O. OXO...OXO O.XO.OX.O OXOOOOOOX XOOX.XO.. ...OOOXXO .....XOO.)"); std::vector<std::string> suicidal_moves = {"E9", "H5", "E3"}; for (const auto& c : suicidal_moves) { EXPECT_TRUE(board.IsMoveSuicidal(c, Color::kBlack)); } std::vector<std::string> nonsuicidal_moves = {"B5", "J1", "A9"}; for (const auto& c : nonsuicidal_moves) { EXPECT_FALSE(board.IsMoveSuicidal(c, Color::kBlack)); } } // Tests ko tracking. TEST(PositionTest, TestKoTracking) { auto board = TestablePosition(R"( XOXO..... .........)"); // Capturing a stone in a non-koish coord shouldn't create a ko. board.PlayMove("B8", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( X.XO..... .X.......)"), board.ToSimpleString()); // Capturing a stone in a koish coord should create a ko. board.PlayMove("C8", Color::kWhite); board.PlayMove("B9", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( XO*O..... .XO......)"), board.ToSimpleString()); // Playing a move should clear the ko. board.PlayMove("J9", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( XO.O....X .XO......)"), board.ToSimpleString()); // Test ko when capturing white as well. board.PlayMove("C9", Color::kBlack); EXPECT_EQ(CleanBoardString(R"( X*XO....X .XO......)"), board.ToSimpleString()); // Playing a move should clear the ko. board.PlayMove("H9", Color::kWhite); EXPECT_EQ(CleanBoardString(R"( X.XO...OX .XO......)"), board.ToSimpleString()); } TEST(PositionTest, TestSeki) { auto board = TestablePosition(R"( O....XXXX .....XOOO .....XOX. .....XO.X .....XOOX ......XOO ......XXX)"); // All empty squares are neutral points and black has 5 more stones than // white. EXPECT_EQ(5, board.CalculateScore(0)); } TEST(PositionTest, TestScoring) { EXPECT_EQ(0, TestablePosition("").CalculateScore(0)); EXPECT_EQ(-42, TestablePosition("").CalculateScore(42)); EXPECT_EQ(kN * kN, TestablePosition("X").CalculateScore(0)); EXPECT_EQ(-kN * kN, TestablePosition("O").CalculateScore(0)); { auto board = TestablePosition(R"( .X. X.O)"); EXPECT_EQ(2, board.CalculateScore(0)); } { auto board = TestablePosition(R"( .XX...... OOXX..... OOOX...X. OXX...... OOXXXXXX. OOOXOXOXX .O.OOXOOX .O.O.OOXX ......OOO)"); EXPECT_EQ(1.5, board.CalculateScore(6.5)); } { auto board = TestablePosition(R"( XXX...... OOXX..... OOOX...X. OXX...... OOXXXXXX. OOOXOXOXX .O.OOXOOX .O.O.OOXX ......OOO)"); EXPECT_EQ(2.5, board.CalculateScore(6.5)); } } // Plays through an example game and verifies that the outcome is as expected. TEST(PositionTest, PlayGame) { std::vector<std::string> moves = { "ge", "de", "cg", "ff", "ed", "dd", "ec", "dc", "eg", "df", "dg", "fe", "gc", "gd", "fd", "hd", "he", "bf", "bg", "fg", "cf", "be", "ce", "cd", "af", "hc", "hb", "gb", "ic", "bd", "fh", "gh", "fi", "eh", "dh", "di", "ci", "fc", "id", "ch", "ei", "eb", "gc", "fb", "gg", "gf", "hg", "hf", "if", "hh", "ig", "ih", "ie", "ha", "ga", "gd", "hd", "fa", "ib", "ae", "ag", "ee", "gd", "cb", "gi", "ga", "hi", "ia", "ii", "ef", "bh", "db", "hh", "ba", "ai", "ac", "bi", "da", "di", "ab", "eh", "bc", "gh", }; TestablePosition board(""); for (const auto& move : moves) { board.PlayMove(move); // std::cout << board.ToPrettyString() << std::endl; } EXPECT_EQ(CleanBoardString(R"( .O.O.OOOO O.OOOOOXX OO.OXOX.X .OOOXXXXX OOXOOOXXX XOXOOOOOX XXXXXOXXX .X.XXXXX. XXXXXXXXX)"), board.ToSimpleString()); std::array<int, 2> expected_captures = {10, 2}; EXPECT_EQ(expected_captures, board.num_captures()); EXPECT_EQ(-0.5, board.CalculateScore(kDefaultKomi)); } } // namespace } // namespace minigo <|endoftext|>
<commit_before>#include <numeric> #include <map> #include "acmacs-base/stream.hh" #include "seqdb/seqdb.hh" #include "signature-page/tree.hh" #include "signature-page/tree-export.hh" #include "signature-page/tree-iterate.hh" // ---------------------------------------------------------------------- using AADiff = std::vector<std::string>; struct DiffEntry { const Node* previous; const Node* current; AADiff with_other; }; inline std::ostream& operator<<(std::ostream& s, const DiffEntry& c) { return s << c.previous->seq_id << " -> " << c.current->seq_id << ' ' << c.with_other; } using AllDiffs = std::map<AADiff, std::vector<DiffEntry>>; // ---------------------------------------------------------------------- static size_t hamming_distance(std::string seq1, std::string seq2); static AADiff diff_sequence(std::string seq1, std::string seq2); static AllDiffs collect(const Tree& tree); static void compute_entries_diffs(AllDiffs& diffs); // ---------------------------------------------------------------------- int main(int argc, const char* const* argv) { int exit_code = 0; if (argc == 2) { std::string source_tree_file = argv[1]; const auto seqdb = seqdb::get(); Tree tree; tree::tree_import(source_tree_file, tree); tree.match_seqdb(seqdb); tree.set_number_strains(); tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves); tree.compute_cumulative_edge_length(); auto diffs = collect(tree); compute_entries_diffs(diffs); for (const auto& entry : diffs) { std::cout << entry.first << '\n'; for (const auto& diff : entry.second) { std::cout << " " << diff << '\n'; } } } else { std::cerr << "Usage: " << argv[0] << " tree.json[.xz]\n"; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- void compute_entries_diffs(AllDiffs& diffs) { for (auto& entry : diffs) { DiffEntry* prev = nullptr; for (auto& ee : entry.second) { if (prev) { ee.with_other = diff_sequence(prev->current->data.amino_acids(), ee.current->data.amino_acids()); } prev = &ee; } } } // compute_entries_diffs // ---------------------------------------------------------------------- AllDiffs collect(const Tree &tree) { AllDiffs diffs; const Node *previous = nullptr; tree::iterate_leaf(tree, [&previous, &diffs](const Node &node) { if (previous) { // const auto dist = hamming_distance(previous->data.amino_acids(), node.data.amino_acids()); // std::cout << std::setw(3) << std::right << dist << ' ' << node.seq_id << '\n'; const auto diff = diff_sequence(previous->data.amino_acids(), node.data.amino_acids()); if (!diff.empty()) { auto found = diffs.find(diff); if (found == diffs.end()) diffs.emplace(diff, std::vector<DiffEntry>{DiffEntry{previous, &node, {}}}); else found->second.push_back(DiffEntry{previous, &node, {}}); // std::cout << diff << " -- " << node.seq_id << " -- " << previous->seq_id << '\n'; } } previous = &node; }); return diffs; } // collect // ---------------------------------------------------------------------- size_t hamming_distance(std::string seq1, std::string seq2) { size_t dist = 0; for (size_t pos = 0; pos < std::min(seq1.size(), seq2.size()); ++pos) { if (seq1[pos] != seq2[pos]) ++dist; } return dist; } // hamming_distance // ---------------------------------------------------------------------- AADiff diff_sequence(std::string seq1, std::string seq2) { AADiff result; for (size_t pos = 0; pos < std::min(seq1.size(), seq2.size()); ++pos) { if (seq1[pos] != seq2[pos]) result.push_back(seq1[pos] + std::to_string(pos + 1) + seq2[pos]); } return result; } // diff // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>report AA per pos collected for all sequences in the tree<commit_after>#include <numeric> #include <map> #include <cmath> #include "acmacs-base/stream.hh" #include "acmacs-base/enumerate.hh" #include "seqdb/seqdb.hh" #include "signature-page/tree.hh" #include "signature-page/tree-export.hh" #include "signature-page/tree-iterate.hh" // ---------------------------------------------------------------------- using AADiff = std::vector<std::string>; struct DiffEntry { const Node* previous; const Node* current; AADiff with_other; }; inline std::ostream& operator<<(std::ostream& s, const DiffEntry& c) { return s << c.previous->seq_id << " -> " << c.current->seq_id << ' ' << c.with_other; } using AllDiffs = std::map<AADiff, std::vector<DiffEntry>>; // ---------------------------------------------------------------------- static size_t hamming_distance(std::string seq1, std::string seq2); static AADiff diff_sequence(std::string seq1, std::string seq2); static AllDiffs collect(const Tree& tree); static void compute_entries_diffs(AllDiffs& diffs); // ---------------------------------------------------------------------- int main(int argc, const char* const* argv) { int exit_code = 0; if (argc == 2) { std::string source_tree_file = argv[1]; const auto seqdb = seqdb::get(); Tree tree; tree::tree_import(source_tree_file, tree); tree.match_seqdb(seqdb); tree.set_number_strains(); tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves); tree.compute_cumulative_edge_length(); auto diffs = collect(tree); compute_entries_diffs(diffs); for (const auto& entry : diffs) { std::cout << entry.first << '\n'; for (const auto& diff : entry.second) { std::cout << " " << diff << '\n'; } } std::map<size_t, std::map<char, size_t>> aa_per_pos; auto collect_aa_per_pos = [&](const Node& node) { const auto sequence = node.data.amino_acids(); for (auto [pos, aa] : acmacs::enumerate(sequence)) { if (aa != 'X') ++aa_per_pos[pos][aa]; } }; tree::iterate_leaf(tree, collect_aa_per_pos); for (auto it = aa_per_pos.begin(); it != aa_per_pos.end();) { if (it->second.size() < 2) it = aa_per_pos.erase(it); else ++it; } // std::cout << "======================================================================\n"; // for (const auto& pos_e : aa_per_pos) // std::cout << std::setw(3) << std::right << (pos_e.first + 1) << ' ' << pos_e.second << '\n'; // https://en.wikipedia.org/wiki/Diversity_index using all_pos_t = std::pair<size_t, ssize_t>; std::vector <all_pos_t> all_pos(aa_per_pos.size()); std::transform(aa_per_pos.begin(), aa_per_pos.end(), all_pos.begin(), [](const auto& src) -> all_pos_t { const auto sum = std::accumulate(src.second.begin(), src.second.end(), 0UL, [](auto accum, const auto& entry) { return accum + entry.second; }); const auto shannon_index = -std::accumulate(src.second.begin(), src.second.end(), 0.0, [sum = double(sum)](auto accum, const auto& entry) { const double p = entry.second / sum; return accum + p * std::log(p); }); return {src.first, std::lround(shannon_index * 100)}; }); std::sort(std::begin(all_pos), std::end(all_pos), [](const auto& p1, const auto& p2) { return p1.second > p2.second; }); std::cout << "======================================================================\n"; for (const auto& pos_e : all_pos) std::cout << std::setw(3) << std::right << (pos_e.first + 1) << ' ' << aa_per_pos[pos_e.first] << '\n'; } else { std::cerr << "Usage: " << argv[0] << " tree.json[.xz]\n"; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- void compute_entries_diffs(AllDiffs& diffs) { for (auto& entry : diffs) { DiffEntry* prev = nullptr; for (auto& ee : entry.second) { if (prev) { ee.with_other = diff_sequence(prev->current->data.amino_acids(), ee.current->data.amino_acids()); } prev = &ee; } } } // compute_entries_diffs // ---------------------------------------------------------------------- AllDiffs collect(const Tree &tree) { AllDiffs diffs; const Node *previous = nullptr; tree::iterate_leaf(tree, [&previous, &diffs](const Node &node) { if (previous) { // const auto dist = hamming_distance(previous->data.amino_acids(), node.data.amino_acids()); // std::cout << std::setw(3) << std::right << dist << ' ' << node.seq_id << '\n'; const auto diff = diff_sequence(previous->data.amino_acids(), node.data.amino_acids()); if (!diff.empty()) { auto found = diffs.find(diff); if (found == diffs.end()) diffs.emplace(diff, std::vector<DiffEntry>{DiffEntry{previous, &node, {}}}); else found->second.push_back(DiffEntry{previous, &node, {}}); // std::cout << diff << " -- " << node.seq_id << " -- " << previous->seq_id << '\n'; } } previous = &node; }); return diffs; } // collect // ---------------------------------------------------------------------- size_t hamming_distance(std::string seq1, std::string seq2) { size_t dist = 0; for (size_t pos = 0; pos < std::min(seq1.size(), seq2.size()); ++pos) { if (seq1[pos] != seq2[pos]) ++dist; } return dist; } // hamming_distance // ---------------------------------------------------------------------- AADiff diff_sequence(std::string seq1, std::string seq2) { AADiff result; for (size_t pos = 0; pos < std::min(seq1.size(), seq2.size()); ++pos) { if (seq1[pos] != seq2[pos]) result.push_back(seq1[pos] + std::to_string(pos + 1) + seq2[pos]); } return result; } // diff // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/********************************************************************** * File: basedir.c (Formerly getpath.c) * Description: Find the directory location of the current executable using PATH. * Author: Ray Smith * Created: Mon Jul 09 09:06:39 BST 1990 * * (C) Copyright 1990, Hewlett-Packard Ltd. ** 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 "basedir.h" #include <stdlib.h> #include "mfcpch.h" // Precompiled headers // Returns the given code_path truncated to the last slash. // Useful for getting to the directory of argv[0], but does not search // any paths. TESS_API void truncate_path(const char *code_path, STRING* trunc_path) { int trunc_index = -1; if (code_path != NULL) { const char* last_slash = strrchr(code_path, '/'); if (last_slash != NULL && last_slash + 1 - code_path > trunc_index) trunc_index = last_slash + 1 - code_path; last_slash = strrchr(code_path, '\\'); if (last_slash != NULL && last_slash + 1 - code_path > trunc_index) trunc_index = last_slash + 1 - code_path; } *trunc_path = code_path; if (trunc_index >= 0) trunc_path->truncate_at(trunc_index); else *trunc_path = "./"; } <commit_msg>Updated comment<commit_after>/********************************************************************** * File: basedir.c (Formerly getpath.c) * Description: Find the directory location of the current executable using PATH. * Author: Ray Smith * Created: Mon Jul 09 09:06:39 BST 1990 * * (C) Copyright 1990, Hewlett-Packard Ltd. ** 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 "basedir.h" #include <stdlib.h> #include "mfcpch.h" // Precompiled headers // Assuming that code_path is the name of some file in a desired directory, // returns the given code_path stripped back to the last slash, leaving // the last slash in place. If there is no slash, returns ./ assuming that // the input was the name of something in the current directory. // Useful for getting to the directory of argv[0], but does not search // any paths. TESS_API void truncate_path(const char *code_path, STRING* trunc_path) { int trunc_index = -1; if (code_path != NULL) { const char* last_slash = strrchr(code_path, '/'); if (last_slash != NULL && last_slash + 1 - code_path > trunc_index) trunc_index = last_slash + 1 - code_path; last_slash = strrchr(code_path, '\\'); if (last_slash != NULL && last_slash + 1 - code_path > trunc_index) trunc_index = last_slash + 1 - code_path; } *trunc_path = code_path; if (trunc_index >= 0) trunc_path->truncate_at(trunc_index); else *trunc_path = "./"; } <|endoftext|>
<commit_before>#include "nicolive.h" #include <obs-module.h> #include "nico-live-api.hpp" #include "nico-live.hpp" #include "nicolive-log.h" // cannot use anonymouse struct because VS2013 bug // https://connect.microsoft.com/VisualStudio/feedback/details/808506/nsdmi-silently-ignored-on-nested-anonymous-classes-and-structs namespace { struct nicolive_buff_s { char *mail = nullptr; char *password = nullptr; char *session = nullptr; char *live_id = nullptr; char *live_url = nullptr; char *live_key = nullptr; } nicolive_buff; } extern "C" void *nicolive_create(void) { return new NicoLive(); } extern "C" void nicolive_destroy(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->deleteLater(); } extern "C" void nicolive_set_settings( void *data, const char *mail, const char *password, const char *session) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive_log_debug("password: %s", password); nicolive->setAccount(mail, password); nicolive->setSession(session); } extern "C" void nicolive_set_enabled_adjust_bitrate(void *data, bool enabled) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->setEnabledAdjustBitrate(enabled); } extern "C" const char *nicolive_get_mail(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.mail); nicolive_buff.mail = bstrdup(nicolive->getMail().toStdString().c_str()); return nicolive_buff.mail; } extern "C" const char *nicolive_get_password(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.password); nicolive_buff.password = bstrdup(nicolive->getPassword().toStdString().c_str()); return nicolive_buff.password; } extern "C" const char *nicolive_get_session(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.session); nicolive_buff.session = bstrdup(nicolive->getSession().toStdString().c_str()); return nicolive_buff.session; } extern "C" const char *nicolive_get_live_id(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_id); nicolive_buff.live_id = bstrdup(nicolive->getLiveId().toStdString().c_str()); return nicolive_buff.live_id; } extern "C" const char *nicolive_get_live_url(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_url); nicolive_buff.live_url = bstrdup(nicolive->getLiveUrl().toStdString().c_str()); return nicolive_buff.live_url; } extern "C" const char *nicolive_get_live_key(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_key); nicolive_buff.live_key = bstrdup(nicolive->getLiveKey().toStdString().c_str()); return nicolive_buff.live_key; } extern "C" long long nicolive_get_live_bitrate(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); return nicolive->getLiveBitrate(); } extern "C" bool nicolive_enabled_adjust_bitrate(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); return nicolive->enabledAdjustBitrate(); } extern "C" bool nicolive_load_viqo_settings(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->loadViqoSettings(); } extern "C" bool nicolive_check_session(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->checkSession(); } extern "C" bool nicolive_check_live(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->checkLive(); } extern "C" void nicolive_start_streaming(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->startStreaming(); } extern "C" void nicolive_stop_streaming(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->stopStreaming(); } extern "C" void nicolive_start_watching(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->startWatching(); } extern "C" void nicolive_stop_watching(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->stopWatching(); } extern "C" bool nicolive_silent_once(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->silentOnce(); } extern "C" bool nicolive_test_login(const char *mail, const char *password) { std::string mail_str(mail); std::string password_str(password); NicoLiveApi nla; auto ticket = nla.loginNicoliveEncoder(mail_str, password_str); return !ticket.empty(); } extern "C" bool nicolive_test_session(const char *session) { std::string session_str(session); NicoLiveApi nla; nla.setCookie("user_session", session_str); return nla.getPublishStatus(); } <commit_msg>失敗条件の見直し<commit_after>#include "nicolive.h" #include <obs-module.h> #include "nico-live-api.hpp" #include "nico-live.hpp" #include "nicolive-log.h" // cannot use anonymouse struct because VS2013 bug // https://connect.microsoft.com/VisualStudio/feedback/details/808506/nsdmi-silently-ignored-on-nested-anonymous-classes-and-structs namespace { struct nicolive_buff_s { char *mail = nullptr; char *password = nullptr; char *session = nullptr; char *live_id = nullptr; char *live_url = nullptr; char *live_key = nullptr; } nicolive_buff; } extern "C" void *nicolive_create(void) { return new NicoLive(); } extern "C" void nicolive_destroy(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->deleteLater(); } extern "C" void nicolive_set_settings( void *data, const char *mail, const char *password, const char *session) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive_log_debug("password: %s", password); nicolive->setAccount(mail, password); nicolive->setSession(session); } extern "C" void nicolive_set_enabled_adjust_bitrate(void *data, bool enabled) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->setEnabledAdjustBitrate(enabled); } extern "C" const char *nicolive_get_mail(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.mail); nicolive_buff.mail = bstrdup(nicolive->getMail().toStdString().c_str()); return nicolive_buff.mail; } extern "C" const char *nicolive_get_password(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.password); nicolive_buff.password = bstrdup(nicolive->getPassword().toStdString().c_str()); return nicolive_buff.password; } extern "C" const char *nicolive_get_session(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.session); nicolive_buff.session = bstrdup(nicolive->getSession().toStdString().c_str()); return nicolive_buff.session; } extern "C" const char *nicolive_get_live_id(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_id); nicolive_buff.live_id = bstrdup(nicolive->getLiveId().toStdString().c_str()); return nicolive_buff.live_id; } extern "C" const char *nicolive_get_live_url(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_url); nicolive_buff.live_url = bstrdup(nicolive->getLiveUrl().toStdString().c_str()); return nicolive_buff.live_url; } extern "C" const char *nicolive_get_live_key(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); bfree(nicolive_buff.live_key); nicolive_buff.live_key = bstrdup(nicolive->getLiveKey().toStdString().c_str()); return nicolive_buff.live_key; } extern "C" long long nicolive_get_live_bitrate(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); return nicolive->getLiveBitrate(); } extern "C" bool nicolive_enabled_adjust_bitrate(const void *data) { const NicoLive *nicolive = static_cast<const NicoLive *>(data); return nicolive->enabledAdjustBitrate(); } extern "C" bool nicolive_load_viqo_settings(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->loadViqoSettings(); } extern "C" bool nicolive_check_session(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->checkSession(); } extern "C" bool nicolive_check_live(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->checkLive(); } extern "C" void nicolive_start_streaming(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->startStreaming(); } extern "C" void nicolive_stop_streaming(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->stopStreaming(); } extern "C" void nicolive_start_watching(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->startWatching(); } extern "C" void nicolive_stop_watching(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); nicolive->stopWatching(); } extern "C" bool nicolive_silent_once(void *data) { NicoLive *nicolive = static_cast<NicoLive *>(data); return nicolive->silentOnce(); } extern "C" bool nicolive_test_login(const char *mail, const char *password) { std::string mail_str(mail); std::string password_str(password); NicoLiveApi nla; auto ticket = nla.loginNicoliveEncoder(mail_str, password_str); return !ticket.empty(); } extern "C" bool nicolive_test_session(const char *session) { std::string session_str(session); NicoLiveApi nla; nla.setCookie("user_session", session_str); const std::string statusXpath = "/getpublishstatus/@status"; const std::string errorCodeXpath = "/getpublishstatus/error/code/text()"; std::unordered_map<std::string, std::vector<std::string>> data; data[statusXpath] = std::vector<std::string>(); data[errorCodeXpath] = std::vector<std::string>(); bool result = nla.getPublishStatus(&data); if (!result) return false; if (!data[statusXpath].empty()) return false; if (data[statusXpath][0] == "ok") return true; if (data[statusXpath][0] == "fail" && !data[errorCodeXpath].empty() && data[errorCodeXpath][0] == "notfound") return true; return false; } <|endoftext|>
<commit_before>#include "ex12_19.h" int main() { return 0; } <commit_msg>updata ex12.19<commit_after><|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * ADIOS.cpp * * Created on: Sep 29, 2016 * Author: William F Godoy godoywf@ornl.gov */ #include "ADIOS.h" #include <algorithm> // std::transform #include <ios> //std::ios_base::failure #include "adios2/ADIOSMPI.h" #include "adios2/core/IO.h" #include "adios2/helper/adiosFunctions.h" //InquireKey, BroadcastFile // OPERATORS // compress #ifdef ADIOS2_HAVE_BZIP2 #include "adios2/operator/compress/CompressBZip2.h" #endif #ifdef ADIOS2_HAVE_ZFP #include "adios2/operator/compress/CompressZfp.h" #endif #ifdef ADIOS2_HAVE_SZ #include "adios2/operator/compress/CompressSZ.h" #endif #ifdef ADIOS2_HAVE_MGARD #include "adios2/operator/compress/CompressMGARD.h" #endif // callbacks #include "adios2/operator/callback/Signature1.h" #include "adios2/operator/callback/Signature2.h" namespace adios2 { namespace core { ADIOS::ADIOS(const std::string configFile, MPI_Comm mpiComm, const bool debugMode, const std::string hostLanguage) : m_ConfigFile(configFile), m_DebugMode(debugMode), m_HostLanguage(hostLanguage) { if (m_DebugMode && mpiComm == MPI_COMM_NULL) { throw std::ios_base::failure( "ERROR: MPI communicator is MPI_COMM_NULL, " " in call to ADIOS constructor\n"); } int flag; MPI_Initialized(&flag); if (flag) { MPI_Comm_dup(mpiComm, &m_MPIComm); m_NeedMPICommFree = true; } else { m_MPIComm = mpiComm; m_NeedMPICommFree = false; } if (!configFile.empty()) { if (configFile.substr(configFile.size() - 3) == "xml") { XMLInit(configFile); } // TODO expand for other formats } } ADIOS::ADIOS(const std::string configFile, const bool debugMode, const std::string hostLanguage) : ADIOS(configFile, MPI_COMM_SELF, debugMode, hostLanguage) { } ADIOS::ADIOS(MPI_Comm mpiComm, const bool debugMode, const std::string hostLanguage) : ADIOS("", mpiComm, debugMode, hostLanguage) { } ADIOS::ADIOS(const bool debugMode, const std::string hostLanguage) : ADIOS("", MPI_COMM_SELF, debugMode, hostLanguage) { } ADIOS::~ADIOS() { int flag; MPI_Initialized(&flag); if (flag && m_NeedMPICommFree) { MPI_Comm_free(&m_MPIComm); } } IO &ADIOS::DeclareIO(const std::string name) { auto itIO = m_IOs.find(name); if (itIO != m_IOs.end()) { IO &io = itIO->second; if (!io.IsDeclared()) // exists from config xml { io.SetDeclared(); return io; } else { if (m_DebugMode) { throw std::invalid_argument( "ERROR: IO with name " + name + " previously declared with DeclareIO, name must be unique," " in call to DeclareIO\n"); } } } auto ioPair = m_IOs.emplace( name, IO(*this, name, m_MPIComm, false, m_HostLanguage, m_DebugMode)); IO &io = ioPair.first->second; io.SetDeclared(); return io; } IO &ADIOS::AtIO(const std::string name) { auto itIO = m_IOs.find(name); if (itIO == m_IOs.end()) { throw std::invalid_argument("ERROR: IO with name " + name + " was not declared, did you previously " "call DeclareIO?, in call to AtIO\n"); } else { if (!itIO->second.IsDeclared()) { throw std::invalid_argument("ERROR: IO with name " + name + " was not declared, did you previously " "call DeclareIO ?, in call to AtIO\n"); } } return itIO->second; } void ADIOS::FlushAll() { for (auto &ioPair : m_IOs) { ioPair.second.FlushAll(); } } Operator &ADIOS::DefineOperator(const std::string name, const std::string type, const Params &parameters) { std::shared_ptr<Operator> operatorPtr; CheckOperator(name); std::string typeLowerCase(type); std::transform(typeLowerCase.begin(), typeLowerCase.end(), typeLowerCase.begin(), ::tolower); if (typeLowerCase == "bzip2") { #ifdef ADIOS2_HAVE_BZIP2 auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressBZip2>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "bzip2 library, in call to DefineOperator\n"); #endif } else if (typeLowerCase == "zfp") { #ifdef ADIOS2_HAVE_ZFP auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressZfp>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "zfp library (minimum v1.5), in call to DefineOperator\n"); #endif } else if (typeLowerCase == "sz") { #ifdef ADIOS2_HAVE_SZ auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressSZ>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "SZ library (minimum v2.0.2.0), in call to DefineOperator\n"); #endif } else if (typeLowerCase == "mgard") { #ifdef ADIOS2_HAVE_MGARD auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressMGARD>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "MGARD library (minimum v0.0.0.1), in call to DefineOperator\n"); #endif } else { if (m_DebugMode) { throw std::invalid_argument( "ERROR: Operator " + name + " of type " + type + " is not supported by ADIOS2, in call to DefineOperator\n"); } } if (m_DebugMode && !operatorPtr) { throw std::invalid_argument( "ERROR: Operator " + name + " of type " + type + " couldn't be defined, in call to DefineOperator\n"); } return *operatorPtr.get(); } Operator *ADIOS::InquireOperator(const std::string name) noexcept { std::shared_ptr<Operator> *op = helper::InquireKey(name, m_Operators); if (op == nullptr) { return nullptr; } return op->get(); } #define declare_type(T) \ Operator &ADIOS::DefineCallBack( \ const std::string name, \ const std::function<void(const T *, const std::string &, \ const std::string &, const std::string &, \ const size_t, const Dims &, const Dims &, \ const Dims &)> &function, \ const Params &parameters) \ { \ CheckOperator(name); \ std::shared_ptr<Operator> callbackOperator = \ std::make_shared<callback::Signature1>(function, parameters, \ m_DebugMode); \ \ auto itPair = m_Operators.emplace(name, std::move(callbackOperator)); \ return *itPair.first->second; \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type Operator &ADIOS::DefineCallBack( const std::string name, const std::function<void(void *, const std::string &, const std::string &, const std::string &, const size_t, const Dims &, const Dims &, const Dims &)> &function, const Params &parameters) { CheckOperator(name); std::shared_ptr<Operator> callbackOperator = std::make_shared<callback::Signature2>(function, parameters, m_DebugMode); auto itPair = m_Operators.emplace(name, std::move(callbackOperator)); return *itPair.first->second; } bool ADIOS::RemoveIO(const std::string name) { if (m_IOs.erase(name) == 1) { return true; } return false; } void ADIOS::RemoveAllIOs() noexcept { m_IOs.clear(); } // PRIVATE FUNCTIONS void ADIOS::CheckOperator(const std::string name) const { if (m_DebugMode) { if (m_Operators.count(name) == 1) { throw std::invalid_argument( "ERROR: Operator with name " + name + ", is already defined in either config file " "or with call to DefineOperator, name must " "be unique, in call to DefineOperator\n"); } } } void ADIOS::XMLInit(const std::string &configFileXML) { helper::ParseConfigXML(*this, configFileXML, m_IOs, m_Operators); } } // end namespace core } // end namespace adios2 <commit_msg>mpicomm: check MPI_Finalized before MPI_Comm_free<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * ADIOS.cpp * * Created on: Sep 29, 2016 * Author: William F Godoy godoywf@ornl.gov */ #include "ADIOS.h" #include <algorithm> // std::transform #include <ios> //std::ios_base::failure #include "adios2/ADIOSMPI.h" #include "adios2/core/IO.h" #include "adios2/helper/adiosFunctions.h" //InquireKey, BroadcastFile // OPERATORS // compress #ifdef ADIOS2_HAVE_BZIP2 #include "adios2/operator/compress/CompressBZip2.h" #endif #ifdef ADIOS2_HAVE_ZFP #include "adios2/operator/compress/CompressZfp.h" #endif #ifdef ADIOS2_HAVE_SZ #include "adios2/operator/compress/CompressSZ.h" #endif #ifdef ADIOS2_HAVE_MGARD #include "adios2/operator/compress/CompressMGARD.h" #endif // callbacks #include "adios2/operator/callback/Signature1.h" #include "adios2/operator/callback/Signature2.h" namespace adios2 { namespace core { ADIOS::ADIOS(const std::string configFile, MPI_Comm mpiComm, const bool debugMode, const std::string hostLanguage) : m_ConfigFile(configFile), m_DebugMode(debugMode), m_HostLanguage(hostLanguage) { if (m_DebugMode && mpiComm == MPI_COMM_NULL) { throw std::ios_base::failure( "ERROR: MPI communicator is MPI_COMM_NULL, " " in call to ADIOS constructor\n"); } int flag; MPI_Initialized(&flag); if (flag) { MPI_Comm_dup(mpiComm, &m_MPIComm); m_NeedMPICommFree = true; } else { m_MPIComm = mpiComm; m_NeedMPICommFree = false; } if (!configFile.empty()) { if (configFile.substr(configFile.size() - 3) == "xml") { XMLInit(configFile); } // TODO expand for other formats } } ADIOS::ADIOS(const std::string configFile, const bool debugMode, const std::string hostLanguage) : ADIOS(configFile, MPI_COMM_SELF, debugMode, hostLanguage) { } ADIOS::ADIOS(MPI_Comm mpiComm, const bool debugMode, const std::string hostLanguage) : ADIOS("", mpiComm, debugMode, hostLanguage) { } ADIOS::ADIOS(const bool debugMode, const std::string hostLanguage) : ADIOS("", MPI_COMM_SELF, debugMode, hostLanguage) { } ADIOS::~ADIOS() { int flag; MPI_Finalized(&flag); if (!flag && m_NeedMPICommFree) { MPI_Comm_free(&m_MPIComm); } } IO &ADIOS::DeclareIO(const std::string name) { auto itIO = m_IOs.find(name); if (itIO != m_IOs.end()) { IO &io = itIO->second; if (!io.IsDeclared()) // exists from config xml { io.SetDeclared(); return io; } else { if (m_DebugMode) { throw std::invalid_argument( "ERROR: IO with name " + name + " previously declared with DeclareIO, name must be unique," " in call to DeclareIO\n"); } } } auto ioPair = m_IOs.emplace( name, IO(*this, name, m_MPIComm, false, m_HostLanguage, m_DebugMode)); IO &io = ioPair.first->second; io.SetDeclared(); return io; } IO &ADIOS::AtIO(const std::string name) { auto itIO = m_IOs.find(name); if (itIO == m_IOs.end()) { throw std::invalid_argument("ERROR: IO with name " + name + " was not declared, did you previously " "call DeclareIO?, in call to AtIO\n"); } else { if (!itIO->second.IsDeclared()) { throw std::invalid_argument("ERROR: IO with name " + name + " was not declared, did you previously " "call DeclareIO ?, in call to AtIO\n"); } } return itIO->second; } void ADIOS::FlushAll() { for (auto &ioPair : m_IOs) { ioPair.second.FlushAll(); } } Operator &ADIOS::DefineOperator(const std::string name, const std::string type, const Params &parameters) { std::shared_ptr<Operator> operatorPtr; CheckOperator(name); std::string typeLowerCase(type); std::transform(typeLowerCase.begin(), typeLowerCase.end(), typeLowerCase.begin(), ::tolower); if (typeLowerCase == "bzip2") { #ifdef ADIOS2_HAVE_BZIP2 auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressBZip2>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "bzip2 library, in call to DefineOperator\n"); #endif } else if (typeLowerCase == "zfp") { #ifdef ADIOS2_HAVE_ZFP auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressZfp>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "zfp library (minimum v1.5), in call to DefineOperator\n"); #endif } else if (typeLowerCase == "sz") { #ifdef ADIOS2_HAVE_SZ auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressSZ>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "SZ library (minimum v2.0.2.0), in call to DefineOperator\n"); #endif } else if (typeLowerCase == "mgard") { #ifdef ADIOS2_HAVE_MGARD auto itPair = m_Operators.emplace( name, std::make_shared<compress::CompressMGARD>(parameters, m_DebugMode)); operatorPtr = itPair.first->second; #else throw std::invalid_argument( "ERROR: this version of ADIOS2 didn't compile with the " "MGARD library (minimum v0.0.0.1), in call to DefineOperator\n"); #endif } else { if (m_DebugMode) { throw std::invalid_argument( "ERROR: Operator " + name + " of type " + type + " is not supported by ADIOS2, in call to DefineOperator\n"); } } if (m_DebugMode && !operatorPtr) { throw std::invalid_argument( "ERROR: Operator " + name + " of type " + type + " couldn't be defined, in call to DefineOperator\n"); } return *operatorPtr.get(); } Operator *ADIOS::InquireOperator(const std::string name) noexcept { std::shared_ptr<Operator> *op = helper::InquireKey(name, m_Operators); if (op == nullptr) { return nullptr; } return op->get(); } #define declare_type(T) \ Operator &ADIOS::DefineCallBack( \ const std::string name, \ const std::function<void(const T *, const std::string &, \ const std::string &, const std::string &, \ const size_t, const Dims &, const Dims &, \ const Dims &)> &function, \ const Params &parameters) \ { \ CheckOperator(name); \ std::shared_ptr<Operator> callbackOperator = \ std::make_shared<callback::Signature1>(function, parameters, \ m_DebugMode); \ \ auto itPair = m_Operators.emplace(name, std::move(callbackOperator)); \ return *itPair.first->second; \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type Operator &ADIOS::DefineCallBack( const std::string name, const std::function<void(void *, const std::string &, const std::string &, const std::string &, const size_t, const Dims &, const Dims &, const Dims &)> &function, const Params &parameters) { CheckOperator(name); std::shared_ptr<Operator> callbackOperator = std::make_shared<callback::Signature2>(function, parameters, m_DebugMode); auto itPair = m_Operators.emplace(name, std::move(callbackOperator)); return *itPair.first->second; } bool ADIOS::RemoveIO(const std::string name) { if (m_IOs.erase(name) == 1) { return true; } return false; } void ADIOS::RemoveAllIOs() noexcept { m_IOs.clear(); } // PRIVATE FUNCTIONS void ADIOS::CheckOperator(const std::string name) const { if (m_DebugMode) { if (m_Operators.count(name) == 1) { throw std::invalid_argument( "ERROR: Operator with name " + name + ", is already defined in either config file " "or with call to DefineOperator, name must " "be unique, in call to DefineOperator\n"); } } } void ADIOS::XMLInit(const std::string &configFileXML) { helper::ParseConfigXML(*this, configFileXML, m_IOs, m_Operators); } } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH #include <vector> #include <dune/common/dynmatrix.hh> #include <dune/common/dynvector.hh> #include <dune/common/shared_ptr.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { template< class TestFunctionSpaceImp, class AnsatzFunctionSpaceImp = TestFunctionSpaceImp > class System { public: typedef TestFunctionSpaceImp TestFunctionSpaceType; typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType; typedef System< TestFunctionSpaceImp, AnsatzFunctionSpaceImp > ThisType; private: typedef typename TestFunctionSpaceType::GridViewType GridViewType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename TestFunctionSpaceType::FunctionSpaceType::RangeFieldType RangeFieldType; typedef Dune::DynamicMatrix< RangeFieldType > LocalMatrixType; typedef Dune::DynamicVector< RangeFieldType > LocalVectorType; typedef std::vector< std::vector< LocalMatrixType > > LocalMatricesContainerType; typedef std::vector< std::vector< LocalVectorType > > LocalVectorsContainerType; class LocalMatrixAssemblerApplication { public: virtual void apply(const TestFunctionSpaceType& /*_testSpace*/, const AnsatzFunctionSpaceType& /*_ansatzSpace*/, const EntityType& /*_entity*/, LocalMatricesContainerType& /*_localMatricesContainer*/) const = 0; virtual std::vector< unsigned int > numTmpObjectsRequired() const = 0; }; // class LocalOperatorApplication template< class LocalMatrixAssemblerType, class MatrixType > class LocalMatrixAssemblerApplicationWrapper : public LocalMatrixAssemblerApplication { public: LocalMatrixAssemblerApplicationWrapper(const Dune::shared_ptr< const LocalMatrixAssemblerType > _localMatrixAssembler, Dune::shared_ptr< MatrixType > _matrix) : localMatrixAssembler_(_localMatrixAssembler) , matrix_(_matrix) {} virtual void apply(const TestFunctionSpaceType& _testSpace, const AnsatzFunctionSpaceType& _ansatzSpace, const EntityType& _entity, LocalMatricesContainerType& _localMatricesContainer) const { localMatrixAssembler_->assembleLocal(_testSpace, _ansatzSpace, _entity, *matrix_, _localMatricesContainer); } // virtual void applyLocal(...) const virtual std::vector< unsigned int > numTmpObjectsRequired() const { return localMatrixAssembler_->numTmpObjectsRequired(); } // virtual std::vector< unsigned int > numTmpObjectsRequired() const private: const Dune::shared_ptr< const LocalMatrixAssemblerType > localMatrixAssembler_; Dune::shared_ptr< MatrixType > matrix_; }; // class LocalMatrixAssemblerApplicationWrapper class LocalVectorAssemblerApplication { public: virtual void apply(const TestFunctionSpaceType& /*_testSpace*/, const EntityType& /*_entity*/, LocalVectorsContainerType& /*_localMatricesContainer*/) const = 0; virtual std::vector< unsigned int > numTmpObjectsRequired() const = 0; }; // class LocalOperatorApplication template< class LocalVectorAssemblerType, class VectorType > class LocalVectorAssemblerApplicationWrapper : public LocalVectorAssemblerApplication { public: LocalVectorAssemblerApplicationWrapper(const Dune::shared_ptr< const LocalVectorAssemblerType > _localVectorAssembler, Dune::shared_ptr< VectorType > _vector) : localVectorAssembler_(_localVectorAssembler) , vector_(_vector) {} virtual void apply(const TestFunctionSpaceType& _testSpace, const EntityType& _entity, LocalVectorsContainerType& _localVectorsContainer) const { localVectorAssembler_->assembleLocal(_testSpace, _entity, *vector_, _localVectorsContainer); } // virtual void applyLocal(...) const virtual std::vector< unsigned int > numTmpObjectsRequired() const { return localVectorAssembler_->numTmpObjectsRequired(); } // virtual std::vector< unsigned int > numTmpObjectsRequired() const private: const Dune::shared_ptr< const LocalVectorAssemblerType > localVectorAssembler_; Dune::shared_ptr< VectorType > vector_; }; // class LocalMatrixAssemblerApplicationWrapper public: System(const TestFunctionSpaceType& _testSpace, const AnsatzFunctionSpaceType& _ansatzSpace) : testSpace_(_testSpace) , ansatzSpace_(_ansatzSpace) {} System(const TestFunctionSpaceType& _testSpace) : testSpace_(_testSpace) , ansatzSpace_(_testSpace) {} const TestFunctionSpaceType& testSpace() { return testSpace_; } const AnsatzFunctionSpaceType& ansatzSpace() { return ansatzSpace_; } template< class LocalMatrixAssemblerType, class MatrixType > void addLocalMatrixAssembler(const Dune::shared_ptr< const LocalMatrixAssemblerType > _localMatrixAssembler, Dune::shared_ptr< MatrixType > _matrix) { typedef LocalMatrixAssemblerApplicationWrapper< LocalMatrixAssemblerType, MatrixType > WrapperType; WrapperType* wrapper = new WrapperType(_localMatrixAssembler, _matrix); localMatrixAssemblers_.push_back(wrapper); } template< class LocalVectorAssemblerType, class VectorType > void addLocalVectorAssembler(const Dune::shared_ptr< const LocalVectorAssemblerType > _localVectorAssembler, Dune::shared_ptr< VectorType > _vector) { typedef LocalVectorAssemblerApplicationWrapper< LocalVectorAssemblerType, VectorType > WrapperType; WrapperType* wrapper = new WrapperType(_localVectorAssembler, _vector); localVectorAssemblers_.push_back(wrapper); } void assemble() const { // common tmp storage for all entities // * for the matrix assemblers std::vector< unsigned int > numberOfTmpMatricesNeeded(2, 0); for (unsigned int ii = 0; ii < localMatrixAssemblers_.size(); ++ii) { const std::vector< unsigned int > tmp = localMatrixAssemblers_[ii]->numTmpObjectsRequired(); numberOfTmpMatricesNeeded[0] = std::max(numberOfTmpMatricesNeeded[0], tmp[0]); numberOfTmpMatricesNeeded[1] = std::max(numberOfTmpMatricesNeeded[1], tmp[1]); } std::vector< LocalMatrixType > tmpLocalAssemblerMatrices( numberOfTmpMatricesNeeded[0], LocalMatrixType(testSpace_.map().maxLocalSize(), ansatzSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< LocalMatrixType > tmpLocalOperatorMatrices(numberOfTmpMatricesNeeded[1], LocalMatrixType(testSpace_.map().maxLocalSize(), ansatzSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< std::vector< LocalMatrixType > > tmpLocalMatricesContainer; tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices); tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices); // * for the vector assemblers std::vector< unsigned int > numberOfTmpVectorsNeeded(2, 0); for (unsigned int ii = 0; ii < localVectorAssemblers_.size(); ++ii) { const std::vector< unsigned int > tmp = localVectorAssemblers_[ii]->numTmpObjectsRequired(); numberOfTmpVectorsNeeded[0] = std::max(numberOfTmpVectorsNeeded[0], tmp[0]); numberOfTmpVectorsNeeded[1] = std::max(numberOfTmpVectorsNeeded[1], tmp[1]); } std::vector< LocalVectorType > tmpLocalAssemblerVectors(numberOfTmpVectorsNeeded[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< LocalVectorType > tmpLocalFunctionalVectors( numberOfTmpVectorsNeeded[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< std::vector< LocalVectorType > > tmpLocalVectorsContainer; tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors); tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors); // walk the grid typedef typename GridViewType::template Codim< 0 >::Iterator EntityIteratorType; for(EntityIteratorType entityIt = ansatzSpace_.gridView().template begin< 0 >(); entityIt != ansatzSpace_.gridView().template end< 0 >(); ++entityIt ) { const EntityType& entity = *entityIt; // assemble local matrices for (unsigned int ii = 0; ii < localMatrixAssemblers_.size(); ++ii) localMatrixAssemblers_[ii]->apply(testSpace_, ansatzSpace_, entity, tmpLocalMatricesContainer); // assemble local vectors for (unsigned int ii = 0; ii < localVectorAssemblers_.size(); ++ii) localVectorAssemblers_[ii]->apply(testSpace_, entity, tmpLocalVectorsContainer); } // walk the grid } // void assemble() const template< class MatrixType, class VectorType > void applyConstraints(MatrixType& matrix, VectorType& vector) const { typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::template Codim< 0 >::EntityType EntityType; typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType; typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType; // walk the grid to apply constraints const ConstraintsType& constraints = testSpace_.constraints(); for(EntityIteratorType entityIterator = testSpace_.gridPart().template begin< 0 >(); entityIterator != testSpace_.gridPart().template end< 0 >(); ++entityIterator ) { const EntityType& entity = *entityIterator; const LocalConstraintsType& localConstraints = constraints.local(entity); applyLocalMatrixConstraints(localConstraints, matrix); applyLocalVectorConstraints(localConstraints, vector); } // walk the grid to apply constraints } // void applyConstraints() private: System(const ThisType&); ThisType& operator=( const ThisType& ); template< class LocalConstraintsType, class MatrixType > void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const { for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) { const unsigned int rowDof = localConstraints.rowDofs(i); for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) { matrix.set(rowDof, localConstraints.columnDofs(j), localConstraints.localMatrix(i,j)); } } } // void applyLocalMatrixConstraints(...) template< class LocalConstraintsType, class VectorType > void applyLocalVectorConstraints( const LocalConstraintsType& localConstraints, VectorType& vector ) const { for( unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i ) { vector.set(localConstraints.rowDofs(i), 0.0); } } // void applyLocalVectorConstraints(...) const TestFunctionSpaceType& testSpace_; const AnsatzFunctionSpaceType& ansatzSpace_; std::vector< LocalMatrixAssemblerApplication* > localMatrixAssemblers_;//!TODO leaks std::vector< LocalVectorAssemblerApplication* > localVectorAssemblers_;//!TODO leaks }; // class System } // namespace Assembler } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH <commit_msg>[assembler.system] added applyMatrixConstraints() and applyVectorConstraints()<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH #include <vector> #include <dune/common/dynmatrix.hh> #include <dune/common/dynvector.hh> #include <dune/common/shared_ptr.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { template< class TestFunctionSpaceImp, class AnsatzFunctionSpaceImp = TestFunctionSpaceImp > class System { public: typedef TestFunctionSpaceImp TestFunctionSpaceType; typedef AnsatzFunctionSpaceImp AnsatzFunctionSpaceType; typedef System< TestFunctionSpaceImp, AnsatzFunctionSpaceImp > ThisType; private: typedef typename TestFunctionSpaceType::GridViewType GridViewType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename TestFunctionSpaceType::FunctionSpaceType::RangeFieldType RangeFieldType; typedef Dune::DynamicMatrix< RangeFieldType > LocalMatrixType; typedef Dune::DynamicVector< RangeFieldType > LocalVectorType; typedef std::vector< std::vector< LocalMatrixType > > LocalMatricesContainerType; typedef std::vector< std::vector< LocalVectorType > > LocalVectorsContainerType; class LocalMatrixAssemblerApplication { public: virtual void apply(const TestFunctionSpaceType& /*_testSpace*/, const AnsatzFunctionSpaceType& /*_ansatzSpace*/, const EntityType& /*_entity*/, LocalMatricesContainerType& /*_localMatricesContainer*/) const = 0; virtual std::vector< unsigned int > numTmpObjectsRequired() const = 0; }; // class LocalOperatorApplication template< class LocalMatrixAssemblerType, class MatrixType > class LocalMatrixAssemblerApplicationWrapper : public LocalMatrixAssemblerApplication { public: LocalMatrixAssemblerApplicationWrapper(const Dune::shared_ptr< const LocalMatrixAssemblerType > _localMatrixAssembler, Dune::shared_ptr< MatrixType > _matrix) : localMatrixAssembler_(_localMatrixAssembler) , matrix_(_matrix) {} virtual void apply(const TestFunctionSpaceType& _testSpace, const AnsatzFunctionSpaceType& _ansatzSpace, const EntityType& _entity, LocalMatricesContainerType& _localMatricesContainer) const { localMatrixAssembler_->assembleLocal(_testSpace, _ansatzSpace, _entity, *matrix_, _localMatricesContainer); } // virtual void applyLocal(...) const virtual std::vector< unsigned int > numTmpObjectsRequired() const { return localMatrixAssembler_->numTmpObjectsRequired(); } // virtual std::vector< unsigned int > numTmpObjectsRequired() const private: const Dune::shared_ptr< const LocalMatrixAssemblerType > localMatrixAssembler_; Dune::shared_ptr< MatrixType > matrix_; }; // class LocalMatrixAssemblerApplicationWrapper class LocalVectorAssemblerApplication { public: virtual void apply(const TestFunctionSpaceType& /*_testSpace*/, const EntityType& /*_entity*/, LocalVectorsContainerType& /*_localMatricesContainer*/) const = 0; virtual std::vector< unsigned int > numTmpObjectsRequired() const = 0; }; // class LocalOperatorApplication template< class LocalVectorAssemblerType, class VectorType > class LocalVectorAssemblerApplicationWrapper : public LocalVectorAssemblerApplication { public: LocalVectorAssemblerApplicationWrapper(const Dune::shared_ptr< const LocalVectorAssemblerType > _localVectorAssembler, Dune::shared_ptr< VectorType > _vector) : localVectorAssembler_(_localVectorAssembler) , vector_(_vector) {} virtual void apply(const TestFunctionSpaceType& _testSpace, const EntityType& _entity, LocalVectorsContainerType& _localVectorsContainer) const { localVectorAssembler_->assembleLocal(_testSpace, _entity, *vector_, _localVectorsContainer); } // virtual void applyLocal(...) const virtual std::vector< unsigned int > numTmpObjectsRequired() const { return localVectorAssembler_->numTmpObjectsRequired(); } // virtual std::vector< unsigned int > numTmpObjectsRequired() const private: const Dune::shared_ptr< const LocalVectorAssemblerType > localVectorAssembler_; Dune::shared_ptr< VectorType > vector_; }; // class LocalMatrixAssemblerApplicationWrapper public: System(const TestFunctionSpaceType& _testSpace, const AnsatzFunctionSpaceType& _ansatzSpace) : testSpace_(_testSpace) , ansatzSpace_(_ansatzSpace) {} System(const TestFunctionSpaceType& _testSpace) : testSpace_(_testSpace) , ansatzSpace_(_testSpace) {} const TestFunctionSpaceType& testSpace() { return testSpace_; } const AnsatzFunctionSpaceType& ansatzSpace() { return ansatzSpace_; } template< class LocalMatrixAssemblerType, class MatrixType > void addLocalMatrixAssembler(const Dune::shared_ptr< const LocalMatrixAssemblerType > _localMatrixAssembler, Dune::shared_ptr< MatrixType > _matrix) { typedef LocalMatrixAssemblerApplicationWrapper< LocalMatrixAssemblerType, MatrixType > WrapperType; WrapperType* wrapper = new WrapperType(_localMatrixAssembler, _matrix); localMatrixAssemblers_.push_back(wrapper); } template< class LocalVectorAssemblerType, class VectorType > void addLocalVectorAssembler(const Dune::shared_ptr< const LocalVectorAssemblerType > _localVectorAssembler, Dune::shared_ptr< VectorType > _vector) { typedef LocalVectorAssemblerApplicationWrapper< LocalVectorAssemblerType, VectorType > WrapperType; WrapperType* wrapper = new WrapperType(_localVectorAssembler, _vector); localVectorAssemblers_.push_back(wrapper); } void assemble() const { // common tmp storage for all entities // * for the matrix assemblers std::vector< unsigned int > numberOfTmpMatricesNeeded(2, 0); for (unsigned int ii = 0; ii < localMatrixAssemblers_.size(); ++ii) { const std::vector< unsigned int > tmp = localMatrixAssemblers_[ii]->numTmpObjectsRequired(); numberOfTmpMatricesNeeded[0] = std::max(numberOfTmpMatricesNeeded[0], tmp[0]); numberOfTmpMatricesNeeded[1] = std::max(numberOfTmpMatricesNeeded[1], tmp[1]); } std::vector< LocalMatrixType > tmpLocalAssemblerMatrices( numberOfTmpMatricesNeeded[0], LocalMatrixType(testSpace_.map().maxLocalSize(), ansatzSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< LocalMatrixType > tmpLocalOperatorMatrices(numberOfTmpMatricesNeeded[1], LocalMatrixType(testSpace_.map().maxLocalSize(), ansatzSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< std::vector< LocalMatrixType > > tmpLocalMatricesContainer; tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices); tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices); // * for the vector assemblers std::vector< unsigned int > numberOfTmpVectorsNeeded(2, 0); for (unsigned int ii = 0; ii < localVectorAssemblers_.size(); ++ii) { const std::vector< unsigned int > tmp = localVectorAssemblers_[ii]->numTmpObjectsRequired(); numberOfTmpVectorsNeeded[0] = std::max(numberOfTmpVectorsNeeded[0], tmp[0]); numberOfTmpVectorsNeeded[1] = std::max(numberOfTmpVectorsNeeded[1], tmp[1]); } std::vector< LocalVectorType > tmpLocalAssemblerVectors(numberOfTmpVectorsNeeded[0], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< LocalVectorType > tmpLocalFunctionalVectors( numberOfTmpVectorsNeeded[1], LocalVectorType(testSpace_.map().maxLocalSize(), RangeFieldType(0))); std::vector< std::vector< LocalVectorType > > tmpLocalVectorsContainer; tmpLocalVectorsContainer.push_back(tmpLocalAssemblerVectors); tmpLocalVectorsContainer.push_back(tmpLocalFunctionalVectors); // walk the grid typedef typename GridViewType::template Codim< 0 >::Iterator EntityIteratorType; for(EntityIteratorType entityIt = ansatzSpace_.gridView().template begin< 0 >(); entityIt != ansatzSpace_.gridView().template end< 0 >(); ++entityIt ) { const EntityType& entity = *entityIt; // assemble local matrices for (unsigned int ii = 0; ii < localMatrixAssemblers_.size(); ++ii) localMatrixAssemblers_[ii]->apply(testSpace_, ansatzSpace_, entity, tmpLocalMatricesContainer); // assemble local vectors for (unsigned int ii = 0; ii < localVectorAssemblers_.size(); ++ii) localVectorAssemblers_[ii]->apply(testSpace_, entity, tmpLocalVectorsContainer); } // walk the grid } // void assemble() const template< class MatrixType, class VectorType > void applyConstraints(MatrixType& matrix, VectorType& vector) const { typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::template Codim< 0 >::EntityType EntityType; typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType; typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType; // walk the grid to apply constraints const ConstraintsType& constraints = testSpace_.constraints(); for(EntityIteratorType entityIterator = testSpace_.gridPart().template begin< 0 >(); entityIterator != testSpace_.gridPart().template end< 0 >(); ++entityIterator ) { const EntityType& entity = *entityIterator; const LocalConstraintsType& localConstraints = constraints.local(entity); applyLocalMatrixConstraints(localConstraints, matrix); applyLocalVectorConstraints(localConstraints, vector); } // walk the grid to apply constraints } // void applyConstraints(MatrixType& matrix, VectorType& vector) const template< class MatrixType > void applyMatrixConstraints(MatrixType& matrix) const { typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::template Codim< 0 >::EntityType EntityType; typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType; typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType; // walk the grid to apply constraints const ConstraintsType& constraints = testSpace_.constraints(); for(EntityIteratorType entityIterator = testSpace_.gridPart().template begin< 0 >(); entityIterator != testSpace_.gridPart().template end< 0 >(); ++entityIterator ) { const EntityType& entity = *entityIterator; const LocalConstraintsType& localConstraints = constraints.local(entity); applyLocalMatrixConstraints(localConstraints, matrix); } // walk the grid to apply constraints } // void applyMatrixConstraints(MatrixType& matrix) const template< class VectorType > void applyVectorConstraints(VectorType& vector) const { typedef typename AnsatzFunctionSpaceType::GridPartType GridPartType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::template Codim< 0 >::EntityType EntityType; typedef typename AnsatzFunctionSpaceType::ConstraintsType ConstraintsType; typedef typename ConstraintsType::LocalConstraintsType LocalConstraintsType; // walk the grid to apply constraints const ConstraintsType& constraints = testSpace_.constraints(); for(EntityIteratorType entityIterator = testSpace_.gridPart().template begin< 0 >(); entityIterator != testSpace_.gridPart().template end< 0 >(); ++entityIterator ) { const EntityType& entity = *entityIterator; const LocalConstraintsType& localConstraints = constraints.local(entity); applyLocalVectorConstraints(localConstraints, vector); } // walk the grid to apply constraints } // void applyVectorConstraints(VectorType& vector) const private: System(const ThisType&); ThisType& operator=( const ThisType& ); template< class LocalConstraintsType, class MatrixType > void applyLocalMatrixConstraints(const LocalConstraintsType& localConstraints, MatrixType& matrix) const { for (unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i) { const unsigned int rowDof = localConstraints.rowDofs(i); for (unsigned int j = 0; j < localConstraints.columnDofsSize(); ++j) { matrix.set(rowDof, localConstraints.columnDofs(j), localConstraints.localMatrix(i,j)); } } } // void applyLocalMatrixConstraints(...) template< class LocalConstraintsType, class VectorType > void applyLocalVectorConstraints( const LocalConstraintsType& localConstraints, VectorType& vector ) const { for( unsigned int i = 0; i < localConstraints.rowDofsSize(); ++i ) { vector.set(localConstraints.rowDofs(i), 0.0); } } // void applyLocalVectorConstraints(...) const TestFunctionSpaceType& testSpace_; const AnsatzFunctionSpaceType& ansatzSpace_; std::vector< LocalMatrixAssemblerApplication* > localMatrixAssemblers_;//!TODO leaks std::vector< LocalVectorAssemblerApplication* > localVectorAssemblers_;//!TODO leaks }; // class System } // namespace Assembler } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_SYSTEM_HH <|endoftext|>
<commit_before>/*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). 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 in the top level directory for details. =============================================================================*/ #include "NiftyLinkTcpClient.h" #include "NiftyLinkTcpNetworkWorker.h" #include <NiftyLinkQThread.h> #include <NiftyLinkUtils.h> #include <igtlMessageBase.h> #include <QsLog.h> namespace niftk { //----------------------------------------------------------------------------- NiftyLinkTcpClient::NiftyLinkTcpClient(QObject *parent) : QObject(parent) , m_Socket(NULL) , m_Worker(NULL) , m_Thread(NULL) { qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); qRegisterMetaType<NiftyLinkMessageContainer::Pointer>("NiftyLinkMessageContainer::Pointer"); qRegisterMetaType<NiftyLinkMessageStatsContainer>("NiftyLinkMessageStatsContainer"); // This is to make sure we have the best possible system timer. #if defined(_WIN32) && !defined(__CYGWIN__) niftk::InitializeWinTimers(); #endif this->setObjectName("NiftyLinkTcpClient"); QLOG_INFO() << QObject::tr("%1::NiftyLinkTcpClient() - constructed.").arg(objectName()); } //----------------------------------------------------------------------------- NiftyLinkTcpClient::~NiftyLinkTcpClient() { QLOG_INFO() << QObject::tr("%1::~NiftyLinkTcpClient() - destroying.").arg(objectName()); // Try to force disconnect. if (this->IsConnected()) { this->DisconnectFromHost(); } // This NiftyLinkTcpClient may be deleted by something external. // So, the thread that we create inside this class needs explicitly asking to stop its event loop. if (!m_Thread->isFinished()) { m_Thread->exit(0); if(!m_Thread->wait(10000)) { QLOG_ERROR() << QObject::tr("%1::~NiftyLinkTcpClient() - failed to shutdown worker thread.").arg(objectName()); } } QLOG_INFO() << QObject::tr("%1::~NiftyLinkTcpClient() - destroyed.").arg(objectName()); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetNumberMessageReceivedThreshold(qint64 threshold) { m_Worker->SetNumberMessageReceivedThreshold(threshold); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetKeepAliveOn(bool isOn) { m_Worker->SetKeepAliveOn(isOn); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetCheckForNoIncomingData(bool isOn) { m_Worker->SetCheckForNoIncomingData(isOn); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OutputStats() { m_Worker->OutputStatsToConsole(); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::RequestStats() { return m_Worker->RequestStats(); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::IsConnected() const { return m_Worker->IsSocketOpen(); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::DisconnectFromHost() { m_Socket->disconnectFromHost(); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::Send(NiftyLinkMessageContainer::Pointer message) { return m_Worker->Send(message); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnMessageReceived(int portNumber) { NiftyLinkMessageContainer::Pointer msg = m_InboundMessages.GetContainer(portNumber); emit MessageReceived(msg); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::ConnectToHost(const QString& hostName, quint16 portNumber) { m_RequestedName = hostName; m_RequestedPort = portNumber; m_Socket = new QTcpSocket(); connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnError())); connect(m_Socket, SIGNAL(disconnected()), this, SLOT(OnDisconnected())); connect(m_Socket, SIGNAL(disconnected()), m_Socket, SLOT(deleteLater())); connect(m_Socket, SIGNAL(connected()), this, SLOT(OnConnected())); // There are no errors reported from this. Listen to the error signal. m_Socket->connectToHost(m_RequestedName, m_RequestedPort); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnError() { QLOG_INFO() << QObject::tr("%1::OnError() - code=%2, string=%3").arg(objectName()).arg(m_Socket->error()).arg(m_Socket->errorString()); emit SocketError(this->m_RequestedName, this->m_RequestedPort, m_Socket->error(), m_Socket->errorString()); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnDisconnected() { emit Disconnected(this->m_RequestedName, this->m_RequestedPort); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnConnected() { this->setObjectName(QObject::tr("NiftyLinkTcpClient(%1:%2)").arg(m_Socket->peerName()).arg(m_Socket->peerPort())); m_Socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_Worker = new NiftyLinkTcpNetworkWorker(&m_InboundMessages, &m_OutboundMessages, m_Socket); connect(m_Worker, SIGNAL(NoIncomingData()), this, SIGNAL(NoIncomingData())); connect(m_Worker, SIGNAL(SentKeepAlive()), this, SIGNAL(SentKeepAlive())); connect(m_Worker, SIGNAL(BytesSent(qint64)), this, SIGNAL(BytesSent(qint64))); connect(m_Worker, SIGNAL(MessageReceived(int)), this, SLOT(OnMessageReceived(int))); m_Thread = new NiftyLinkQThread(); connect(m_Thread, SIGNAL(finished()), m_Thread, SLOT(deleteLater())); // i.e. the event loop of thread deletes it when control returns to this event loop. connect(m_Thread, SIGNAL(finished()), m_Worker, SLOT(deleteLater())); m_Worker->moveToThread(m_Thread); m_Socket->moveToThread(m_Thread); m_Thread->start(); emit Connected(m_Socket->peerName(), m_Socket->peerPort()); } } // end niftk namespace <commit_msg>Bug #3609: Check for socket being open on methods that rely on it.<commit_after>/*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). 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 in the top level directory for details. =============================================================================*/ #include "NiftyLinkTcpClient.h" #include "NiftyLinkTcpNetworkWorker.h" #include <NiftyLinkQThread.h> #include <NiftyLinkUtils.h> #include <igtlMessageBase.h> #include <QsLog.h> #include <cassert> namespace niftk { //----------------------------------------------------------------------------- NiftyLinkTcpClient::NiftyLinkTcpClient(QObject *parent) : QObject(parent) , m_Socket(NULL) , m_Worker(NULL) , m_Thread(NULL) { qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError"); qRegisterMetaType<NiftyLinkMessageContainer::Pointer>("NiftyLinkMessageContainer::Pointer"); qRegisterMetaType<NiftyLinkMessageStatsContainer>("NiftyLinkMessageStatsContainer"); // This is to make sure we have the best possible system timer. #if defined(_WIN32) && !defined(__CYGWIN__) niftk::InitializeWinTimers(); #endif this->setObjectName("NiftyLinkTcpClient"); QLOG_INFO() << QObject::tr("%1::NiftyLinkTcpClient() - constructed.").arg(objectName()); } //----------------------------------------------------------------------------- NiftyLinkTcpClient::~NiftyLinkTcpClient() { QLOG_INFO() << QObject::tr("%1::~NiftyLinkTcpClient() - destroying.").arg(objectName()); // Try to force disconnect. if (this->IsConnected()) { this->DisconnectFromHost(); } // This NiftyLinkTcpClient may be deleted by something external. // So, the thread that we create inside this class needs explicitly asking to stop its event loop. if (m_Thread != NULL && !m_Thread->isFinished()) { m_Thread->exit(0); if(!m_Thread->wait(10000)) { QLOG_ERROR() << QObject::tr("%1::~NiftyLinkTcpClient() - failed to shutdown worker thread.").arg(objectName()); } } QLOG_INFO() << QObject::tr("%1::~NiftyLinkTcpClient() - destroyed.").arg(objectName()); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::IsConnected() const { return m_Socket != NULL && m_Worker != NULL && m_Worker->IsSocketOpen(); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetNumberMessageReceivedThreshold(qint64 threshold) { assert(this->IsConnected()); m_Worker->SetNumberMessageReceivedThreshold(threshold); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetKeepAliveOn(bool isOn) { assert(this->IsConnected()); m_Worker->SetKeepAliveOn(isOn); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::SetCheckForNoIncomingData(bool isOn) { assert(this->IsConnected()); m_Worker->SetCheckForNoIncomingData(isOn); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OutputStats() { assert(this->IsConnected()); m_Worker->OutputStatsToConsole(); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::RequestStats() { assert(this->IsConnected()); return m_Worker->RequestStats(); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::DisconnectFromHost() { assert(this->IsConnected()); m_Socket->disconnectFromHost(); } //----------------------------------------------------------------------------- bool NiftyLinkTcpClient::Send(NiftyLinkMessageContainer::Pointer message) { assert(this->IsConnected()); return m_Worker->Send(message); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnMessageReceived(int portNumber) { NiftyLinkMessageContainer::Pointer msg = m_InboundMessages.GetContainer(portNumber); emit MessageReceived(msg); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::ConnectToHost(const QString& hostName, quint16 portNumber) { m_RequestedName = hostName; m_RequestedPort = portNumber; m_Socket = new QTcpSocket(); connect(m_Socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnError())); connect(m_Socket, SIGNAL(disconnected()), this, SLOT(OnDisconnected())); connect(m_Socket, SIGNAL(disconnected()), m_Socket, SLOT(deleteLater())); connect(m_Socket, SIGNAL(connected()), this, SLOT(OnConnected())); // There are no errors reported from this. Listen to the error signal. m_Socket->connectToHost(m_RequestedName, m_RequestedPort); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnError() { QLOG_INFO() << QObject::tr("%1::OnError() - code=%2, string=%3").arg(objectName()).arg(m_Socket->error()).arg(m_Socket->errorString()); emit SocketError(this->m_RequestedName, this->m_RequestedPort, m_Socket->error(), m_Socket->errorString()); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnDisconnected() { emit Disconnected(this->m_RequestedName, this->m_RequestedPort); } //----------------------------------------------------------------------------- void NiftyLinkTcpClient::OnConnected() { this->setObjectName(QObject::tr("NiftyLinkTcpClient(%1:%2)").arg(m_Socket->peerName()).arg(m_Socket->peerPort())); m_Socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_Worker = new NiftyLinkTcpNetworkWorker(&m_InboundMessages, &m_OutboundMessages, m_Socket); connect(m_Worker, SIGNAL(NoIncomingData()), this, SIGNAL(NoIncomingData())); connect(m_Worker, SIGNAL(SentKeepAlive()), this, SIGNAL(SentKeepAlive())); connect(m_Worker, SIGNAL(BytesSent(qint64)), this, SIGNAL(BytesSent(qint64))); connect(m_Worker, SIGNAL(MessageReceived(int)), this, SLOT(OnMessageReceived(int))); m_Thread = new NiftyLinkQThread(); connect(m_Thread, SIGNAL(finished()), m_Thread, SLOT(deleteLater())); // i.e. the event loop of thread deletes it when control returns to this event loop. connect(m_Thread, SIGNAL(finished()), m_Worker, SLOT(deleteLater())); m_Worker->moveToThread(m_Thread); m_Socket->moveToThread(m_Thread); m_Thread->start(); emit Connected(m_Socket->peerName(), m_Socket->peerPort()); } } // end niftk namespace <|endoftext|>
<commit_before>/// (c) Koheron #include "oscillo.hpp" #include <string.h> #include <thread> #include <chrono> Oscillo::Oscillo(Klib::DevMem& dev_mem_) : dev_mem(dev_mem_) , data_decim(0) { avg_on = false; status = CLOSED; } Oscillo::~Oscillo() { Close(); } int Oscillo::Open() { // Reopening if(status == OPENED) { Close(); } if(status == CLOSED) { config_map = dev_mem.AddMemoryMap(CONFIG_ADDR, CONFIG_RANGE); if (static_cast<int>(config_map) < 0) { status = FAILED; return -1; } status_map = dev_mem.AddMemoryMap(STATUS_ADDR, STATUS_RANGE); if (static_cast<int>(status_map) < 0) { status = FAILED; return -1; } adc_1_map = dev_mem.AddMemoryMap(ADC1_ADDR, ADC1_RANGE); if (static_cast<int>(adc_1_map) < 0) { status = FAILED; return -1; } adc_2_map = dev_mem.AddMemoryMap(ADC2_ADDR, ADC2_RANGE); if (static_cast<int>(adc_2_map) < 0) { status = FAILED; return -1; } raw_data_1 = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_1_map)); raw_data_2 = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_2_map)); status = OPENED; // Reset averaging set_averaging(false); } return 0; } void Oscillo::Close() { if(status == OPENED) { dev_mem.RmMemoryMap(config_map); dev_mem.RmMemoryMap(status_map); dev_mem.RmMemoryMap(adc_1_map); dev_mem.RmMemoryMap(adc_2_map); status = CLOSED; } } void Oscillo::_wait_for_acquisition() { // The overhead of sleep_for might be of the order of our waiting time: // http://stackoverflow.com/questions/18071664/stdthis-threadsleep-for-and-nanoseconds std::this_thread::sleep_for(std::chrono::microseconds(ACQ_TIME_US)); } // http://stackoverflow.com/questions/12276675/modulus-with-negative-numbers-in-c inline long long int mod(long long int k, long long int n) { return ((k %= n) < 0) ? k+n : k; } #define POW_2_31 2147483648 // 2^31 #define POW_2_32 4294967296 // 2^32 inline float _raw_to_float(uint32_t raw) { return float(mod(raw - POW_2_31, POW_2_32) - POW_2_31); } // Read only one channel std::array<float, WFM_SIZE>& Oscillo::read_data(bool channel) { Klib::MemMapID adc_map; channel ? adc_map = adc_1_map : adc_map = adc_2_map; Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); _wait_for_acquisition(); uint32_t *raw_data = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_map)); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i < WFM_SIZE; i++) data[i] = _raw_to_float(raw_data[i]) / num_avg; } else { for(unsigned int i=0; i < WFM_SIZE; i++) data[i] = _raw_to_float(raw_data[i]); } Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); return data; } // Read the two channels std::array<float, 2*WFM_SIZE>& Oscillo::read_all_channels() { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); _wait_for_acquisition(); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i<WFM_SIZE; i++) { data_all[i] = _raw_to_float(raw_data_1[i]) / num_avg; data_all[i + WFM_SIZE] = _raw_to_float(raw_data_2[i]) / num_avg; } } else { for(unsigned int i=0; i<WFM_SIZE; i++) { data_all[i] = _raw_to_float(raw_data_1[i]); data_all[i + WFM_SIZE] = _raw_to_float(raw_data_2[i]); } } return data_all; } // Read the two channels but take only one point every decim_factor points std::vector<float>& Oscillo::read_all_channels_decim(uint32_t decim_factor) { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); uint32_t n_pts = WFM_SIZE/decim_factor; data_decim.resize(2*n_pts); _wait_for_acquisition(); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i<n_pts; i++) { data_decim[i] = _raw_to_float(raw_data_1[decim_factor * i])/num_avg; data_decim[i + n_pts] = _raw_to_float(raw_data_2[decim_factor * i])/num_avg; } } else { for(unsigned int i=0; i<n_pts; i++) { data_decim[i] = _raw_to_float(raw_data_1[decim_factor * i]); data_decim[i + n_pts] = _raw_to_float(raw_data_2[decim_factor * i]); } } Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); return data_decim; } void Oscillo::set_averaging(bool avg_status) { avg_on = avg_status; if(avg_on) { Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+AVG0_OFF, 0); Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+AVG1_OFF, 0); } else { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+AVG0_OFF, 0); Klib::SetBit(dev_mem.GetBaseAddr(config_map)+AVG1_OFF, 0); } } uint32_t Oscillo::get_num_average() { return avg_on ? Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF) : 0; } <commit_msg>fix forgotten clear_bit in oscillo.cpp<commit_after>/// (c) Koheron #include "oscillo.hpp" #include <string.h> #include <thread> #include <chrono> Oscillo::Oscillo(Klib::DevMem& dev_mem_) : dev_mem(dev_mem_) , data_decim(0) { avg_on = false; status = CLOSED; } Oscillo::~Oscillo() { Close(); } int Oscillo::Open() { // Reopening if(status == OPENED) { Close(); } if(status == CLOSED) { config_map = dev_mem.AddMemoryMap(CONFIG_ADDR, CONFIG_RANGE); if (static_cast<int>(config_map) < 0) { status = FAILED; return -1; } status_map = dev_mem.AddMemoryMap(STATUS_ADDR, STATUS_RANGE); if (static_cast<int>(status_map) < 0) { status = FAILED; return -1; } adc_1_map = dev_mem.AddMemoryMap(ADC1_ADDR, ADC1_RANGE); if (static_cast<int>(adc_1_map) < 0) { status = FAILED; return -1; } adc_2_map = dev_mem.AddMemoryMap(ADC2_ADDR, ADC2_RANGE); if (static_cast<int>(adc_2_map) < 0) { status = FAILED; return -1; } raw_data_1 = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_1_map)); raw_data_2 = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_2_map)); status = OPENED; // Reset averaging set_averaging(false); } return 0; } void Oscillo::Close() { if(status == OPENED) { dev_mem.RmMemoryMap(config_map); dev_mem.RmMemoryMap(status_map); dev_mem.RmMemoryMap(adc_1_map); dev_mem.RmMemoryMap(adc_2_map); status = CLOSED; } } void Oscillo::_wait_for_acquisition() { // The overhead of sleep_for might be of the order of our waiting time: // http://stackoverflow.com/questions/18071664/stdthis-threadsleep-for-and-nanoseconds std::this_thread::sleep_for(std::chrono::microseconds(ACQ_TIME_US)); } // http://stackoverflow.com/questions/12276675/modulus-with-negative-numbers-in-c inline long long int mod(long long int k, long long int n) { return ((k %= n) < 0) ? k+n : k; } #define POW_2_31 2147483648 // 2^31 #define POW_2_32 4294967296 // 2^32 inline float _raw_to_float(uint32_t raw) { return float(mod(raw - POW_2_31, POW_2_32) - POW_2_31); } // Read only one channel std::array<float, WFM_SIZE>& Oscillo::read_data(bool channel) { Klib::MemMapID adc_map; channel ? adc_map = adc_1_map : adc_map = adc_2_map; Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); _wait_for_acquisition(); uint32_t *raw_data = reinterpret_cast<uint32_t*>(dev_mem.GetBaseAddr(adc_map)); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i < WFM_SIZE; i++) data[i] = _raw_to_float(raw_data[i]) / num_avg; } else { for(unsigned int i=0; i < WFM_SIZE; i++) data[i] = _raw_to_float(raw_data[i]); } Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); return data; } // Read the two channels std::array<float, 2*WFM_SIZE>& Oscillo::read_all_channels() { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); _wait_for_acquisition(); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i<WFM_SIZE; i++) { data_all[i] = _raw_to_float(raw_data_1[i]) / num_avg; data_all[i + WFM_SIZE] = _raw_to_float(raw_data_2[i]) / num_avg; } } else { for(unsigned int i=0; i<WFM_SIZE; i++) { data_all[i] = _raw_to_float(raw_data_1[i]); data_all[i + WFM_SIZE] = _raw_to_float(raw_data_2[i]); } } Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); return data_all; } // Read the two channels but take only one point every decim_factor points std::vector<float>& Oscillo::read_all_channels_decim(uint32_t decim_factor) { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); uint32_t n_pts = WFM_SIZE/decim_factor; data_decim.resize(2*n_pts); _wait_for_acquisition(); if(avg_on) { float num_avg = float(Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF)); for(unsigned int i=0; i<n_pts; i++) { data_decim[i] = _raw_to_float(raw_data_1[decim_factor * i])/num_avg; data_decim[i + n_pts] = _raw_to_float(raw_data_2[decim_factor * i])/num_avg; } } else { for(unsigned int i=0; i<n_pts; i++) { data_decim[i] = _raw_to_float(raw_data_1[decim_factor * i]); data_decim[i + n_pts] = _raw_to_float(raw_data_2[decim_factor * i]); } } Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+ADDR_OFF, 1); return data_decim; } void Oscillo::set_averaging(bool avg_status) { avg_on = avg_status; if(avg_on) { Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+AVG0_OFF, 0); Klib::ClearBit(dev_mem.GetBaseAddr(config_map)+AVG1_OFF, 0); } else { Klib::SetBit(dev_mem.GetBaseAddr(config_map)+AVG0_OFF, 0); Klib::SetBit(dev_mem.GetBaseAddr(config_map)+AVG1_OFF, 0); } } uint32_t Oscillo::get_num_average() { return avg_on ? Klib::ReadReg32(dev_mem.GetBaseAddr(status_map)+N_AVG1_OFF) : 0; } <|endoftext|>
<commit_before>/* * Copyright 2009 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "sppbfield.hpp" SP_ProtoBufFieldList :: SP_ProtoBufFieldList() { mList = NULL; mCount = mTotal = 0; } SP_ProtoBufFieldList :: ~SP_ProtoBufFieldList() { if( NULL != mList ) { for( int i = 0; i < mCount; i++ ) { Field_t * field = mList + i; if( field->mIsRepeated ) { free( field->mList ); } } free( mList ); mList = NULL; } } void SP_ProtoBufFieldList :: print() { printf( "field count %d\n", mCount ); for( int i = 0; i < mCount; i++ ) { Field_t * field = mList + i; printf( "field#%d: id %d, is.repeated %s", i, field->mFieldNumber, field->mIsRepeated ? "1" : "0" ); if( field->mIsRepeated ) { printf( "\n\toffset " ); for( int j = 0; j < field->mList->mCount; j++ ) { printf( "%d, ", field->mList->mList[j] ); } printf( "\n" ); } else { printf( ", offset %d\n", field->mOffset ); } } printf( "\n" ); } int SP_ProtoBufFieldList :: binarySearch( int fieldNumber, int * insertPoint, int firstIndex, int size ) const { if( NULL == mList ) { if( NULL != insertPoint ) * insertPoint = 0; return -1; } // if aiSize not specify, then search the hold list if( size == -1 ) size = mCount; // can't find the key if( size == 0 ) { // set the insert point if( insertPoint != NULL ) * insertPoint = firstIndex; return -1; // return "can't find" } int cmpRet = fieldNumber - mList[ firstIndex + ( size - 1 ) / 2 ].mFieldNumber; if( cmpRet < 0 ) { return binarySearch( fieldNumber, insertPoint, firstIndex, ( size - 1 ) / 2 ); } else if( cmpRet > 0 ) { return binarySearch( fieldNumber, insertPoint, firstIndex + ( ( size - 1 ) / 2 ) + 1, size - ( ( size - 1 ) / 2 ) - 1 ); } else { // find it return( firstIndex + ( size - 1 ) / 2 ); } } int SP_ProtoBufFieldList :: addField( int fieldNumber, int wireType, int offset ) { int ret = -1; int insertPoint = -1; int index = binarySearch( fieldNumber, &insertPoint, 0, -1 ); if( index >= 0 ) { Field_t * field = &( mList[ index ] ); ensureOffsetList( field, 1 ); OffsetList_t * list = field->mList; list->mList[ list->mCount ] = offset; ++ list->mCount; ret = 1; } else { ensureFieldList( 1 ); memmove( mList + insertPoint + 1, mList + insertPoint, ( mTotal - insertPoint - 1 ) * sizeof( Field_t ) ); Field_t * field = &( mList[ insertPoint ] ); field->mFieldNumber = fieldNumber; field->mWireType = wireType; field->mIsRepeated = 0; field->mOffset = offset; ++mCount; ret = 0; } return ret; } SP_ProtoBufFieldList::Field_t * SP_ProtoBufFieldList :: findField( int fieldNumber ) { Field_t * ret = NULL; int index = binarySearch( fieldNumber, NULL, 0, -1 ); if( index >= 0 ) ret = &( mList[ index ] ); return ret; } int SP_ProtoBufFieldList :: getFieldCount() { return mCount; } SP_ProtoBufFieldList::Field_t * SP_ProtoBufFieldList :: getField( int index ) { Field_t * ret = NULL; if( index >= 0 && index < mCount ) ret = &( mList[ index ] ); return ret; } int SP_ProtoBufFieldList :: ensureFieldList( int count ) { int need = mCount + count; if( need > mTotal ) { int total = mTotal < 16 ? 16 : mTotal; for( ; total < need; ) total = total * 2; Field_t * tmp = (Field_t*)realloc( mList, sizeof( Field_t ) * total ); if( NULL == tmp ) return -1; mList = tmp; mTotal = total; } return 0; } int SP_ProtoBufFieldList :: ensureOffsetList( Field_t * field, int count ) { int need = 0, total = 0; if( field->mIsRepeated ) { need = field->mList->mCount + count; total = field->mList->mTotal; } else { need = count + 1; total = 0; } if( need > total ) { total = total < 8 ? 8 : total; for( ; total < need; ) total = total * 2; OffsetList_t * newList = (OffsetList_t*)malloc( total * sizeof( int ) + sizeof( OffsetList_t ) ); newList->mTotal = total; if( field->mIsRepeated ) { OffsetList_t * oldList = field->mList; memcpy( newList, oldList, sizeof( int ) * oldList->mTotal + sizeof( OffsetList_t ) ); field->mList = newList; free( oldList ); } else { newList->mList[0] = field->mOffset; newList->mCount = 1; field->mIsRepeated = 1; field->mList = newList; } } return 0; } <commit_msg>correct the total count of the offset list<commit_after>/* * Copyright 2009 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "sppbfield.hpp" SP_ProtoBufFieldList :: SP_ProtoBufFieldList() { mList = NULL; mCount = mTotal = 0; } SP_ProtoBufFieldList :: ~SP_ProtoBufFieldList() { if( NULL != mList ) { for( int i = 0; i < mCount; i++ ) { Field_t * field = mList + i; if( field->mIsRepeated ) { free( field->mList ); } } free( mList ); mList = NULL; } } void SP_ProtoBufFieldList :: print() { printf( "field count %d\n", mCount ); for( int i = 0; i < mCount; i++ ) { Field_t * field = mList + i; printf( "field#%d: id %d, is.repeated %s", i, field->mFieldNumber, field->mIsRepeated ? "1" : "0" ); if( field->mIsRepeated ) { printf( "\n\toffset " ); for( int j = 0; j < field->mList->mCount; j++ ) { printf( "%d, ", field->mList->mList[j] ); } printf( "\n" ); } else { printf( ", offset %d\n", field->mOffset ); } } printf( "\n" ); } int SP_ProtoBufFieldList :: binarySearch( int fieldNumber, int * insertPoint, int firstIndex, int size ) const { if( NULL == mList ) { if( NULL != insertPoint ) * insertPoint = 0; return -1; } // if aiSize not specify, then search the hold list if( size == -1 ) size = mCount; // can't find the key if( size == 0 ) { // set the insert point if( insertPoint != NULL ) * insertPoint = firstIndex; return -1; // return "can't find" } int cmpRet = fieldNumber - mList[ firstIndex + ( size - 1 ) / 2 ].mFieldNumber; if( cmpRet < 0 ) { return binarySearch( fieldNumber, insertPoint, firstIndex, ( size - 1 ) / 2 ); } else if( cmpRet > 0 ) { return binarySearch( fieldNumber, insertPoint, firstIndex + ( ( size - 1 ) / 2 ) + 1, size - ( ( size - 1 ) / 2 ) - 1 ); } else { // find it return( firstIndex + ( size - 1 ) / 2 ); } } int SP_ProtoBufFieldList :: addField( int fieldNumber, int wireType, int offset ) { int ret = -1; int insertPoint = -1; int index = binarySearch( fieldNumber, &insertPoint, 0, -1 ); if( index >= 0 ) { Field_t * field = &( mList[ index ] ); ensureOffsetList( field, 1 ); OffsetList_t * list = field->mList; list->mList[ list->mCount ] = offset; ++ list->mCount; ret = 1; } else { ensureFieldList( 1 ); memmove( mList + insertPoint + 1, mList + insertPoint, ( mTotal - insertPoint - 1 ) * sizeof( Field_t ) ); Field_t * field = &( mList[ insertPoint ] ); field->mFieldNumber = fieldNumber; field->mWireType = wireType; field->mIsRepeated = 0; field->mOffset = offset; ++mCount; ret = 0; } return ret; } SP_ProtoBufFieldList::Field_t * SP_ProtoBufFieldList :: findField( int fieldNumber ) { Field_t * ret = NULL; int index = binarySearch( fieldNumber, NULL, 0, -1 ); if( index >= 0 ) ret = &( mList[ index ] ); return ret; } int SP_ProtoBufFieldList :: getFieldCount() { return mCount; } SP_ProtoBufFieldList::Field_t * SP_ProtoBufFieldList :: getField( int index ) { Field_t * ret = NULL; if( index >= 0 && index < mCount ) ret = &( mList[ index ] ); return ret; } int SP_ProtoBufFieldList :: ensureFieldList( int count ) { int need = mCount + count; if( need > mTotal ) { int total = mTotal < 16 ? 16 : mTotal; for( ; total < need; ) total = total * 2; Field_t * tmp = (Field_t*)realloc( mList, sizeof( Field_t ) * total ); if( NULL == tmp ) return -1; mList = tmp; mTotal = total; } return 0; } int SP_ProtoBufFieldList :: ensureOffsetList( Field_t * field, int count ) { int need = 0, total = 0; if( field->mIsRepeated ) { need = field->mList->mCount + count; total = field->mList->mTotal; } else { need = count + 1; total = 0; } if( need > total ) { total = total < 8 ? 8 : total; for( ; total < need; ) total = total * 2; OffsetList_t * newList = (OffsetList_t*)malloc( total * sizeof( int ) + sizeof( OffsetList_t ) ); if( field->mIsRepeated ) { OffsetList_t * oldList = field->mList; memcpy( newList, oldList, sizeof( int ) * oldList->mTotal + sizeof( OffsetList_t ) ); newList->mTotal = total; field->mList = newList; free( oldList ); } else { newList->mList[0] = field->mOffset; newList->mCount = 1; newList->mTotal = total; field->mIsRepeated = 1; field->mList = newList; } } return 0; } <|endoftext|>
<commit_before>#include "opt/data_flow_collector.h" #include "iroha/i_design.h" #include "opt/bb_set.h" #include "opt/data_flow.h" #include "opt/optimizer_log.h" namespace iroha { namespace opt { DataFlowCollector::DataFlowCollector(BBSet *bbs, OptimizerLog *opt_log) : bbs_(bbs), opt_log_(opt_log) {} DataFlow *DataFlowCollector::Create() { for (auto *bb : bbs_->bbs_) { BBInfo *info = new BBInfo; info->bb_ = bb; bb_info_[bb] = info; } df_ = new DataFlow; for (auto p : bb_info_) { CollectDefs(p.second); } for (auto p : bb_info_) { CollectKills(p.second); } CollectReaches(); CopyReaches(); if (opt_log_->IsEnabled()) { Log(opt_log_->Table(bbs_->GetTable())); } return df_; } void DataFlowCollector::Log(ostream &os) { for (auto p : bb_info_) { os << "bb:" << p.first->bb_id_ << "<br>\n"; for (auto *reg_def : p.second->reaches_) { os << " def: insn:" << reg_def->insn->GetId() << " reg: " << reg_def->reg->GetName() << "<br>\n"; } } } void DataFlowCollector::CollectDefs(BBInfo *info) { for (IState *st : info->bb_->states_) { for (IInsn *insn : st->insns_) { int nth_output = 0; for (IRegister *oreg : insn->outputs_) { if (!(oreg->IsConst() || oreg->IsStateLocal())) { // Normal register. RegDef *reg_def = new RegDef; reg_def->reg = oreg; reg_def->insn = insn; reg_def->output_index = nth_output; reg_def->st = st; reg_def->bb = info->bb_; df_->all_defs_.push_back(reg_def); info->last_defs_[oreg] = reg_def; } ++nth_output; } } } } void DataFlowCollector::CollectKills(BBInfo *info) { for (RegDef *reg_def : df_->all_defs_) { if (info->bb_ == reg_def->bb) { continue; } if (info->last_defs_.find(reg_def->reg) == info->last_defs_.end()) { continue; } info->kills_.push_back(reg_def); } } void DataFlowCollector::CollectReaches() { bool changed; do { changed = false; for (auto p : bb_info_) { BBInfo *info = p.second; set<RegDef *> temp; for (BB *prev_bb : info->bb_->prev_bbs_) { BBInfo *prev_bb_info = bb_info_[prev_bb]; CollectPropagates(prev_bb_info, &temp); } if (temp.size() > info->reaches_.size()) { changed = true; info->reaches_ = temp; } } } while (changed); } void DataFlowCollector::CopyReaches() { for (auto p : bb_info_) { BBInfo *info = p.second; for (RegDef *reg_def : info->reaches_) { df_->reaches_.insert(make_pair(info->bb_, reg_def)); } } } void DataFlowCollector::CollectPropagates(BBInfo *prev_bb_info, set<RegDef *> *prop) { // DEF(P) for (auto e : prev_bb_info->last_defs_) { prop->insert(e.second); } // REACH(P) - KILL(P) set<RegDef *> defs; for (RegDef *r : prev_bb_info->reaches_) { defs.insert(r); } for (RegDef *k : prev_bb_info->kills_) { defs.erase(k); } for (RegDef *r : defs) { prop->insert(r); } } } // namespace opt } // namespace iroha <commit_msg>Tidy up data flow print.<commit_after>#include "opt/data_flow_collector.h" #include "iroha/i_design.h" #include "opt/bb_set.h" #include "opt/data_flow.h" #include "opt/optimizer_log.h" namespace iroha { namespace opt { DataFlowCollector::DataFlowCollector(BBSet *bbs, OptimizerLog *opt_log) : bbs_(bbs), opt_log_(opt_log) {} DataFlow *DataFlowCollector::Create() { for (auto *bb : bbs_->bbs_) { BBInfo *info = new BBInfo; info->bb_ = bb; bb_info_[bb] = info; } df_ = new DataFlow; for (auto p : bb_info_) { CollectDefs(p.second); } for (auto p : bb_info_) { CollectKills(p.second); } CollectReaches(); CopyReaches(); if (opt_log_->IsEnabled()) { Log(opt_log_->Table(bbs_->GetTable())); } return df_; } void DataFlowCollector::Log(ostream &os) { os << "Data flow<br/>\n"; for (auto p : bb_info_) { os << "bb:" << p.first->bb_id_ << "<br>\n"; for (auto *reg_def : p.second->reaches_) { IRegister *reg = reg_def->reg; os << " def: insn:" << reg_def->insn->GetId() << " reg:" << reg->GetId() << " " << reg->GetName() << "<br>\n"; } } } void DataFlowCollector::CollectDefs(BBInfo *info) { for (IState *st : info->bb_->states_) { for (IInsn *insn : st->insns_) { int nth_output = 0; for (IRegister *oreg : insn->outputs_) { if (!(oreg->IsConst() || oreg->IsStateLocal())) { // Normal register. RegDef *reg_def = new RegDef; reg_def->reg = oreg; reg_def->insn = insn; reg_def->output_index = nth_output; reg_def->st = st; reg_def->bb = info->bb_; df_->all_defs_.push_back(reg_def); info->last_defs_[oreg] = reg_def; } ++nth_output; } } } } void DataFlowCollector::CollectKills(BBInfo *info) { for (RegDef *reg_def : df_->all_defs_) { if (info->bb_ == reg_def->bb) { continue; } if (info->last_defs_.find(reg_def->reg) == info->last_defs_.end()) { continue; } info->kills_.push_back(reg_def); } } void DataFlowCollector::CollectReaches() { bool changed; do { changed = false; for (auto p : bb_info_) { BBInfo *info = p.second; set<RegDef *> temp; for (BB *prev_bb : info->bb_->prev_bbs_) { BBInfo *prev_bb_info = bb_info_[prev_bb]; CollectPropagates(prev_bb_info, &temp); } if (temp.size() > info->reaches_.size()) { changed = true; info->reaches_ = temp; } } } while (changed); } void DataFlowCollector::CopyReaches() { for (auto p : bb_info_) { BBInfo *info = p.second; for (RegDef *reg_def : info->reaches_) { df_->reaches_.insert(make_pair(info->bb_, reg_def)); } } } void DataFlowCollector::CollectPropagates(BBInfo *prev_bb_info, set<RegDef *> *prop) { // DEF(P) for (auto e : prev_bb_info->last_defs_) { prop->insert(e.second); } // REACH(P) - KILL(P) set<RegDef *> defs; for (RegDef *r : prev_bb_info->reaches_) { defs.insert(r); } for (RegDef *k : prev_bb_info->kills_) { defs.erase(k); } for (RegDef *r : defs) { prop->insert(r); } } } // namespace opt } // namespace iroha <|endoftext|>
<commit_before> #include "JournalingObjectStore.h" #include "config.h" #define DOUT_SUBSYS journal #undef dout_prefix #define dout_prefix *_dout << dbeginl << "journal " void JournalingObjectStore::journal_start() { dout(10) << "journal_start" << dendl; finisher.start(); } void JournalingObjectStore::journal_stop() { dout(10) << "journal_stop" << dendl; finisher.stop(); if (journal) { journal->close(); delete journal; journal = 0; } } int JournalingObjectStore::journal_replay(uint64_t fs_op_seq) { dout(10) << "journal_replay fs op_seq " << fs_op_seq << dendl; op_seq = fs_op_seq; committed_seq = op_seq; applied_seq = fs_op_seq; if (!journal) return 0; int err = journal->open(op_seq+1); if (err < 0) { char buf[80]; dout(3) << "journal_replay open failed with " << strerror_r(-err, buf, sizeof(buf)) << dendl; delete journal; journal = 0; return err; } int count = 0; while (1) { bufferlist bl; uint64_t seq = op_seq + 1; if (!journal->read_entry(bl, seq)) { dout(3) << "journal_replay: end of journal, done." << dendl; break; } if (seq <= op_seq) { dout(3) << "journal_replay: skipping old op seq " << seq << " <= " << op_seq << dendl; continue; } assert(op_seq == seq-1); dout(3) << "journal_replay: applying op seq " << seq << " (op_seq " << op_seq << ")" << dendl; bufferlist::iterator p = bl.begin(); list<Transaction*> tls; while (!p.end()) { Transaction *t = new Transaction(p); tls.push_back(t); } int r = do_transactions(tls, op_seq); op_seq++; while (!tls.empty()) { delete tls.front(); tls.pop_front(); } dout(3) << "journal_replay: r = " << r << ", op now seq " << op_seq << dendl; assert(op_seq == seq); seq++; // we expect the next op } committed_seq = op_seq; applied_seq = op_seq; // done reading, make writeable. journal->make_writeable(); return count; } // ------------------------------------ uint64_t JournalingObjectStore::op_apply_start(uint64_t op) { Mutex::Locker l(journal_lock); return _op_apply_start(op); } uint64_t JournalingObjectStore::_op_apply_start(uint64_t op) { assert(journal_lock.is_locked()); if (blocked) { Cond cond; ops_apply_blocked.push_back(&cond); dout(10) << "op_apply_start " << op << " blocked (getting in back of line)" << dendl; while (blocked && ops_apply_blocked.front() != &cond) cond.Wait(journal_lock); dout(10) << "op_apply_start " << op << " woke (at front of line)" << dendl; ops_apply_blocked.pop_front(); if (!ops_apply_blocked.empty()) { dout(10) << "op_apply_start " << op << " ...and kicking next in line" << dendl; ops_apply_blocked.front()->Signal(); } } else { dout(10) << "op_apply_start " << op << dendl; } open_ops++; return op; } void JournalingObjectStore::op_apply_finish(uint64_t op) { dout(10) << "op_apply_finish " << op << dendl; journal_lock.Lock(); if (--open_ops == 0) cond.Signal(); // there can be multiple applies in flight; track the max value we // note. note that we can't _read_ this value and learn anything // meaningful unless/until we've quiesced all in-flight applies. if (op > applied_seq) applied_seq = op; journal_lock.Unlock(); } uint64_t JournalingObjectStore::op_submit_start() { journal_lock.Lock(); uint64_t op = ++op_seq; dout(10) << "op_submit_start " << op << dendl; ops_submitting.push_back(op); return op; } void JournalingObjectStore::op_submit_finish(uint64_t op) { dout(10) << "op_submit_finish " << op << dendl; if (op != ops_submitting.front()) { dout(0) << "op_submit_finish " << op << " expected " << ops_submitting.front() << ", OUT OF ORDER" << dendl; } ops_submitting.pop_front(); journal_lock.Unlock(); } // ------------------------------------------ bool JournalingObjectStore::commit_start() { bool ret = false; journal_lock.Lock(); dout(10) << "commit_start op_seq " << op_seq << ", applied_seq " << applied_seq << ", committed_seq " << committed_seq << dendl; blocked = true; while (open_ops > 0) { dout(10) << "commit_start blocked, waiting for " << open_ops << " open ops" << dendl; cond.Wait(journal_lock); } if (applied_seq == committed_seq) { dout(10) << "commit_start nothing to do" << dendl; blocked = false; if (!ops_apply_blocked.empty()) ops_apply_blocked.front()->Signal(); assert(commit_waiters.empty()); goto out; } // we can _only_ read applied_seq here because open_ops == 0 (we've // quiesced all in-flight applies). committing_seq = applied_seq; dout(10) << "commit_start committing " << committing_seq << ", still blocked" << dendl; ret = true; out: journal->commit_start(); // tell the journal too journal_lock.Unlock(); return ret; } void JournalingObjectStore::commit_started() { Mutex::Locker l(journal_lock); // allow new ops. (underlying fs should now be committing all prior ops) dout(10) << "commit_started committing " << committing_seq << ", unblocking" << dendl; blocked = false; if (!ops_apply_blocked.empty()) ops_apply_blocked.front()->Signal(); } void JournalingObjectStore::commit_finish() { Mutex::Locker l(journal_lock); dout(10) << "commit_finish thru " << committing_seq << dendl; if (journal) journal->committed_thru(committing_seq); committed_seq = committing_seq; map<version_t, vector<Context*> >::iterator p = commit_waiters.begin(); while (p != commit_waiters.end() && p->first <= committing_seq) { finisher.queue(p->second); commit_waiters.erase(p++); } } void JournalingObjectStore::op_journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op, Context *onjournal) { Mutex::Locker l(journal_lock); _op_journal_transactions(tls, op, onjournal); } void JournalingObjectStore::_op_journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op, Context *onjournal) { assert(journal_lock.is_locked()); dout(10) << "op_journal_transactions " << op << dendl; if (journal && journal->is_writeable()) { bufferlist tbl; unsigned data_len = 0, data_align = 0; for (list<ObjectStore::Transaction*>::iterator p = tls.begin(); p != tls.end(); p++) { ObjectStore::Transaction *t = *p; if (t->get_data_length() > data_len && (int)t->get_data_length() >= g_conf.journal_align_min_size) { data_len = t->get_data_length(); data_align = (t->get_data_alignment() - tbl.length()) & ~PAGE_MASK; } t->encode(tbl); } journal->submit_entry(op, tbl, data_align, onjournal); } else if (onjournal) commit_waiters[op].push_back(onjournal); } <commit_msg>filestore: assert on out of order journal pipeline submissions<commit_after> #include "JournalingObjectStore.h" #include "config.h" #define DOUT_SUBSYS journal #undef dout_prefix #define dout_prefix *_dout << dbeginl << "journal " void JournalingObjectStore::journal_start() { dout(10) << "journal_start" << dendl; finisher.start(); } void JournalingObjectStore::journal_stop() { dout(10) << "journal_stop" << dendl; finisher.stop(); if (journal) { journal->close(); delete journal; journal = 0; } } int JournalingObjectStore::journal_replay(uint64_t fs_op_seq) { dout(10) << "journal_replay fs op_seq " << fs_op_seq << dendl; op_seq = fs_op_seq; committed_seq = op_seq; applied_seq = fs_op_seq; if (!journal) return 0; int err = journal->open(op_seq+1); if (err < 0) { char buf[80]; dout(3) << "journal_replay open failed with " << strerror_r(-err, buf, sizeof(buf)) << dendl; delete journal; journal = 0; return err; } int count = 0; while (1) { bufferlist bl; uint64_t seq = op_seq + 1; if (!journal->read_entry(bl, seq)) { dout(3) << "journal_replay: end of journal, done." << dendl; break; } if (seq <= op_seq) { dout(3) << "journal_replay: skipping old op seq " << seq << " <= " << op_seq << dendl; continue; } assert(op_seq == seq-1); dout(3) << "journal_replay: applying op seq " << seq << " (op_seq " << op_seq << ")" << dendl; bufferlist::iterator p = bl.begin(); list<Transaction*> tls; while (!p.end()) { Transaction *t = new Transaction(p); tls.push_back(t); } int r = do_transactions(tls, op_seq); op_seq++; while (!tls.empty()) { delete tls.front(); tls.pop_front(); } dout(3) << "journal_replay: r = " << r << ", op now seq " << op_seq << dendl; assert(op_seq == seq); seq++; // we expect the next op } committed_seq = op_seq; applied_seq = op_seq; // done reading, make writeable. journal->make_writeable(); return count; } // ------------------------------------ uint64_t JournalingObjectStore::op_apply_start(uint64_t op) { Mutex::Locker l(journal_lock); return _op_apply_start(op); } uint64_t JournalingObjectStore::_op_apply_start(uint64_t op) { assert(journal_lock.is_locked()); if (blocked) { Cond cond; ops_apply_blocked.push_back(&cond); dout(10) << "op_apply_start " << op << " blocked (getting in back of line)" << dendl; while (blocked && ops_apply_blocked.front() != &cond) cond.Wait(journal_lock); dout(10) << "op_apply_start " << op << " woke (at front of line)" << dendl; ops_apply_blocked.pop_front(); if (!ops_apply_blocked.empty()) { dout(10) << "op_apply_start " << op << " ...and kicking next in line" << dendl; ops_apply_blocked.front()->Signal(); } } else { dout(10) << "op_apply_start " << op << dendl; } open_ops++; return op; } void JournalingObjectStore::op_apply_finish(uint64_t op) { dout(10) << "op_apply_finish " << op << dendl; journal_lock.Lock(); if (--open_ops == 0) cond.Signal(); // there can be multiple applies in flight; track the max value we // note. note that we can't _read_ this value and learn anything // meaningful unless/until we've quiesced all in-flight applies. if (op > applied_seq) applied_seq = op; journal_lock.Unlock(); } uint64_t JournalingObjectStore::op_submit_start() { journal_lock.Lock(); uint64_t op = ++op_seq; dout(10) << "op_submit_start " << op << dendl; ops_submitting.push_back(op); return op; } void JournalingObjectStore::op_submit_finish(uint64_t op) { dout(10) << "op_submit_finish " << op << dendl; if (op != ops_submitting.front()) { dout(0) << "op_submit_finish " << op << " expected " << ops_submitting.front() << ", OUT OF ORDER" << dendl; assert(0 == "out of order op_submit_finish"); } ops_submitting.pop_front(); journal_lock.Unlock(); } // ------------------------------------------ bool JournalingObjectStore::commit_start() { bool ret = false; journal_lock.Lock(); dout(10) << "commit_start op_seq " << op_seq << ", applied_seq " << applied_seq << ", committed_seq " << committed_seq << dendl; blocked = true; while (open_ops > 0) { dout(10) << "commit_start blocked, waiting for " << open_ops << " open ops" << dendl; cond.Wait(journal_lock); } if (applied_seq == committed_seq) { dout(10) << "commit_start nothing to do" << dendl; blocked = false; if (!ops_apply_blocked.empty()) ops_apply_blocked.front()->Signal(); assert(commit_waiters.empty()); goto out; } // we can _only_ read applied_seq here because open_ops == 0 (we've // quiesced all in-flight applies). committing_seq = applied_seq; dout(10) << "commit_start committing " << committing_seq << ", still blocked" << dendl; ret = true; out: journal->commit_start(); // tell the journal too journal_lock.Unlock(); return ret; } void JournalingObjectStore::commit_started() { Mutex::Locker l(journal_lock); // allow new ops. (underlying fs should now be committing all prior ops) dout(10) << "commit_started committing " << committing_seq << ", unblocking" << dendl; blocked = false; if (!ops_apply_blocked.empty()) ops_apply_blocked.front()->Signal(); } void JournalingObjectStore::commit_finish() { Mutex::Locker l(journal_lock); dout(10) << "commit_finish thru " << committing_seq << dendl; if (journal) journal->committed_thru(committing_seq); committed_seq = committing_seq; map<version_t, vector<Context*> >::iterator p = commit_waiters.begin(); while (p != commit_waiters.end() && p->first <= committing_seq) { finisher.queue(p->second); commit_waiters.erase(p++); } } void JournalingObjectStore::op_journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op, Context *onjournal) { Mutex::Locker l(journal_lock); _op_journal_transactions(tls, op, onjournal); } void JournalingObjectStore::_op_journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op, Context *onjournal) { assert(journal_lock.is_locked()); dout(10) << "op_journal_transactions " << op << dendl; if (journal && journal->is_writeable()) { bufferlist tbl; unsigned data_len = 0, data_align = 0; for (list<ObjectStore::Transaction*>::iterator p = tls.begin(); p != tls.end(); p++) { ObjectStore::Transaction *t = *p; if (t->get_data_length() > data_len && (int)t->get_data_length() >= g_conf.journal_align_min_size) { data_len = t->get_data_length(); data_align = (t->get_data_alignment() - tbl.length()) & ~PAGE_MASK; } t->encode(tbl); } journal->submit_entry(op, tbl, data_align, onjournal); } else if (onjournal) commit_waiters[op].push_back(onjournal); } <|endoftext|>
<commit_before>/********************************************************************** * * FILE: PagedLOD.cpp * * DESCRIPTION: Read/Write osg::PagedLOD in binary format to disk. * * CREATED BY: Auto generated by iveGenerate * and later modified by Rune Schmidt Jensen. * * HISTORY: Created 24.3.2003 * * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" #include "PagedLOD.h" #include "Node.h" using namespace ive; void PagedLOD::write(DataOutputStream* out){ // Write LOD's identification. out->writeInt(IVEPAGEDLOD); // If the osg class is inherited by any other class we should also write this to file. osg::Node* node = dynamic_cast<osg::Node*>(this); if(node){ static_cast<ive::Node*>(node)->write(out); } else throw Exception("PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD."); out->writeString(getDatabasePath()); out->writeFloat(getRadius()); out->writeUInt(getNumChildrenThatCannotBeExpired()); unsigned int numChildrenToWriteOut = 0; int i; for(i=0; i<(int)getNumFileNames();++i) { if (getFileName(i).empty()) { ++numChildrenToWriteOut; } } // Write Group's properties. // Write number of children. out->writeInt(numChildrenToWriteOut); // Write children. for(i=0; i<(int)getNumChildren(); i++){ if (getFileName(i).empty()) { osg::Node* child = getChild(i); out->writeNode(child); } } // LOD properties // Write centermode out->writeInt(getCenterMode()); out->writeVec3(getCenter()); out->writeInt(getRangeMode()); // Write rangelist int size = getNumRanges(); out->writeInt(size); for(i=0;i<size;i++){ out->writeFloat(getMinRange(i)); out->writeFloat(getMaxRange(i)); } // PagedLOD properties size = getNumFileNames(); out->writeInt(size); for(i=0;i<size;i++){ out->writeString(getFileName(i)); } } void PagedLOD::read(DataInputStream* in){ // Peek on LOD's identification. int id = in->peekInt(); if(id == IVEPAGEDLOD){ // Read LOD's identification. id = in->readInt(); // If the osg class is inherited by any other class we should also read this from file. osg::Node* node = dynamic_cast<osg::Node*>(this); if(node){ ((ive::Node*)(node))->read(in); } else throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node."); if ( in->getVersion() > VERSION_0006 ) { setDatabasePath(in->readString()); } if (getDatabasePath().empty() && in->getOptions() && !in->getOptions()->getDatabasePathList().empty()) { const std::string& path = in->getOptions()->getDatabasePathList().front(); if (!path.empty()) { setDatabasePath(path); } } setRadius(in->readFloat()); setNumChildrenThatCannotBeExpired(in->readUInt()); // Read groups properties. // Read number of children. int size = in->readInt(); // Read children. int i; for(i=0; i<size; i++) { addChild(in->readNode()); } // Read centermode setCenterMode((osg::LOD::CenterMode)in->readInt()); setCenter(in->readVec3()); setRangeMode((RangeMode)in->readInt()); // Read rangelist size = in->readInt(); for(i=0;i<size;i++){ float min = in->readFloat(); float max = in->readFloat(); setRange(i, min, max); } size = in->readInt(); for(i=0;i<size;i++){ setFileName(i, in->readString()); } } else{ throw Exception("LOD::read(): Expected LOD identification."); } } <commit_msg>CHanged line 101 in PageLOD.cpp to read if ( in->getVersion() >= VERSION_0006 ) { setDatabasePath(in->readString()); }<commit_after>/********************************************************************** * * FILE: PagedLOD.cpp * * DESCRIPTION: Read/Write osg::PagedLOD in binary format to disk. * * CREATED BY: Auto generated by iveGenerate * and later modified by Rune Schmidt Jensen. * * HISTORY: Created 24.3.2003 * * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" #include "PagedLOD.h" #include "Node.h" using namespace ive; void PagedLOD::write(DataOutputStream* out){ // Write LOD's identification. out->writeInt(IVEPAGEDLOD); // If the osg class is inherited by any other class we should also write this to file. osg::Node* node = dynamic_cast<osg::Node*>(this); if(node){ static_cast<ive::Node*>(node)->write(out); } else throw Exception("PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD."); out->writeString(getDatabasePath()); out->writeFloat(getRadius()); out->writeUInt(getNumChildrenThatCannotBeExpired()); unsigned int numChildrenToWriteOut = 0; int i; for(i=0; i<(int)getNumFileNames();++i) { if (getFileName(i).empty()) { ++numChildrenToWriteOut; } } // Write Group's properties. // Write number of children. out->writeInt(numChildrenToWriteOut); // Write children. for(i=0; i<(int)getNumChildren(); i++){ if (getFileName(i).empty()) { osg::Node* child = getChild(i); out->writeNode(child); } } // LOD properties // Write centermode out->writeInt(getCenterMode()); out->writeVec3(getCenter()); out->writeInt(getRangeMode()); // Write rangelist int size = getNumRanges(); out->writeInt(size); for(i=0;i<size;i++){ out->writeFloat(getMinRange(i)); out->writeFloat(getMaxRange(i)); } // PagedLOD properties size = getNumFileNames(); out->writeInt(size); for(i=0;i<size;i++){ out->writeString(getFileName(i)); } } void PagedLOD::read(DataInputStream* in){ // Peek on LOD's identification. int id = in->peekInt(); if(id == IVEPAGEDLOD){ // Read LOD's identification. id = in->readInt(); // If the osg class is inherited by any other class we should also read this from file. osg::Node* node = dynamic_cast<osg::Node*>(this); if(node){ ((ive::Node*)(node))->read(in); } else throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node."); if ( in->getVersion() >= VERSION_0006 ) { setDatabasePath(in->readString()); } if (getDatabasePath().empty() && in->getOptions() && !in->getOptions()->getDatabasePathList().empty()) { const std::string& path = in->getOptions()->getDatabasePathList().front(); if (!path.empty()) { setDatabasePath(path); } } setRadius(in->readFloat()); setNumChildrenThatCannotBeExpired(in->readUInt()); // Read groups properties. // Read number of children. int size = in->readInt(); // Read children. int i; for(i=0; i<size; i++) { addChild(in->readNode()); } // Read centermode setCenterMode((osg::LOD::CenterMode)in->readInt()); setCenter(in->readVec3()); setRangeMode((RangeMode)in->readInt()); // Read rangelist size = in->readInt(); for(i=0;i<size;i++){ float min = in->readFloat(); float max = in->readFloat(); setRange(i, min, max); } size = in->readInt(); for(i=0;i<size;i++){ setFileName(i, in->readString()); } } else{ throw Exception("LOD::read(): Expected LOD identification."); } } <|endoftext|>
<commit_before>//Hold the runtime statistics. E.g. how long was spent in simplification. //The times don't add up to the runtime, because we allow multiple times to //be counted simultaneously. For example, the current Transform()s call //Simplify_TopLevel, so inside simplify time will be counted towards both //Simplify_TopLevel & Transform. // This is intended as a low overhead profiling class. So runtimes can // always be tracked. #include <cassert> #include <sys/time.h> #include <sstream> #include <iostream> #include <utility> #include "RunTimes.h" #include "../sat/utils/System.h" // BE VERY CAREFUL> Update the Category Names to match. std::string RunTimes::CategoryNames[] = { "Transforming", "Simplifying", "Parsing", "CNF Conversion", "Bit Blasting", "SAT Solving", "Bitvector Solving","Create SubstitutionMap", "Sending to SAT Solver", "Counter Example Generation","SAT Simplification", "Constant Bit Propagation","Array Read Refinement", "Applying Substitutions", "Remove Unconstrained", "Pure Literals" , "ITE Contexts", "AIG core simplification", "Interval Propagation"}; namespace BEEV { void FatalError(const char * str); } long RunTimes::getCurrentTime() { timeval t; gettimeofday(&t, NULL); return (1000 * t.tv_sec) + (t.tv_usec / 1000); } void RunTimes::print() { if (0 != category_stack.size()) { std::cerr << "size:" << category_stack.size() << std::endl; std::cerr << "top:" << CategoryNames[category_stack.top().first] << std::endl; BEEV::FatalError("category stack is not yet empty!!"); } std::ostringstream result; result << "statistics\n"; std::map<Category, int>::const_iterator it1 = counts.begin(); std::map<Category, long>::const_iterator it2 = times.begin(); int cummulative_ms = 0; while (it1 != counts.end()) { int time_ms = 0; if ((it2 = times.find(it1->first)) != times.end()) time_ms = it2->second; if (time_ms!=0) { result << " " << CategoryNames[it1->first] << ": " << it1->second; result << " [" << time_ms << "ms]"; result << std::endl; cummulative_ms += time_ms; } it1++; } std::cerr << result.str(); std::cerr << std::fixed; std::cerr.precision(2); std::cerr << "Statistics Total: " << ((double)cummulative_ms)/1000 << "s" << std::endl; std::cerr << "CPU Time Used : " << Minisat::cpuTime() << "s" << std::endl; std::cerr << "Peak Memory Used: " << Minisat::memUsedPeak() << "MB" << std::endl; clear(); } void RunTimes::addTime(Category c, long milliseconds) { std::map<Category, long>::iterator it; if ((it = times.find(c)) == times.end()) { times[c] = milliseconds; } else { it->second += milliseconds; } } void RunTimes::addCount(Category c) { std::map<Category, int>::iterator it; if ((it = counts.find(c)) == counts.end()) { counts[c] = 1; } else { it->second++; } } void RunTimes::stop(Category c) { Element e = category_stack.top(); category_stack.pop(); if (e.first != c) { std::cerr << e.first; std::cerr << c; BEEV::FatalError("Don't match"); } addTime(c, getCurrentTime() - e.second); addCount(c); } void RunTimes::start(Category c) { category_stack.push(std::make_pair(c, getCurrentTime())); } <commit_msg>Change the names for some statistics.<commit_after>//Hold the runtime statistics. E.g. how long was spent in simplification. //The times don't add up to the runtime, because we allow multiple times to //be counted simultaneously. For example, the current Transform()s call //Simplify_TopLevel, so inside simplify time will be counted towards both //Simplify_TopLevel & Transform. // This is intended as a low overhead profiling class. So runtimes can // always be tracked. #include <cassert> #include <sys/time.h> #include <sstream> #include <iostream> #include <utility> #include "RunTimes.h" #include "../sat/utils/System.h" // BE VERY CAREFUL> Update the Category Names to match. std::string RunTimes::CategoryNames[] = { "Transforming", "Simplifying", "Parsing", "CNF Conversion", "Bit Blasting", "SAT Solving", "Bitvector Solving","Variable Elimination", "Sending to SAT Solver", "Counter Example Generation","SAT Simplification", "Constant Bit Propagation","Array Read Refinement", "Applying Substitutions", "Removing Unconstrained", "Pure Literals" , "ITE Contexts", "AIG core simplification", "Interval Propagation"}; namespace BEEV { void FatalError(const char * str); } long RunTimes::getCurrentTime() { timeval t; gettimeofday(&t, NULL); return (1000 * t.tv_sec) + (t.tv_usec / 1000); } void RunTimes::print() { if (0 != category_stack.size()) { std::cerr << "size:" << category_stack.size() << std::endl; std::cerr << "top:" << CategoryNames[category_stack.top().first] << std::endl; BEEV::FatalError("category stack is not yet empty!!"); } std::ostringstream result; result << "statistics\n"; std::map<Category, int>::const_iterator it1 = counts.begin(); std::map<Category, long>::const_iterator it2 = times.begin(); int cummulative_ms = 0; while (it1 != counts.end()) { int time_ms = 0; if ((it2 = times.find(it1->first)) != times.end()) time_ms = it2->second; if (time_ms!=0) { result << " " << CategoryNames[it1->first] << ": " << it1->second; result << " [" << time_ms << "ms]"; result << std::endl; cummulative_ms += time_ms; } it1++; } std::cerr << result.str(); std::cerr << std::fixed; std::cerr.precision(2); std::cerr << "Statistics Total: " << ((double)cummulative_ms)/1000 << "s" << std::endl; std::cerr << "CPU Time Used : " << Minisat::cpuTime() << "s" << std::endl; std::cerr << "Peak Memory Used: " << Minisat::memUsedPeak() << "MB" << std::endl; clear(); } void RunTimes::addTime(Category c, long milliseconds) { std::map<Category, long>::iterator it; if ((it = times.find(c)) == times.end()) { times[c] = milliseconds; } else { it->second += milliseconds; } } void RunTimes::addCount(Category c) { std::map<Category, int>::iterator it; if ((it = counts.find(c)) == counts.end()) { counts[c] = 1; } else { it->second++; } } void RunTimes::stop(Category c) { Element e = category_stack.top(); category_stack.pop(); if (e.first != c) { std::cerr << e.first; std::cerr << c; BEEV::FatalError("Don't match"); } addTime(c, getCurrentTime() - e.second); addCount(c); } void RunTimes::start(Category c) { category_stack.push(std::make_pair(c, getCurrentTime())); } <|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: */ #include "graph-math-rewriter.h" #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include "flint/parser.h" #include "flint/sexp.h" using std::cerr; using std::endl; namespace flint { namespace { struct Detector : public sexp::Visitor<bool> { bool operator()(const sexp::Identifier &/*x*/) override {return false;} bool operator()(const sexp::Literal &/*a*/) override {return false;} bool operator()(const sexp::Compound &c) override { const auto &children = c.children(); size_t s = children.size(); assert(s > 0); const auto &head = children.at(0); if (head->type() == sexp::Expression::Type::kIdentifier) { const Token &t = static_cast<const sexp::Identifier *>(head.get())->token(); if (t.Equals("$is")) return true; } for (size_t i=1;i<s;i++) { if (sexp::ApplyVisitor(*this, *children.at(i))) return true; } return false; } }; class Writer : public sexp::Visitor<bool> { public: Writer(phml::GraphMathRewriter *rewriter, sqlite3_int64 pq_rowid, std::ostringstream *oss) : rewriter_(rewriter), pq_rowid_(pq_rowid), oss_(oss) { } bool operator()(const sexp::Identifier &x) override { return x.Write(oss_); } bool operator()(const sexp::Literal &a) override { return a.Write(oss_); } bool operator()(const sexp::Compound &c) override { const auto &children = c.children(); size_t s = children.size(); assert(s > 0); const auto &head = children.at(0); if (head->type() != sexp::Expression::Type::kIdentifier) return RewriteRecursively(c); const Token &t = static_cast<const sexp::Identifier *>(head.get())->token(); if (!t.Equals("$is")) return RewriteRecursively(c); assert(s == 3); const auto &lhs = children.at(1); const auto &rhs = children.at(2); if (rhs->type() != sexp::Expression::Type::kIdentifier) { std::cerr << "invalid 2nd argument of $is: "; rhs->Write(&std::cerr); std::cerr << std::endl; return false; } const Token &t2 = static_cast<const sexp::Identifier *>(rhs.get())->token(); // copy lexeme, but skip the first % std::unique_ptr<char[]> node_name(new char[t2.size]); std::memcpy(node_name.get(), t2.lexeme+1, t2.size-1); node_name[t2.size-1] = '\0'; int node_id; if (!rewriter_->FindNode(pq_rowid_, node_name.get(), &node_id)) return false; *oss_ << "(eq "; lhs->Write(oss_); oss_->put(' '); *oss_ << node_id; return oss_->put(')'); } private: bool RewriteRecursively(const sexp::Compound &c) { const auto &children = c.children(); size_t s = children.size(); oss_->put('('); for (size_t i=0;i<s;i++) { if (i > 0) oss_->put(' '); if (!sexp::ApplyVisitor(*this, *children.at(i))) return false; } return oss_->put(')'); } phml::GraphMathRewriter *rewriter_; sqlite3_int64 pq_rowid_; std::ostringstream *oss_; }; const char kQueryNode[] = \ "SELECT n.node_id FROM nodes AS n" " LEFT JOIN pqs AS p ON n.pq_rowid = p.rowid" " LEFT JOIN modules AS m ON p.module_rowid = m.rowid" " WHERE n.name = ?" " AND EXISTS (SELECT * FROM pqs WHERE rowid = ? AND module_rowid = m.rowid)"; } // namespace namespace phml { GraphMathRewriter::GraphMathRewriter(const char *query_select, const char *query_update) : query_select_(query_select) , query_update_(query_update) , stmt_select_(nullptr) , stmt_node_(nullptr) , stmt_update_(nullptr) { } GraphMathRewriter::~GraphMathRewriter() { sqlite3_finalize(stmt_select_); sqlite3_finalize(stmt_node_); sqlite3_finalize(stmt_update_); } bool GraphMathRewriter::Rewrite(sqlite3 *db) { int e = sqlite3_prepare_v2(db, query_select_, -1, &stmt_select_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << query_select_ << ": " << e << endl; return false; } e = sqlite3_prepare_v2(db, kQueryNode, -1, &stmt_node_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_prepare_v2(db, query_update_, -1, &stmt_update_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << query_update_ << ": " << e << endl; return false; } for (e = sqlite3_step(stmt_select_); e == SQLITE_ROW; e = sqlite3_step(stmt_select_)) { sqlite3_int64 rowid = sqlite3_column_int64(stmt_select_, 0); sqlite3_int64 pq_rowid = sqlite3_column_int64(stmt_select_, 1); const unsigned char *math = sqlite3_column_text(stmt_select_, 2); if (!Process(rowid, pq_rowid, (const char *)math)) return false; } if (e != SQLITE_DONE) { cerr << "failed to step statement: " << query_select_ << ": " << e << endl; return false; } return true; } bool GraphMathRewriter::Process(sqlite3_int64 rowid, sqlite3_int64 pq_rowid, const char *math) { std::unique_ptr<sexp::Expression> expr; parser::Parser parser(math); if (!parser(&expr)) return false; Detector d; if (!sexp::ApplyVisitor(d, *expr)) return true; std::ostringstream oss; oss.put(' '); // a leading space Writer w(this, pq_rowid, &oss); if (!sexp::ApplyVisitor(w, *expr)) return false; return Update(rowid, oss.str().c_str()); } bool GraphMathRewriter::FindNode(sqlite3_int64 pq_rowid, const char *node_name, int *node_id) { int e; e = sqlite3_bind_text(stmt_node_, 1, node_name, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind name: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_bind_int64(stmt_node_, 2, pq_rowid); if (e != SQLITE_OK) { cerr << "failed to bind pq_rowid: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_step(stmt_node_); if (e != SQLITE_ROW) { cerr << "failed to find node with pq_rowid/named: " << pq_rowid << '/' << node_name << ": " << kQueryNode << ": " << e << endl; return false; } int r = sqlite3_column_int(stmt_node_, 0); assert(r > 0); *node_id = r; sqlite3_reset(stmt_node_); return true; } bool GraphMathRewriter::Update(sqlite3_int64 rowid, const char *math) { int e = sqlite3_bind_text(stmt_update_, 1, math, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind math: " << query_update_ << ": " << e << endl; return false; } e = sqlite3_bind_int64(stmt_update_, 2, rowid); if (e != SQLITE_OK) { cerr << "failed to bind rowid: " << query_update_ << ": " << e << endl; return false; } e = sqlite3_step(stmt_update_); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << query_update_ << ": " << e << endl; return false; } sqlite3_reset(stmt_update_); return true; } } } <commit_msg>std::basic_ios's operator bool() is explicit since C++11<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #include "graph-math-rewriter.h" #include <cassert> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include "flint/parser.h" #include "flint/sexp.h" using std::cerr; using std::endl; namespace flint { namespace { struct Detector : public sexp::Visitor<bool> { bool operator()(const sexp::Identifier &/*x*/) override {return false;} bool operator()(const sexp::Literal &/*a*/) override {return false;} bool operator()(const sexp::Compound &c) override { const auto &children = c.children(); size_t s = children.size(); assert(s > 0); const auto &head = children.at(0); if (head->type() == sexp::Expression::Type::kIdentifier) { const Token &t = static_cast<const sexp::Identifier *>(head.get())->token(); if (t.Equals("$is")) return true; } for (size_t i=1;i<s;i++) { if (sexp::ApplyVisitor(*this, *children.at(i))) return true; } return false; } }; class Writer : public sexp::Visitor<bool> { public: Writer(phml::GraphMathRewriter *rewriter, sqlite3_int64 pq_rowid, std::ostringstream *oss) : rewriter_(rewriter), pq_rowid_(pq_rowid), oss_(oss) { } bool operator()(const sexp::Identifier &x) override { return bool(x.Write(oss_)); } bool operator()(const sexp::Literal &a) override { return bool(a.Write(oss_)); } bool operator()(const sexp::Compound &c) override { const auto &children = c.children(); size_t s = children.size(); assert(s > 0); const auto &head = children.at(0); if (head->type() != sexp::Expression::Type::kIdentifier) return RewriteRecursively(c); const Token &t = static_cast<const sexp::Identifier *>(head.get())->token(); if (!t.Equals("$is")) return RewriteRecursively(c); assert(s == 3); const auto &lhs = children.at(1); const auto &rhs = children.at(2); if (rhs->type() != sexp::Expression::Type::kIdentifier) { std::cerr << "invalid 2nd argument of $is: "; rhs->Write(&std::cerr); std::cerr << std::endl; return false; } const Token &t2 = static_cast<const sexp::Identifier *>(rhs.get())->token(); // copy lexeme, but skip the first % std::unique_ptr<char[]> node_name(new char[t2.size]); std::memcpy(node_name.get(), t2.lexeme+1, t2.size-1); node_name[t2.size-1] = '\0'; int node_id; if (!rewriter_->FindNode(pq_rowid_, node_name.get(), &node_id)) return false; *oss_ << "(eq "; lhs->Write(oss_); oss_->put(' '); *oss_ << node_id; return bool(oss_->put(')')); } private: bool RewriteRecursively(const sexp::Compound &c) { const auto &children = c.children(); size_t s = children.size(); oss_->put('('); for (size_t i=0;i<s;i++) { if (i > 0) oss_->put(' '); if (!sexp::ApplyVisitor(*this, *children.at(i))) return false; } return bool(oss_->put(')')); } phml::GraphMathRewriter *rewriter_; sqlite3_int64 pq_rowid_; std::ostringstream *oss_; }; const char kQueryNode[] = \ "SELECT n.node_id FROM nodes AS n" " LEFT JOIN pqs AS p ON n.pq_rowid = p.rowid" " LEFT JOIN modules AS m ON p.module_rowid = m.rowid" " WHERE n.name = ?" " AND EXISTS (SELECT * FROM pqs WHERE rowid = ? AND module_rowid = m.rowid)"; } // namespace namespace phml { GraphMathRewriter::GraphMathRewriter(const char *query_select, const char *query_update) : query_select_(query_select) , query_update_(query_update) , stmt_select_(nullptr) , stmt_node_(nullptr) , stmt_update_(nullptr) { } GraphMathRewriter::~GraphMathRewriter() { sqlite3_finalize(stmt_select_); sqlite3_finalize(stmt_node_); sqlite3_finalize(stmt_update_); } bool GraphMathRewriter::Rewrite(sqlite3 *db) { int e = sqlite3_prepare_v2(db, query_select_, -1, &stmt_select_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << query_select_ << ": " << e << endl; return false; } e = sqlite3_prepare_v2(db, kQueryNode, -1, &stmt_node_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_prepare_v2(db, query_update_, -1, &stmt_update_, nullptr); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << query_update_ << ": " << e << endl; return false; } for (e = sqlite3_step(stmt_select_); e == SQLITE_ROW; e = sqlite3_step(stmt_select_)) { sqlite3_int64 rowid = sqlite3_column_int64(stmt_select_, 0); sqlite3_int64 pq_rowid = sqlite3_column_int64(stmt_select_, 1); const unsigned char *math = sqlite3_column_text(stmt_select_, 2); if (!Process(rowid, pq_rowid, (const char *)math)) return false; } if (e != SQLITE_DONE) { cerr << "failed to step statement: " << query_select_ << ": " << e << endl; return false; } return true; } bool GraphMathRewriter::Process(sqlite3_int64 rowid, sqlite3_int64 pq_rowid, const char *math) { std::unique_ptr<sexp::Expression> expr; parser::Parser parser(math); if (!parser(&expr)) return false; Detector d; if (!sexp::ApplyVisitor(d, *expr)) return true; std::ostringstream oss; oss.put(' '); // a leading space Writer w(this, pq_rowid, &oss); if (!sexp::ApplyVisitor(w, *expr)) return false; return Update(rowid, oss.str().c_str()); } bool GraphMathRewriter::FindNode(sqlite3_int64 pq_rowid, const char *node_name, int *node_id) { int e; e = sqlite3_bind_text(stmt_node_, 1, node_name, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind name: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_bind_int64(stmt_node_, 2, pq_rowid); if (e != SQLITE_OK) { cerr << "failed to bind pq_rowid: " << kQueryNode << ": " << e << endl; return false; } e = sqlite3_step(stmt_node_); if (e != SQLITE_ROW) { cerr << "failed to find node with pq_rowid/named: " << pq_rowid << '/' << node_name << ": " << kQueryNode << ": " << e << endl; return false; } int r = sqlite3_column_int(stmt_node_, 0); assert(r > 0); *node_id = r; sqlite3_reset(stmt_node_); return true; } bool GraphMathRewriter::Update(sqlite3_int64 rowid, const char *math) { int e = sqlite3_bind_text(stmt_update_, 1, math, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind math: " << query_update_ << ": " << e << endl; return false; } e = sqlite3_bind_int64(stmt_update_, 2, rowid); if (e != SQLITE_OK) { cerr << "failed to bind rowid: " << query_update_ << ": " << e << endl; return false; } e = sqlite3_step(stmt_update_); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << query_update_ << ": " << e << endl; return false; } sqlite3_reset(stmt_update_); return true; } } } <|endoftext|>
<commit_before>#include <assert.h> #include <deque> #include <stdio.h> #define __STDC_LIMIT_MACROS /* for UINT32_MAX etc. */ #include <stdint.h> #include <stdlib.h> #include "Buffer.h" #include "CompressTree.h" #include "Slaves.h" namespace cbt { uint32_t BUFFER_SIZE; uint32_t MAX_ELS_PER_BUFFER; uint32_t EMPTY_THRESHOLD; CompressTree::CompressTree(uint32_t a, uint32_t b, uint32_t nodesInMemory, uint32_t buffer_size, uint32_t pao_size, const Operations* const ops) : a_(a), b_(b), nodeCtr(1), ops(ops), alg_(SNAPPY), allFlush_(true), lastLeafRead_(0), lastOffset_(0), lastElement_(0), threadsStarted_(false), nodesInMemory_(nodesInMemory), numEvicted_(0) { BUFFER_SIZE = buffer_size; MAX_ELS_PER_BUFFER = BUFFER_SIZE / pao_size; EMPTY_THRESHOLD = MAX_ELS_PER_BUFFER >> 1; pthread_mutex_init(&rootNodeAvailableMutex_, NULL); pthread_cond_init(&rootNodeAvailableForWriting_, NULL); uint32_t threadCount = 4; #ifdef ENABLE_PAGING threadCount++; #endif #ifdef ENABLE_COUNTERS threadCount++; monitor_ = NULL; #endif pthread_barrier_init(&threadsBarrier_, NULL, threadCount); } CompressTree::~CompressTree() { pthread_cond_destroy(&rootNodeAvailableForWriting_); pthread_mutex_destroy(&rootNodeAvailableMutex_); pthread_barrier_destroy(&threadsBarrier_); } bool CompressTree::bulk_insert(PartialAgg** paos, uint64_t num) { bool ret = true; for (uint64_t i=0; i<num; i++) ret &= insert(paos[i]); return ret; } bool CompressTree::insert(PartialAgg* agg) { // copy buf into root node buffer // root node buffer always decompressed allFlush_ = false; if (!threadsStarted_) { startThreads(); } if (inputNode_->isFull()) { // check if rootNode_ is available inputNode_->checkSerializationIntegrity(); pthread_mutex_lock(&rootNodeAvailableMutex_); while (!rootNode_->buffer_.empty() || rootNode_->queuedForEmptying_) { #ifdef CT_NODE_DEBUG fprintf(stderr, "inserter sleeping\n"); #endif pthread_cond_wait(&rootNodeAvailableForWriting_, &rootNodeAvailableMutex_); #ifdef CT_NODE_DEBUG fprintf(stderr, "inserter fingered\n"); #endif } // switch buffers Buffer temp; temp.lists_ = rootNode_->buffer_.lists_; rootNode_->buffer_.lists_ = inputNode_->buffer_.lists_; inputNode_->buffer_.lists_ = temp.lists_; temp.clear(); pthread_mutex_unlock(&rootNodeAvailableMutex_); // schedule the root node for emptying sorter_->addNode(rootNode_); sorter_->wakeup(); } bool ret = inputNode_->insert(agg); return ret; } bool CompressTree::bulk_read(PartialAgg**& pao_list, uint64_t& num_read, uint64_t max) { uint64_t hash; void* ptrToHash = (void*)&hash; num_read = 0; while(num_read < max) { if (!(nextValue(ptrToHash, pao_list[num_read]))) return false; num_read++; } return true; } bool CompressTree::nextValue(void*& hash, PartialAgg*& agg) { if (!allFlush_) { /* wait for all nodes to be sorted and emptied before proceeding */ /* do { #ifdef ENABLE_PAGING pager_->waitUntilCompletionNoticeReceived(); #endif sorter_->waitUntilCompletionNoticeReceived(); emptier_->waitUntilCompletionNoticeReceived(); #ifdef ENABLE_PAGING } while (!sorter_->empty() || !emptier_->empty() || !pager_->empty()); #else } while (!sorter_->empty() || !emptier_->empty()); #endif */ flushBuffers(); lastLeafRead_ = 0; lastOffset_ = 0; lastElement_ = 0; /* Wait for all outstanding compression work to finish */ compressor_->waitUntilCompletionNoticeReceived(); allFlush_ = true; // page in and decompress first leaf Node* curLeaf = allLeaves_[0]; while (curLeaf->buffer_.numElements() == 0) curLeaf = allLeaves_[++lastLeafRead_]; curLeaf->scheduleBufferCompressAction(Buffer::DECOMPRESS); curLeaf->waitForCompressAction(Buffer::DECOMPRESS); } Node* curLeaf = allLeaves_[lastLeafRead_]; Buffer::List* l = curLeaf->buffer_.lists_[0]; hash = (void*)&l->hashes_[lastElement_]; ops->createPAO(NULL, &agg); // if (lastLeafRead_ == 0) // fprintf(stderr, "%ld\n", lastOffset_); if (!(ops->deserialize(agg, l->data_ + lastOffset_, l->sizes_[lastElement_]))) { fprintf(stderr, "Can't deserialize at %u, index: %u\n", lastOffset_, lastElement_); assert(false); } lastOffset_ += l->sizes_[lastElement_]; lastElement_++; if (lastElement_ >= curLeaf->buffer_.numElements()) { curLeaf->scheduleBufferCompressAction(Buffer::COMPRESS); if (++lastLeafRead_ == allLeaves_.size()) { /* Wait for all outstanding compression work to finish */ compressor_->waitUntilCompletionNoticeReceived(); #ifdef CT_NODE_DEBUG fprintf(stderr, "Emptying tree!\n"); #endif emptyTree(); stopThreads(); return false; } Node *n = allLeaves_[lastLeafRead_]; while (curLeaf->buffer_.numElements() == 0) curLeaf = allLeaves_[++lastLeafRead_]; n->scheduleBufferCompressAction(Buffer::DECOMPRESS); n->waitForCompressAction(Buffer::DECOMPRESS); lastOffset_ = 0; lastElement_ = 0; } return true; } void CompressTree::emptyTree() { std::deque<Node*> delList1; std::deque<Node*> delList2; delList1.push_back(rootNode_); while (!delList1.empty()) { Node* n = delList1.front(); delList1.pop_front(); for (uint32_t i=0; i<n->children_.size(); i++) { delList1.push_back(n->children_[i]); } delList2.push_back(n); } while (!delList2.empty()) { Node* n = delList2.front(); delList2.pop_front(); delete n; } allLeaves_.clear(); leavesToBeEmptied_.clear(); allFlush_ = true; lastLeafRead_ = 0; lastOffset_ = 0; lastElement_ = 0; nodeCtr = 0; } bool CompressTree::flushBuffers() { Node* curNode; std::deque<Node*> visitQueue; fprintf(stderr, "Starting to flush\n"); // check if rootNode_ is available pthread_mutex_lock(&rootNodeAvailableMutex_); while (!rootNode_->buffer_.empty() || rootNode_->queuedForEmptying_) { pthread_cond_wait(&rootNodeAvailableForWriting_, &rootNodeAvailableMutex_); } pthread_mutex_unlock(&rootNodeAvailableMutex_); // root node is now empty emptyType_ = ALWAYS; // switch buffers Buffer temp; temp.lists_ = rootNode_->buffer_.lists_; rootNode_->buffer_.lists_ = inputNode_->buffer_.lists_; inputNode_->buffer_.lists_ = temp.lists_; temp.clear(); sorter_->addNode(rootNode_); sorter_->wakeup(); /* wait for all nodes to be sorted and emptied before proceeding */ do { #ifdef ENABLE_PAGING pager_->waitUntilCompletionNoticeReceived(); #endif sorter_->waitUntilCompletionNoticeReceived(); emptier_->waitUntilCompletionNoticeReceived(); #ifdef ENABLE_PAGING } while (!sorter_->empty() || !emptier_->empty() || !pager_->empty()); #else } while (!sorter_->empty() || !emptier_->empty()); #endif // add all leaves; visitQueue.push_back(rootNode_); while(!visitQueue.empty()) { curNode = visitQueue.front(); visitQueue.pop_front(); if (curNode->isLeaf()) { allLeaves_.push_back(curNode); #ifdef CT_NODE_DEBUG fprintf(stderr, "Pushing node %d to all-leaves\t", curNode->id_); fprintf(stderr, "Now has: "); for (int i=0; i<allLeaves_.size(); i++) { fprintf(stderr, "%d ", allLeaves_[i]->id_); } fprintf(stderr, "\n"); #endif continue; } for (uint32_t i=0; i<curNode->children_.size(); i++) { visitQueue.push_back(curNode->children_[i]); } } fprintf(stderr, "Tree has %ld leaves\n", allLeaves_.size()); uint32_t depth = 1; curNode = rootNode_; while (curNode->children_.size() > 0) { depth++; curNode = curNode->children_[0]; } fprintf(stderr, "Tree has depth: %d\n", depth); uint64_t numit = 0; for (uint64_t i=0; i<allLeaves_.size(); i++) numit += allLeaves_[i]->buffer_.numElements(); fprintf(stderr, "Tree has %ld elements\n", numit); return true; } bool CompressTree::addLeafToEmpty(Node* node) { leavesToBeEmptied_.push_back(node); return true; } /* A full leaf is handled by splitting the leaf into two leaves.*/ void CompressTree::handleFullLeaves() { while (!leavesToBeEmptied_.empty()) { Node* node = leavesToBeEmptied_.front(); leavesToBeEmptied_.pop_front(); Node* newLeaf = node->splitLeaf(); Node *l1 = NULL, *l2 = NULL; if (node->isFull()) { l1 = node->splitLeaf(); } if (newLeaf && newLeaf->isFull()) { l2 = newLeaf->splitLeaf(); } node->scheduleBufferCompressAction(Buffer::COMPRESS); if (newLeaf) { newLeaf->scheduleBufferCompressAction(Buffer::COMPRESS); } if (l1) { l1->scheduleBufferCompressAction(Buffer::COMPRESS); } if (l2) { l2->scheduleBufferCompressAction(Buffer::COMPRESS); } #ifdef CT_NODE_DEBUG fprintf(stderr, "Leaf node %d removed from full-leaf-list\n", node->id_); #endif pthread_mutex_lock(&node->queuedForEmptyMutex_); node->queuedForEmptying_ = false; pthread_mutex_unlock(&node->queuedForEmptyMutex_); } } void CompressTree::startThreads() { // create root node; initially a leaf rootNode_ = new Node(this, 0); rootNode_->buffer_.addList(); rootNode_->separator_ = UINT32_MAX; rootNode_->buffer_.setCompressible(false); inputNode_ = new Node(this, 0); inputNode_->buffer_.addList(); inputNode_->separator_ = UINT32_MAX; inputNode_->buffer_.setCompressible(false); #ifdef ENABLE_PAGING rootNode_->buffer_.setPageable(false); inputNode_->buffer_.setPageable(false); #endif emptyType_ = IF_FULL; sorter_ = new Sorter(this); sorter_->startThreads(); compressor_ = new Compressor(this); compressor_->startThreads(); emptier_ = new Emptier(this); emptier_->startThreads(); #ifdef ENABLE_PAGING pager_ = new Pager(this); pager_->startThreads(); #endif #ifdef ENABLE_COUNTERS monitor_ = new Monitor(this); monitor_->startThreads(); #endif pthread_barrier_wait(&threadsBarrier_); threadsStarted_ = true; } void CompressTree::stopThreads() { delete inputNode_; sorter_->stopThreads(); emptier_->stopThreads(); compressor_->stopThreads(); #ifdef ENABLE_PAGING pager_->stopThreads(); #endif #ifdef ENABLE_COUNTERS monitor_->stopThreads(); #endif threadsStarted_ = false; } bool CompressTree::createNewRoot(Node* otherChild) { Node* newRoot = new Node(this, rootNode_->level() + 1); newRoot->buffer_.addList(); newRoot->separator_ = UINT32_MAX; newRoot->buffer_.setCompressible(false); #ifdef CT_NODE_DEBUG fprintf(stderr, "Node %d is new root; children are %d and %d\n", newRoot->id_, rootNode_->id_, otherChild->id_); #endif // add two children of new root newRoot->addChild(rootNode_); newRoot->addChild(otherChild); rootNode_ = newRoot; return true; } } <commit_msg>fixed cpplint errors for CompressTree.cpp<commit_after>// Copyright (C) 2012 Georgia Institute of Technology // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // --- // Author: Hrishikesh Amur #include <assert.h> #include <stdio.h> #define __STDC_LIMIT_MACROS /* for UINT32_MAX etc. */ #include <stdint.h> #include <stdlib.h> #include <deque> #include "Buffer.h" #include "CompressTree.h" #include "Slaves.h" namespace cbt { uint32_t BUFFER_SIZE; uint32_t MAX_ELS_PER_BUFFER; uint32_t EMPTY_THRESHOLD; CompressTree::CompressTree(uint32_t a, uint32_t b, uint32_t nodesInMemory, uint32_t buffer_size, uint32_t pao_size, const Operations* const ops) : a_(a), b_(b), nodeCtr(1), ops(ops), alg_(SNAPPY), allFlush_(true), lastLeafRead_(0), lastOffset_(0), lastElement_(0), threadsStarted_(false), nodesInMemory_(nodesInMemory), numEvicted_(0) { BUFFER_SIZE = buffer_size; MAX_ELS_PER_BUFFER = BUFFER_SIZE / pao_size; EMPTY_THRESHOLD = MAX_ELS_PER_BUFFER >> 1; pthread_mutex_init(&rootNodeAvailableMutex_, NULL); pthread_cond_init(&rootNodeAvailableForWriting_, NULL); uint32_t threadCount = 4; #ifdef ENABLE_PAGING threadCount++; #endif #ifdef ENABLE_COUNTERS threadCount++; monitor_ = NULL; #endif pthread_barrier_init(&threadsBarrier_, NULL, threadCount); } CompressTree::~CompressTree() { pthread_cond_destroy(&rootNodeAvailableForWriting_); pthread_mutex_destroy(&rootNodeAvailableMutex_); pthread_barrier_destroy(&threadsBarrier_); } bool CompressTree::bulk_insert(PartialAgg** paos, uint64_t num) { bool ret = true; for (uint64_t i = 0; i < num; ++i) ret &= insert(paos[i]); return ret; } bool CompressTree::insert(PartialAgg* agg) { // copy buf into root node buffer // root node buffer always decompressed allFlush_ = false; if (!threadsStarted_) { startThreads(); } if (inputNode_->isFull()) { // check if rootNode_ is available inputNode_->checkSerializationIntegrity(); pthread_mutex_lock(&rootNodeAvailableMutex_); while (!rootNode_->buffer_.empty() || rootNode_->queuedForEmptying_) { #ifdef CT_NODE_DEBUG fprintf(stderr, "inserter sleeping\n"); #endif pthread_cond_wait(&rootNodeAvailableForWriting_, &rootNodeAvailableMutex_); #ifdef CT_NODE_DEBUG fprintf(stderr, "inserter fingered\n"); #endif } // switch buffers Buffer temp; temp.lists_ = rootNode_->buffer_.lists_; rootNode_->buffer_.lists_ = inputNode_->buffer_.lists_; inputNode_->buffer_.lists_ = temp.lists_; temp.clear(); pthread_mutex_unlock(&rootNodeAvailableMutex_); // schedule the root node for emptying sorter_->addNode(rootNode_); sorter_->wakeup(); } bool ret = inputNode_->insert(agg); return ret; } bool CompressTree::bulk_read(PartialAgg** pao_list, uint64_t& num_read, uint64_t max) { uint64_t hash; void* ptrToHash = reinterpret_cast<void*>(&hash); num_read = 0; while (num_read < max) { if (!(nextValue(ptrToHash, pao_list[num_read]))) return false; num_read++; } return true; } bool CompressTree::nextValue(void*& hash, PartialAgg*& agg) { if (!allFlush_) { /* wait for all nodes to be sorted and emptied before proceeding */ /* do { #ifdef ENABLE_PAGING pager_->waitUntilCompletionNoticeReceived(); #endif sorter_->waitUntilCompletionNoticeReceived(); emptier_->waitUntilCompletionNoticeReceived(); #ifdef ENABLE_PAGING } while (!sorter_->empty() || !emptier_->empty() || !pager_->empty()); #else } while (!sorter_->empty() || !emptier_->empty()); #endif */ flushBuffers(); lastLeafRead_ = 0; lastOffset_ = 0; lastElement_ = 0; /* Wait for all outstanding compression work to finish */ compressor_->waitUntilCompletionNoticeReceived(); allFlush_ = true; // page in and decompress first leaf Node* curLeaf = allLeaves_[0]; while (curLeaf->buffer_.numElements() == 0) curLeaf = allLeaves_[++lastLeafRead_]; curLeaf->scheduleBufferCompressAction(Buffer::DECOMPRESS); curLeaf->waitForCompressAction(Buffer::DECOMPRESS); } Node* curLeaf = allLeaves_[lastLeafRead_]; Buffer::List* l = curLeaf->buffer_.lists_[0]; hash = reinterpret_cast<void*>(&l->hashes_[lastElement_]); ops->createPAO(NULL, &agg); // if (lastLeafRead_ == 0) // fprintf(stderr, "%ld\n", lastOffset_); if (!(ops->deserialize(agg, l->data_ + lastOffset_, l->sizes_[lastElement_]))) { fprintf(stderr, "Can't deserialize at %u, index: %u\n", lastOffset_, lastElement_); assert(false); } lastOffset_ += l->sizes_[lastElement_]; lastElement_++; if (lastElement_ >= curLeaf->buffer_.numElements()) { curLeaf->scheduleBufferCompressAction(Buffer::COMPRESS); if (++lastLeafRead_ == allLeaves_.size()) { /* Wait for all outstanding compression work to finish */ compressor_->waitUntilCompletionNoticeReceived(); #ifdef CT_NODE_DEBUG fprintf(stderr, "Emptying tree!\n"); #endif emptyTree(); stopThreads(); return false; } Node *n = allLeaves_[lastLeafRead_]; while (curLeaf->buffer_.numElements() == 0) curLeaf = allLeaves_[++lastLeafRead_]; n->scheduleBufferCompressAction(Buffer::DECOMPRESS); n->waitForCompressAction(Buffer::DECOMPRESS); lastOffset_ = 0; lastElement_ = 0; } return true; } void CompressTree::emptyTree() { std::deque<Node*> delList1; std::deque<Node*> delList2; delList1.push_back(rootNode_); while (!delList1.empty()) { Node* n = delList1.front(); delList1.pop_front(); for (uint32_t i = 0; i < n->children_.size(); ++i) { delList1.push_back(n->children_[i]); } delList2.push_back(n); } while (!delList2.empty()) { Node* n = delList2.front(); delList2.pop_front(); delete n; } allLeaves_.clear(); leavesToBeEmptied_.clear(); allFlush_ = true; lastLeafRead_ = 0; lastOffset_ = 0; lastElement_ = 0; nodeCtr = 0; } bool CompressTree::flushBuffers() { Node* curNode; std::deque<Node*> visitQueue; fprintf(stderr, "Starting to flush\n"); // check if rootNode_ is available pthread_mutex_lock(&rootNodeAvailableMutex_); while (!rootNode_->buffer_.empty() || rootNode_->queuedForEmptying_) { pthread_cond_wait(&rootNodeAvailableForWriting_, &rootNodeAvailableMutex_); } pthread_mutex_unlock(&rootNodeAvailableMutex_); // root node is now empty emptyType_ = ALWAYS; // switch buffers Buffer temp; temp.lists_ = rootNode_->buffer_.lists_; rootNode_->buffer_.lists_ = inputNode_->buffer_.lists_; inputNode_->buffer_.lists_ = temp.lists_; temp.clear(); sorter_->addNode(rootNode_); sorter_->wakeup(); /* wait for all nodes to be sorted and emptied before proceeding */ do { #ifdef ENABLE_PAGING pager_->waitUntilCompletionNoticeReceived(); #endif sorter_->waitUntilCompletionNoticeReceived(); emptier_->waitUntilCompletionNoticeReceived(); #ifdef ENABLE_PAGING } while (!sorter_->empty() || !emptier_->empty() || !pager_->empty()); #else } while (!sorter_->empty() || !emptier_->empty()); #endif // add all leaves; visitQueue.push_back(rootNode_); while (!visitQueue.empty()) { curNode = visitQueue.front(); visitQueue.pop_front(); if (curNode->isLeaf()) { allLeaves_.push_back(curNode); #ifdef CT_NODE_DEBUG fprintf(stderr, "Pushing node %d to all-leaves\t", curNode->id_); fprintf(stderr, "Now has: "); for (int i = 0; i < allLeaves_.size(); ++i) { fprintf(stderr, "%d ", allLeaves_[i]->id_); } fprintf(stderr, "\n"); #endif continue; } for (uint32_t i = 0; i < curNode->children_.size(); ++i) { visitQueue.push_back(curNode->children_[i]); } } fprintf(stderr, "Tree has %ld leaves\n", allLeaves_.size()); uint32_t depth = 1; curNode = rootNode_; while (curNode->children_.size() > 0) { depth++; curNode = curNode->children_[0]; } fprintf(stderr, "Tree has depth: %d\n", depth); uint64_t numit = 0; for (uint64_t i = 0; i < allLeaves_.size(); ++i) numit += allLeaves_[i]->buffer_.numElements(); fprintf(stderr, "Tree has %ld elements\n", numit); return true; } bool CompressTree::addLeafToEmpty(Node* node) { leavesToBeEmptied_.push_back(node); return true; } /* A full leaf is handled by splitting the leaf into two leaves.*/ void CompressTree::handleFullLeaves() { while (!leavesToBeEmptied_.empty()) { Node* node = leavesToBeEmptied_.front(); leavesToBeEmptied_.pop_front(); Node* newLeaf = node->splitLeaf(); Node *l1 = NULL, *l2 = NULL; if (node->isFull()) { l1 = node->splitLeaf(); } if (newLeaf && newLeaf->isFull()) { l2 = newLeaf->splitLeaf(); } node->scheduleBufferCompressAction(Buffer::COMPRESS); if (newLeaf) { newLeaf->scheduleBufferCompressAction(Buffer::COMPRESS); } if (l1) { l1->scheduleBufferCompressAction(Buffer::COMPRESS); } if (l2) { l2->scheduleBufferCompressAction(Buffer::COMPRESS); } #ifdef CT_NODE_DEBUG fprintf(stderr, "Leaf node %d removed from full-leaf-list\n", node->id_); #endif pthread_mutex_lock(&node->queuedForEmptyMutex_); node->queuedForEmptying_ = false; pthread_mutex_unlock(&node->queuedForEmptyMutex_); } } void CompressTree::startThreads() { // create root node; initially a leaf rootNode_ = new Node(this, 0); rootNode_->buffer_.addList(); rootNode_->separator_ = UINT32_MAX; rootNode_->buffer_.setCompressible(false); inputNode_ = new Node(this, 0); inputNode_->buffer_.addList(); inputNode_->separator_ = UINT32_MAX; inputNode_->buffer_.setCompressible(false); #ifdef ENABLE_PAGING rootNode_->buffer_.setPageable(false); inputNode_->buffer_.setPageable(false); #endif emptyType_ = IF_FULL; sorter_ = new Sorter(this); sorter_->startThreads(); compressor_ = new Compressor(this); compressor_->startThreads(); emptier_ = new Emptier(this); emptier_->startThreads(); #ifdef ENABLE_PAGING pager_ = new Pager(this); pager_->startThreads(); #endif #ifdef ENABLE_COUNTERS monitor_ = new Monitor(this); monitor_->startThreads(); #endif pthread_barrier_wait(&threadsBarrier_); threadsStarted_ = true; } void CompressTree::stopThreads() { delete inputNode_; sorter_->stopThreads(); emptier_->stopThreads(); compressor_->stopThreads(); #ifdef ENABLE_PAGING pager_->stopThreads(); #endif #ifdef ENABLE_COUNTERS monitor_->stopThreads(); #endif threadsStarted_ = false; } bool CompressTree::createNewRoot(Node* otherChild) { Node* newRoot = new Node(this, rootNode_->level() + 1); newRoot->buffer_.addList(); newRoot->separator_ = UINT32_MAX; newRoot->buffer_.setCompressible(false); #ifdef CT_NODE_DEBUG fprintf(stderr, "Node %d is new root; children are %d and %d\n", newRoot->id_, rootNode_->id_, otherChild->id_); #endif // add two children of new root newRoot->addChild(rootNode_); newRoot->addChild(otherChild); rootNode_ = newRoot; return true; } } <|endoftext|>
<commit_before>/* See Project chip LICENSE file for licensing information. */ #include <platform/logging/LogV.h> #include <core/CHIPConfig.h> #include <os/log.h> #include <stdarg.h> #include <stdio.h> #include <string.h> namespace chip { namespace Logging { namespace Platform { void LogV(const char * module, uint8_t category, const char * msg, va_list v) { char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; int32_t prefixLen = snprintf(formattedMsg, sizeof(formattedMsg), "CHIP: [%s] ", module); if (prefixLen < 0) { // This should not happen return; } if (static_cast<size_t>(prefixLen) >= sizeof(formattedMsg)) { prefixLen = sizeof(formattedMsg) - 1; } vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - static_cast<size_t>(prefixLen), msg, v); switch (category) { case kLogCategory_Error: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_ERROR, "🔴 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[1;31m"); #endif break; case kLogCategory_Progress: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_INFO, "🔵 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;32m"); #endif break; case kLogCategory_Detail: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEBUG, "🟢 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;34m"); #endif break; } #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "%s\033[0m\n", formattedMsg); #endif } } // namespace Platform } // namespace Logging } // namespace chip <commit_msg>Fix broken Darwin Builds (#4854)<commit_after>/* See Project chip LICENSE file for licensing information. */ #include <platform/logging/LogV.h> #include <core/CHIPConfig.h> #include <support/logging/Constants.h> #include <os/log.h> #include <stdarg.h> #include <stdio.h> #include <string.h> namespace chip { namespace Logging { namespace Platform { void LogV(const char * module, uint8_t category, const char * msg, va_list v) { char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; int32_t prefixLen = snprintf(formattedMsg, sizeof(formattedMsg), "CHIP: [%s] ", module); if (prefixLen < 0) { // This should not happen return; } if (static_cast<size_t>(prefixLen) >= sizeof(formattedMsg)) { prefixLen = sizeof(formattedMsg) - 1; } vsnprintf(formattedMsg + prefixLen, sizeof(formattedMsg) - static_cast<size_t>(prefixLen), msg, v); switch (category) { case kLogCategory_Error: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_ERROR, "🔴 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[1;31m"); #endif break; case kLogCategory_Progress: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_INFO, "🔵 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;32m"); #endif break; case kLogCategory_Detail: os_log_with_type(OS_LOG_DEFAULT, OS_LOG_TYPE_DEBUG, "🟢 %{public}s", formattedMsg); #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "\033[0;34m"); #endif break; } #if TARGET_OS_MAC && TARGET_OS_IPHONE == 0 fprintf(stdout, "%s\033[0m\n", formattedMsg); #endif } } // namespace Platform } // namespace Logging } // namespace chip <|endoftext|>
<commit_before>/* Copyright (c) 2013-2017 Jeffrey Pfau * * 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 "CoreManager.h" #include "CoreController.h" #include "LogController.h" #include "VFileDevice.h" #include <QDir> #ifdef M_CORE_GBA #include <mgba/gba/core.h> #endif #include <mgba/core/core.h> #include <mgba-util/vfs.h> using namespace QGBA; void CoreManager::setConfig(const mCoreConfig* config) { m_config = config; } void CoreManager::setMultiplayerController(MultiplayerController* multiplayer) { m_multiplayer = multiplayer; } CoreController* CoreManager::loadGame(const QString& path) { QFileInfo info(path); if (!info.isReadable()) { QString fname = info.fileName(); QString base = info.path(); if (base.endsWith("/") || base.endsWith(QDir::separator())) { base.chop(1); } VDir* dir = VDirOpenArchive(base.toUtf8().constData()); if (dir) { VFile* vf = dir->openFile(dir, fname.toUtf8().constData(), O_RDONLY); if (vf) { struct VFile* vfclone = VFileMemChunk(NULL, vf->size(vf)); uint8_t buffer[2048]; ssize_t read; while ((read = vf->read(vf, buffer, sizeof(buffer))) > 0) { vfclone->write(vfclone, buffer, read); } vf->close(vf); vf = vfclone; } dir->close(dir); return loadGame(vf, fname, base); } else { LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path); } return nullptr; } VFile* vf = nullptr; VDir* archive = VDirOpenArchive(path.toUtf8().constData()); if (archive) { VFile* vfOriginal = VDirFindFirst(archive, [](VFile* vf) { return mCoreIsCompatible(vf) != mPLATFORM_NONE; }); ssize_t size; if (vfOriginal && (size = vfOriginal->size(vfOriginal)) > 0) { void* mem = vfOriginal->map(vfOriginal, size, MAP_READ); vf = VFileMemChunk(mem, size); vfOriginal->unmap(vfOriginal, mem, size); vfOriginal->close(vfOriginal); } } QDir dir(info.dir()); if (!vf) { vf = VFileOpen(info.canonicalFilePath().toUtf8().constData(), O_RDONLY); } return loadGame(vf, info.fileName(), dir.canonicalPath()); } CoreController* CoreManager::loadGame(VFile* vf, const QString& path, const QString& base) { if (!vf) { return nullptr; } mCore* core = mCoreFindVF(vf); if (!core) { vf->close(vf); LOG(QT, ERROR) << tr("Could not load game. Are you sure it's in the correct format?"); return nullptr; } core->init(core); mCoreInitConfig(core, nullptr); if (m_config) { mCoreLoadForeignConfig(core, m_config); } if (m_preload) { mCorePreloadVF(core, vf); } else { core->loadROM(core, vf); } QByteArray bytes(path.toUtf8()); separatePath(bytes.constData(), nullptr, core->dirs.baseName, nullptr); QFileInfo info(base); if (info.isDir()) { info = QFileInfo(base + "/" + path); } bytes = info.dir().canonicalPath().toUtf8(); mDirectorySetAttachBase(&core->dirs, VDirOpen(bytes.constData())); if (!mCoreAutoloadSave(core)) { LOG(QT, ERROR) << tr("Failed to open save file. Is the save directory writable?"); } mCoreAutoloadCheats(core); CoreController* cc = new CoreController(core); if (m_multiplayer) { cc->setMultiplayerController(m_multiplayer); } emit coreLoaded(cc); return cc; } CoreController* CoreManager::loadBIOS(int platform, const QString& path) { QFileInfo info(path); VFile* vf = VFileOpen(info.canonicalFilePath().toUtf8().constData(), O_RDONLY); if (!vf) { return nullptr; } mCore* core = nullptr; switch (platform) { #ifdef M_CORE_GBA case mPLATFORM_GBA: core = GBACoreCreate(); break; #endif default: vf->close(vf); return nullptr; } if (!core) { vf->close(vf); return nullptr; } core->init(core); mCoreInitConfig(core, nullptr); if (m_config) { mCoreLoadForeignConfig(core, m_config); } core->loadBIOS(core, vf, 0); mCoreConfigSetOverrideIntValue(&core->config, "useBios", 1); mCoreConfigSetOverrideIntValue(&core->config, "skipBios", 0); QByteArray bytes(info.baseName().toUtf8()); strncpy(core->dirs.baseName, bytes.constData(), sizeof(core->dirs.baseName)); bytes = info.dir().canonicalPath().toUtf8(); mDirectorySetAttachBase(&core->dirs, VDirOpen(bytes.constData())); CoreController* cc = new CoreController(core); if (m_multiplayer) { cc->setMultiplayerController(m_multiplayer); } emit coreLoaded(cc); return cc; } <commit_msg>Qt: Rephrase save fail error<commit_after>/* Copyright (c) 2013-2017 Jeffrey Pfau * * 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 "CoreManager.h" #include "CoreController.h" #include "LogController.h" #include "VFileDevice.h" #include <QDir> #ifdef M_CORE_GBA #include <mgba/gba/core.h> #endif #include <mgba/core/core.h> #include <mgba-util/vfs.h> using namespace QGBA; void CoreManager::setConfig(const mCoreConfig* config) { m_config = config; } void CoreManager::setMultiplayerController(MultiplayerController* multiplayer) { m_multiplayer = multiplayer; } CoreController* CoreManager::loadGame(const QString& path) { QFileInfo info(path); if (!info.isReadable()) { QString fname = info.fileName(); QString base = info.path(); if (base.endsWith("/") || base.endsWith(QDir::separator())) { base.chop(1); } VDir* dir = VDirOpenArchive(base.toUtf8().constData()); if (dir) { VFile* vf = dir->openFile(dir, fname.toUtf8().constData(), O_RDONLY); if (vf) { struct VFile* vfclone = VFileMemChunk(NULL, vf->size(vf)); uint8_t buffer[2048]; ssize_t read; while ((read = vf->read(vf, buffer, sizeof(buffer))) > 0) { vfclone->write(vfclone, buffer, read); } vf->close(vf); vf = vfclone; } dir->close(dir); return loadGame(vf, fname, base); } else { LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path); } return nullptr; } VFile* vf = nullptr; VDir* archive = VDirOpenArchive(path.toUtf8().constData()); if (archive) { VFile* vfOriginal = VDirFindFirst(archive, [](VFile* vf) { return mCoreIsCompatible(vf) != mPLATFORM_NONE; }); ssize_t size; if (vfOriginal && (size = vfOriginal->size(vfOriginal)) > 0) { void* mem = vfOriginal->map(vfOriginal, size, MAP_READ); vf = VFileMemChunk(mem, size); vfOriginal->unmap(vfOriginal, mem, size); vfOriginal->close(vfOriginal); } } QDir dir(info.dir()); if (!vf) { vf = VFileOpen(info.canonicalFilePath().toUtf8().constData(), O_RDONLY); } return loadGame(vf, info.fileName(), dir.canonicalPath()); } CoreController* CoreManager::loadGame(VFile* vf, const QString& path, const QString& base) { if (!vf) { return nullptr; } mCore* core = mCoreFindVF(vf); if (!core) { vf->close(vf); LOG(QT, ERROR) << tr("Could not load game. Are you sure it's in the correct format?"); return nullptr; } core->init(core); mCoreInitConfig(core, nullptr); if (m_config) { mCoreLoadForeignConfig(core, m_config); } if (m_preload) { mCorePreloadVF(core, vf); } else { core->loadROM(core, vf); } QByteArray bytes(path.toUtf8()); separatePath(bytes.constData(), nullptr, core->dirs.baseName, nullptr); QFileInfo info(base); if (info.isDir()) { info = QFileInfo(base + "/" + path); } bytes = info.dir().canonicalPath().toUtf8(); mDirectorySetAttachBase(&core->dirs, VDirOpen(bytes.constData())); if (!mCoreAutoloadSave(core)) { LOG(QT, ERROR) << tr("Failed to open save file; in-game saves cannot be updated. Please ensure the save directory is writable without additional privileges (e.g. UAC on Windows)."); } mCoreAutoloadCheats(core); CoreController* cc = new CoreController(core); if (m_multiplayer) { cc->setMultiplayerController(m_multiplayer); } emit coreLoaded(cc); return cc; } CoreController* CoreManager::loadBIOS(int platform, const QString& path) { QFileInfo info(path); VFile* vf = VFileOpen(info.canonicalFilePath().toUtf8().constData(), O_RDONLY); if (!vf) { return nullptr; } mCore* core = nullptr; switch (platform) { #ifdef M_CORE_GBA case mPLATFORM_GBA: core = GBACoreCreate(); break; #endif default: vf->close(vf); return nullptr; } if (!core) { vf->close(vf); return nullptr; } core->init(core); mCoreInitConfig(core, nullptr); if (m_config) { mCoreLoadForeignConfig(core, m_config); } core->loadBIOS(core, vf, 0); mCoreConfigSetOverrideIntValue(&core->config, "useBios", 1); mCoreConfigSetOverrideIntValue(&core->config, "skipBios", 0); QByteArray bytes(info.baseName().toUtf8()); strncpy(core->dirs.baseName, bytes.constData(), sizeof(core->dirs.baseName)); bytes = info.dir().canonicalPath().toUtf8(); mDirectorySetAttachBase(&core->dirs, VDirOpen(bytes.constData())); CoreController* cc = new CoreController(core); if (m_multiplayer) { cc->setMultiplayerController(m_multiplayer); } emit coreLoaded(cc); return cc; } <|endoftext|>
<commit_before>#include "ErrorHandler.h" ErrorHandler::ErrorHandler() { errId = -1; } char* ErrorHandler::getError() { switch(errId) { case FILE_DOES_NOT_EXIST: return "The file directory submitted does not exist.\n"; case WRONG_EXTENSION: return "This is not a TMX file. Make sure the file extension is .tmx.\n"; case NO_MAP_NODE: return "The TMX file has no map node.\n"; case MISSING_MAP_ATTRIBUTES: return "Required attributes from the map node are missing.\n"; case MISSING_TILESET_ATTRIBUTES: return "Required attributes from a certain tileset node are missing.\n"; case NO_FIRSTGID_IN_TILESET: return "No firstgid specified on a tileset node.\n"; case MISSING_IMAGE_ATTRIBUTES: return "Required attributes from a certain image node are missing.\n"; case NO_SOURCE_IN_IMAGE: return "No source directory for an image node.\n"; case MISSING_DATA_ATTRIBUTES: return "Required attributes from a certain data node are missing.\n"; case NO_DATA_ENCODING_SPECIFIED: return "No data encoding specified on layer data.\n"; case UNSUPPORTED_DATA_ENCODING: return "The encoding specified for a layer's data is currently unsupported by the parser.\n"; case MISSING_TILE_ATTRIBUTES: return "Required attributes from a certain tile node are missing.\n"; case NO_TILE_ID: return "No tile id specified for a certain tile node.\n"; case MISSING_PROPERTY_ATTRIBUTES: return "Required attributes from a certain property node are missing.\n"; case MISSING_TERRAIN_ATTRIBUTES: return "Required attributes from a certain terrain node are missing.\n"; case NO_NAME_IN_TERRAIN: return "No terrain name specified.\n"; return NO_TILE_IN_TERRAIN: return "No tile specified for a certain terrain node.\n"; case MISSING_LAYER_ATTRIBUTES: return "Required attributes from a certain layer node are missing.\n"; case NO_NAME_IN_LAYER: return "No layer name specified for a certain layer node.\n"; case MISSING_IMAGE_LAYER_ATTRIBUTES: return "Required attributes from a certain image layer node are missing.\n"; case MISSING_OBJECT_ATTRIBUTES: return "Required attributes from a certain object node are missing.\n"; default: return "No known error detected.\n"; } } <commit_msg>Implement set error id<commit_after>#include "ErrorHandler.h" ErrorHandler::ErrorHandler() { errId = -1; } void ErrorHandler::setErrorId(int id) { this->errId = id; } char* ErrorHandler::getError() { switch(errId) { case FILE_DOES_NOT_EXIST: return "The file directory submitted does not exist.\n"; case WRONG_EXTENSION: return "This is not a TMX file. Make sure the file extension is .tmx.\n"; case NO_MAP_NODE: return "The TMX file has no map node.\n"; case MISSING_MAP_ATTRIBUTES: return "Required attributes from the map node are missing.\n"; case MISSING_TILESET_ATTRIBUTES: return "Required attributes from a certain tileset node are missing.\n"; case NO_FIRSTGID_IN_TILESET: return "No firstgid specified on a tileset node.\n"; case MISSING_IMAGE_ATTRIBUTES: return "Required attributes from a certain image node are missing.\n"; case NO_SOURCE_IN_IMAGE: return "No source directory for an image node.\n"; case MISSING_DATA_ATTRIBUTES: return "Required attributes from a certain data node are missing.\n"; case NO_DATA_ENCODING_SPECIFIED: return "No data encoding specified on layer data.\n"; case UNSUPPORTED_DATA_ENCODING: return "The encoding specified for a layer's data is currently unsupported by the parser.\n"; case MISSING_TILE_ATTRIBUTES: return "Required attributes from a certain tile node are missing.\n"; case NO_TILE_ID: return "No tile id specified for a certain tile node.\n"; case MISSING_PROPERTY_ATTRIBUTES: return "Required attributes from a certain property node are missing.\n"; case MISSING_TERRAIN_ATTRIBUTES: return "Required attributes from a certain terrain node are missing.\n"; case NO_NAME_IN_TERRAIN: return "No terrain name specified.\n"; case NO_TILE_IN_TERRAIN: return "No tile specified for a certain terrain node.\n"; case MISSING_LAYER_ATTRIBUTES: return "Required attributes from a certain layer node are missing.\n"; case NO_NAME_IN_LAYER: return "No layer name specified for a certain layer node.\n"; case MISSING_IMAGE_LAYER_ATTRIBUTES: return "Required attributes from a certain image layer node are missing.\n"; case MISSING_OBJECT_ATTRIBUTES: return "Required attributes from a certain object node are missing.\n"; default: return "No known error detected.\n"; } } <|endoftext|>
<commit_before>#include "Genes/Genome.h" #include <limits> #include "Game/Board.h" #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/King_Protection_Gene.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Sphere_of_Influence_Gene); genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); for(const auto& gene : genome) { gene_active[gene->name()] = true; } } // Cloning Genome::Genome(const Genome& other) : genome(), gene_active(other.gene_active), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { auto piece_strength_gene = std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]); if( ! gene_active[piece_strength_gene->name()]) { piece_strength_gene = std::make_shared<Piece_Strength_Gene>(); // contains all-zero values } for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } gene_active = other.gene_active; reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); gene_active[genome[i]->name()] = Random::coin_flip() ? A.gene_active.at(genome[i]->name()) : B.gene_active.at(genome[i]->name()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene_active[gene->name()] = gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups if(gene_active.at(gene->name())) { score += gene->evaluate(board, perspective); } } return score; } double Genome::evaluate(const Board& board, Color perspective) const { if(board.game_has_ended()) { if(board.get_winner() == perspective) // checkmate win { return std::numeric_limits<double>::infinity(); } else if(board.get_winner() == opposite(perspective)) // checkmate loss { return -std::numeric_limits<double>::infinity(); } else // stalemate { return std::numeric_limits<double>::lowest(); } } return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { if(Random::success_probability(0.95)) { gene->mutate(); } else { gene_active[gene->name()] = ! gene_active[gene->name()]; } } } reseat_piece_strength_gene(); } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); os << (gene_active.at(gene->name()) ? "" : "IN") << "ACTIVE\n"; } os << "\n"; } double Genome::positions_to_examine(const Board& board, const Clock& clock) const { if(look_ahead_gene_index < genome.size() && gene_active.at(genome[look_ahead_gene_index]->name())) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(board, clock); } else { return 0; } } <commit_msg>Better order for endgame scoring<commit_after>#include "Genes/Genome.h" #include <limits> #include "Game/Board.h" #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/King_Protection_Gene.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Sphere_of_Influence_Gene); genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); for(const auto& gene : genome) { gene_active[gene->name()] = true; } } // Cloning Genome::Genome(const Genome& other) : genome(), gene_active(other.gene_active), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { auto piece_strength_gene = std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]); if( ! gene_active[piece_strength_gene->name()]) { piece_strength_gene = std::make_shared<Piece_Strength_Gene>(); // contains all-zero values } for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } gene_active = other.gene_active; reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); gene_active[genome[i]->name()] = Random::coin_flip() ? A.gene_active.at(genome[i]->name()) : B.gene_active.at(genome[i]->name()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene_active[gene->name()] = gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups if(gene_active.at(gene->name())) { score += gene->evaluate(board, perspective); } } return score; } double Genome::evaluate(const Board& board, Color perspective) const { if(board.game_has_ended()) { if(board.get_winner() == NONE) // stalemate { return std::numeric_limits<double>::lowest(); } else if(board.get_winner() == perspective) // checkmate win { return std::numeric_limits<double>::infinity(); } else // checkmate loss { return -std::numeric_limits<double>::infinity(); } } return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { if(Random::success_probability(0.95)) { gene->mutate(); } else { gene_active[gene->name()] = ! gene_active[gene->name()]; } } } reseat_piece_strength_gene(); } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); os << (gene_active.at(gene->name()) ? "" : "IN") << "ACTIVE\n"; } os << "\n"; } double Genome::positions_to_examine(const Board& board, const Clock& clock) const { if(look_ahead_gene_index < genome.size() && gene_active.at(genome[look_ahead_gene_index]->name())) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(board, clock); } else { return 0; } } <|endoftext|>
<commit_before>#include "Genes/Genome.h" #include <limits> #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/Last_Minute_Panic_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/King_Protection_Gene.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1), last_minute_panic_gene_index(-1), branch_pruning_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(new Last_Minute_Panic_Gene); last_minute_panic_gene_index = genome.size() - 1; genome.emplace_back(new Branch_Pruning_Gene); branch_pruning_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Sphere_of_Influence_Gene); genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); for(const auto& gene : genome) { gene_active[gene->name()] = true; } } // Cloning Genome::Genome(const Genome& other) : genome(), gene_active(other.gene_active), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), last_minute_panic_gene_index(other.last_minute_panic_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { auto piece_strength_gene = std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]); if( ! gene_active[piece_strength_gene->name()]) { piece_strength_gene = std::make_shared<Piece_Strength_Gene>(); // contains all-zero values } for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; last_minute_panic_gene_index = other.last_minute_panic_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } gene_active = other.gene_active; reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), last_minute_panic_gene_index(A.last_minute_panic_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); gene_active[genome[i]->name()] = Random::coin_flip() ? A.gene_active.at(genome[i]->name()) : B.gene_active.at(genome[i]->name()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene_active[gene->name()] = gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups if(gene_active.at(gene->name())) { score += gene->evaluate(board, perspective); } } return score; } double Genome::evaluate(const Board& board, Color perspective) const { return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { if(Random::success_probability(0.95)) { gene->mutate(); } else { gene_active[gene->name()] = ! gene_active[gene->name()]; } } } reseat_piece_strength_gene(); } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); os << (gene_active.at(gene->name()) ? "" : "IN") << "ACTIVE\n"; } os << "\n"; } size_t Genome::positions_to_examine(const Board& board, const Clock& clock) const { if(look_ahead_gene_index < genome.size() && gene_active.at(genome[look_ahead_gene_index]->name())) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(board, clock); } else { return 0; } } double Genome::time_required() const { if(last_minute_panic_gene_index < genome.size() && gene_active.at(genome[last_minute_panic_gene_index]->name())) { return std::static_pointer_cast<Last_Minute_Panic_Gene>(genome[last_minute_panic_gene_index])->time_required(); } else { return 0; } } double Genome::minimum_score_change() const { if(branch_pruning_gene_index < genome.size() && gene_active.at(genome[branch_pruning_gene_index]->name())) { return std::static_pointer_cast<Branch_Pruning_Gene>(genome[branch_pruning_gene_index])->minimum_score_change(); } else { return std::numeric_limits<double>::lowest(); } } <commit_msg>Disable Branch Pruning Gene<commit_after>#include "Genes/Genome.h" #include <limits> #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/Last_Minute_Panic_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/King_Protection_Gene.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1), last_minute_panic_gene_index(-1), branch_pruning_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(new Last_Minute_Panic_Gene); last_minute_panic_gene_index = genome.size() - 1; //genome.emplace_back(new Branch_Pruning_Gene); //branch_pruning_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Sphere_of_Influence_Gene); genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); for(const auto& gene : genome) { gene_active[gene->name()] = true; } } // Cloning Genome::Genome(const Genome& other) : genome(), gene_active(other.gene_active), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), last_minute_panic_gene_index(other.last_minute_panic_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { auto piece_strength_gene = std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]); if( ! gene_active[piece_strength_gene->name()]) { piece_strength_gene = std::make_shared<Piece_Strength_Gene>(); // contains all-zero values } for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; last_minute_panic_gene_index = other.last_minute_panic_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } gene_active = other.gene_active; reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), last_minute_panic_gene_index(A.last_minute_panic_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); gene_active[genome[i]->name()] = Random::coin_flip() ? A.gene_active.at(genome[i]->name()) : B.gene_active.at(genome[i]->name()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene_active[gene->name()] = gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups if(gene_active.at(gene->name())) { score += gene->evaluate(board, perspective); } } return score; } double Genome::evaluate(const Board& board, Color perspective) const { return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { if(Random::success_probability(0.95)) { gene->mutate(); } else { gene_active[gene->name()] = ! gene_active[gene->name()]; } } } reseat_piece_strength_gene(); } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); os << (gene_active.at(gene->name()) ? "" : "IN") << "ACTIVE\n"; } os << "\n"; } size_t Genome::positions_to_examine(const Board& board, const Clock& clock) const { if(look_ahead_gene_index < genome.size() && gene_active.at(genome[look_ahead_gene_index]->name())) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(board, clock); } else { return 0; } } double Genome::time_required() const { if(last_minute_panic_gene_index < genome.size() && gene_active.at(genome[last_minute_panic_gene_index]->name())) { return std::static_pointer_cast<Last_Minute_Panic_Gene>(genome[last_minute_panic_gene_index])->time_required(); } else { return 0; } } double Genome::minimum_score_change() const { if(branch_pruning_gene_index < genome.size() && gene_active.at(genome[branch_pruning_gene_index]->name())) { return std::static_pointer_cast<Branch_Pruning_Gene>(genome[branch_pruning_gene_index])->minimum_score_change(); } else { return std::numeric_limits<double>::lowest(); } } <|endoftext|>
<commit_before>// // Copyright (C) 2016 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // #include "fsbmodel.h" FSBModel::FSBModel(QObject *parent) : QObject(parent) { } const FSBModel::FileSystemEntryList &FSBModel::entries() const { return _entries; } void FSBModel::setPath(QString path) { _path = path; refresh(); emit pathChanged(path); } const QString &FSBModel::path() const { return _path; } const QString &FSBModel::rootPath() const { return _rootPath; } bool FSBModel::contains(const QString &path) const { foreach (const FSEntry &entry, _entries) { if (entry.path == path) return true; } return false; } bool FSBModel::hasFileEntry(QString name, QString &path) { for (int i =0; i < _entries.length(); i++) { if (_entries[i].entryType != FSEntry::Folder && _entries[i].name.toLower() == name) { path = _entries[i].path; return true; } } return false; } bool FSBModel::hasFolderEntry(QString name) { for (int i =0; i < _entries.length(); i++) { if (_entries[i].entryType == FSEntry::Folder && _entries[i].name.toLower() == name) return true; } return false; } FSEntry FSBModel::createEntry(const QString &path, FSEntry::EntryType type) { FSEntry entry; entry.entryType = type; int index = path.lastIndexOf("/"); if (index != -1) { entry.name = path.mid(index + 1); entry.path = path; entry.description = path.mid(0, index); } else { entry.name = path; entry.path = path; entry.description = ""; } return entry; } FSEntry FSBModel::createEntry(const QString &path, const QString &name, const QString &description, FSEntry::EntryType type) { FSEntry entry; entry.name = name; entry.path = path; entry.description = description; entry.entryType = type; return entry; } <commit_msg>Fixes #1324<commit_after>// // Copyright (C) 2016 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // #include "fsbmodel.h" FSBModel::FSBModel(QObject *parent) : QObject(parent) { } const FSBModel::FileSystemEntryList &FSBModel::entries() const { return _entries; } void FSBModel::setPath(QString path) { _path = path; refresh(); emit pathChanged(path); } const QString &FSBModel::path() const { return _path; } const QString &FSBModel::rootPath() const { return _rootPath; } bool FSBModel::contains(const QString &path) const { foreach (const FSEntry &entry, _entries) { if (entry.path == path) return true; } return false; } bool FSBModel::hasFileEntry(QString name, QString &path) { for (int i =0; i < _entries.length(); i++) { if (_entries[i].entryType != FSEntry::Folder && _entries[i].name.toLower() == name) { path = _entries[i].path; return true; } } return false; } bool FSBModel::hasFolderEntry(QString name) { for (int i =0; i < _entries.length(); i++) { if (_entries[i].entryType == FSEntry::Folder && _entries[i].name.toLower() == name) return true; } return false; } FSEntry FSBModel::createEntry(const QString &path, FSEntry::EntryType type) { FSEntry entry; entry.entryType = type; int index = path.lastIndexOf("/"); if (index == -1) { index = path.lastIndexOf("\\"); } if (index != -1) { entry.name = path.mid(index + 1); entry.path = path; entry.description = path.mid(0, index); } else { entry.name = path; entry.path = path; entry.description = ""; } return entry; } FSEntry FSBModel::createEntry(const QString &path, const QString &name, const QString &description, FSEntry::EntryType type) { FSEntry entry; entry.name = name; entry.path = path; entry.description = description; entry.entryType = type; return entry; } <|endoftext|>
<commit_before>#include <exception> #include <iostream> #include <sstream> #include <TFormula.h> #include <pqxx/pqxx> #include "../DBHandler/HeaderFiles/DBHandler.h" #include "JPetCalibration.h" namespace JPetCalibration { using namespace std; class Exception:public exception{ public: Exception(const string&&msg); virtual ~Exception() throw(); virtual const char* what() const throw(); private: string m_msg; }; using namespace std; using namespace pqxx; using namespace DB::SERVICES; Exception::Exception(const string&& msg):m_msg(msg){} Exception::~Exception()throw(){} const char* Exception::what() const throw(){ return m_msg.c_str(); } CalibrationType::CalibrationType(const CalibrationType& source) :m_name(source.m_name),m_id(source.m_id),m_count(source.m_count),m_formula(source.m_formula){} CalibrationType::CalibrationType(const result::const_iterator&row) :m_name(row["name"].as<string>()),m_id(row["type_id"].as<size_t>()) ,m_count(row["param_count"].as<size_t>()),m_formula(row["formula"].as<string>()){} CalibrationType::CalibrationType(const string& n,const size_t count, const string& f) :m_name(n),m_id(0),m_count(count),m_formula(f){} CalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f) :m_name(n),m_id(0),m_count(count),m_formula(f){} CalibrationType::~CalibrationType(){} const size_t CalibrationType::id()const{return m_id;} const string& CalibrationType::name()const{return m_name;} const size_t CalibrationType::param_count()const{return m_count;} const string& CalibrationType::formula()const{return m_formula;} CalibrationTypeEdit::CalibrationTypeEdit(){} CalibrationTypeEdit::~CalibrationTypeEdit(){} const vector<CalibrationType> CalibrationTypeEdit::GetTypes()const{ result data=DBHandler::getInstance().querry("SELECT * FROM getcalibrationtypes();"); vector<CalibrationType> res; for(const auto&row:data)res.push_back(CalibrationType(row)); return res; } void CalibrationTypeEdit::AddType(const CalibrationType& type){ if(type.id()>0)throw Exception("CalibrationInterface: attempt to insert CalibrationType that already exists"); string req="SELECT * FROM insert_calibrationtype("; req+="'"+type.name()+"',"+to_string(type.param_count())+",'"+type.formula()+"');"; DBHandler::getInstance().querry(req); } void CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);} Calibration::Calibration(const string&n,const size_t count,const string& f,const string&params) :m_name(n),m_formula(f),m_encoded_params(params){ stringstream ss(params); vector<string> tokens; copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(tokens)); for(const string&token:tokens) if(m_params.size()<count) m_params.push_back(stod(token)); if(m_params.size()<count) throw Exception("PhmAmplCalibration: the number of decoded parameters is bad"); init_formula(); } Calibration::Calibration(const string&&n,const size_t count,const string&&f,const string&&params):Calibration(n,count,f,params){} Calibration::Calibration(const result::const_iterator&row,const vector<string>&field_names) :Calibration(row[field_names[0]].as<string>(),row[field_names[1]].as<size_t>(),row[field_names[2]].as<string>(),row[field_names[3]].as<string>()){} Calibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){ if(0==type.id())throw Exception("Calibration: attempt to create calibration of type that is not present in database"); if(values.size()!=type.param_count()) throw Exception("Calibration: parameters count is not good for selected calibration type"); m_encoded_params=""; for(double p:values){ m_params.push_back(p); m_encoded_params+=to_string(p)+" "; } init_formula(); } Calibration::Calibration(const Calibration& source) :m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){ for(double p:source.m_params)m_params.push_back(p); init_formula(); } Calibration::~Calibration(){deinit_formula();} const string& Calibration::name() const{return m_name;} const string& Calibration::formula() const{return m_formula;} const vector<double>&Calibration::params() const{return m_params;} const string& Calibration::encoded_params() const{return m_encoded_params;} void Calibration::init_formula(){ buf=new double[m_params.size()]; for(size_t i=0;i<m_params.size();i++)buf[i]=m_params[i]; m_tformula= new TFormula(formula().c_str(),formula().c_str()); } void Calibration::deinit_formula(){ delete[] buf; delete m_tformula; } double Calibration::operator()(const parameter_set& X) const{ double x[X.size()]; for(size_t i=0,n=X.size();i<n;i++)x[i]=X[i]; return m_tformula->EvalPar(x,buf); } double Calibration::operator()(const parameter_set&& X) const{return operator()(X);} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&field_names) :Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&&field_names) :CalibrationForEquipment(eq_id,row,field_names), m_type_id(0), m_cal_id(0){} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values) :Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values) :CalibrationForEquipment(eq_id,type,values){} CalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source) :Calibration(source), m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::~CalibrationForEquipment(){} const size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;} const id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;} const size_t CalibrationForEquipment::type_id()const{return m_type_id;} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&field_names) :Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&&field_names) :CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source) :Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);} CalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){} const id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;} const size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;} AmplificationCalibrationEdit::AmplificationCalibrationEdit() :m_fields{"name","param_count","formula","param_values"}{} AmplificationCalibrationEdit::~AmplificationCalibrationEdit(){} const vector<CalibrationForEquipment> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{ vector<CalibrationForEquipment> res; for(const auto&row:DBHandler::getInstance().querry("select * from getcalibrations_phmampl_allphm("+to_string(eq_id[0])+");")) res.push_back(CalibrationForEquipment(eq_id,row,m_fields)); return res; } const vector<CalibrationForEquipmentAndRun> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{ vector<CalibrationForEquipmentAndRun> res; for(const auto&row:DBHandler::getInstance() .querry("select * from getcalibrations_phmampl_setupandphm("+to_string(setup_id)+","+to_string(eq_id[0])+");")) res.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields)); return res; } bool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){ if( (new_calibration.calibration_id()==0)&& (new_calibration.type_id()!=0)&& (new_calibration.equipment_ids()[0]!=0) ){ DBHandler::getInstance().querry("select * from insert_calibration_phmampl(" +to_string(new_calibration.equipment_ids()[0])+"," +to_string(new_calibration.type_id())+"," +new_calibration.encoded_params()+");" ); return true; }else return false; } bool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){ if( (cal.calibration_id()!=0)&&(cal.type_id()==0)&& (cal.equipment_ids()[0]!=0) ){ DBHandler::getInstance().querry( "select * from connect_calibration_phmampl(" +to_string(cal.calibration_id())+","+to_string(run_id)+");" ); return true; }else return false; } AmplificationCalibration::AmplificationCalibration() :m_fields{"name","param_count","formula","param_values"}{} AmplificationCalibration::~AmplificationCalibration(){} const vector<CalibrationForEquipmentAndRun> AmplificationCalibration::ForRun(const size_t run_id) const{ vector<CalibrationForEquipmentAndRun> res; for(const auto&row: DBHandler::getInstance().querry( "select * from getcalibrations_phmampl_run("+to_string(run_id)+");" ) ) res.push_back(CalibrationForEquipmentAndRun( {row["id_phm"].as<size_t>()},run_id,row,m_fields )); return res; } } <commit_msg>Change position of variable initialization in constructors<commit_after>#include <exception> #include <iostream> #include <sstream> #include <TFormula.h> #include <pqxx/pqxx> #include "../DBHandler/HeaderFiles/DBHandler.h" #include "JPetCalibration.h" namespace JPetCalibration { using namespace std; class Exception:public exception{ public: Exception(const string&&msg); virtual ~Exception() throw(); virtual const char* what() const throw(); private: string m_msg; }; using namespace std; using namespace pqxx; using namespace DB::SERVICES; Exception::Exception(const string&& msg):m_msg(msg){} Exception::~Exception()throw(){} const char* Exception::what() const throw(){ return m_msg.c_str(); } CalibrationType::CalibrationType(const CalibrationType& source) :m_id(source.m_id), m_count(source.m_count), m_name(source.m_name),m_formula(source.m_formula){} CalibrationType::CalibrationType(const result::const_iterator&row) :m_id(row["type_id"].as<size_t>()), m_count(row["param_count"].as<size_t>()), m_name(row["name"].as<string>()), m_formula(row["formula"].as<string>()){} CalibrationType::CalibrationType(const string& n,const size_t count, const string& f) :m_id(0), m_count(count), m_name(n), m_formula(f){} CalibrationType::CalibrationType(const string&&n,const size_t count,const string&&f) :m_id(0), m_count(count), m_name(n), m_formula(f){} CalibrationType::~CalibrationType(){} const size_t CalibrationType::id()const{return m_id;} const string& CalibrationType::name()const{return m_name;} const size_t CalibrationType::param_count()const{return m_count;} const string& CalibrationType::formula()const{return m_formula;} CalibrationTypeEdit::CalibrationTypeEdit(){} CalibrationTypeEdit::~CalibrationTypeEdit(){} const vector<CalibrationType> CalibrationTypeEdit::GetTypes()const{ result data=DBHandler::getInstance().querry("SELECT * FROM getcalibrationtypes();"); vector<CalibrationType> res; for(const auto&row:data)res.push_back(CalibrationType(row)); return res; } void CalibrationTypeEdit::AddType(const CalibrationType& type){ if(type.id()>0)throw Exception("CalibrationInterface: attempt to insert CalibrationType that already exists"); string req="SELECT * FROM insert_calibrationtype("; req+="'"+type.name()+"',"+to_string(type.param_count())+",'"+type.formula()+"');"; DBHandler::getInstance().querry(req); } void CalibrationTypeEdit::AddType(const CalibrationType&& type){AddType(type);} Calibration::Calibration(const string&n,const size_t count,const string& f,const string&params) :m_name(n),m_formula(f),m_encoded_params(params){ stringstream ss(params); vector<string> tokens; copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(tokens)); for(const string&token:tokens) if(m_params.size()<count) m_params.push_back(stod(token)); if(m_params.size()<count) throw Exception("PhmAmplCalibration: the number of decoded parameters is bad"); init_formula(); } Calibration::Calibration(const string&&n,const size_t count,const string&&f,const string&&params):Calibration(n,count,f,params){} Calibration::Calibration(const result::const_iterator&row,const vector<string>&field_names) :Calibration(row[field_names[0]].as<string>(),row[field_names[1]].as<size_t>(),row[field_names[2]].as<string>(),row[field_names[3]].as<string>()){} Calibration::Calibration(const CalibrationType&type,const parameter_set&values):m_name(type.name()),m_formula(type.formula()){ if(0==type.id())throw Exception("Calibration: attempt to create calibration of type that is not present in database"); if(values.size()!=type.param_count()) throw Exception("Calibration: parameters count is not good for selected calibration type"); m_encoded_params=""; for(double p:values){ m_params.push_back(p); m_encoded_params+=to_string(p)+" "; } init_formula(); } Calibration::Calibration(const Calibration& source) :m_name(source.m_name),m_formula(source.m_formula),m_encoded_params(source.m_encoded_params){ for(double p:source.m_params)m_params.push_back(p); init_formula(); } Calibration::~Calibration(){deinit_formula();} const string& Calibration::name() const{return m_name;} const string& Calibration::formula() const{return m_formula;} const vector<double>&Calibration::params() const{return m_params;} const string& Calibration::encoded_params() const{return m_encoded_params;} void Calibration::init_formula(){ buf=new double[m_params.size()]; for(size_t i=0;i<m_params.size();i++)buf[i]=m_params[i]; m_tformula= new TFormula(formula().c_str(),formula().c_str()); } void Calibration::deinit_formula(){ delete[] buf; delete m_tformula; } double Calibration::operator()(const parameter_set& X) const{ double x[X.size()]; for(size_t i=0,n=X.size();i<n;i++)x[i]=X[i]; return m_tformula->EvalPar(x,buf); } double Calibration::operator()(const parameter_set&& X) const{return operator()(X);} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&field_names) :Calibration(row, field_names), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const result::const_iterator&row,const vector<string>&&field_names) :CalibrationForEquipment(eq_id,row,field_names){} CalibrationForEquipment::CalibrationForEquipment(const id_set&eq_id,const CalibrationType&type,const parameter_set&values) :Calibration(type, values), m_type_id(0), m_cal_id(0){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::CalibrationForEquipment(const id_set& eq_id,const CalibrationType&type,const parameter_set&&values) :CalibrationForEquipment(eq_id,type,values){} CalibrationForEquipment::CalibrationForEquipment(const CalibrationForEquipment&source) :Calibration(source),m_type_id(0), m_cal_id(0){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);} CalibrationForEquipment::~CalibrationForEquipment(){} const size_t CalibrationForEquipment::calibration_id()const{return m_cal_id;} const id_set& CalibrationForEquipment::equipment_ids()const{return m_eq_id;} const size_t CalibrationForEquipment::type_id()const{return m_type_id;} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&field_names) :Calibration(row, field_names),m_run_id(run_id){for(const auto&item:eq_id)m_eq_id.push_back(item);} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const id_set&eq_id,size_t run_id,const result::const_iterator&row,const vector<string>&&field_names) :CalibrationForEquipmentAndRun(eq_id,run_id,row,field_names){} CalibrationForEquipmentAndRun::CalibrationForEquipmentAndRun(const CalibrationForEquipmentAndRun& source) :Calibration(source),m_run_id(source.m_run_id){for(const auto&item:source.m_eq_id)m_eq_id.push_back(item);} CalibrationForEquipmentAndRun::~CalibrationForEquipmentAndRun(){} const id_set&CalibrationForEquipmentAndRun::equipment_ids()const{return m_eq_id;} const size_t CalibrationForEquipmentAndRun::run_id()const{return m_run_id;} AmplificationCalibrationEdit::AmplificationCalibrationEdit() :m_fields{"name","param_count","formula","param_values"}{} AmplificationCalibrationEdit::~AmplificationCalibrationEdit(){} const vector<CalibrationForEquipment> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id)const{ vector<CalibrationForEquipment> res; for(const auto&row:DBHandler::getInstance().querry("select * from getcalibrations_phmampl_allphm("+to_string(eq_id[0])+");")) res.push_back(CalibrationForEquipment(eq_id,row,m_fields)); return res; } const vector<CalibrationForEquipmentAndRun> AmplificationCalibrationEdit::CalibrationList(const id_set&&eq_id,const size_t setup_id)const{ vector<CalibrationForEquipmentAndRun> res; for(const auto&row:DBHandler::getInstance() .querry("select * from getcalibrations_phmampl_setupandphm("+to_string(setup_id)+","+to_string(eq_id[0])+");")) res.push_back(CalibrationForEquipmentAndRun(eq_id,setup_id,row,m_fields)); return res; } bool AmplificationCalibrationEdit::AddCalibration(const CalibrationForEquipment&&new_calibration){ if( (new_calibration.calibration_id()==0)&& (new_calibration.type_id()!=0)&& (new_calibration.equipment_ids()[0]!=0) ){ DBHandler::getInstance().querry("select * from insert_calibration_phmampl(" +to_string(new_calibration.equipment_ids()[0])+"," +to_string(new_calibration.type_id())+"," +new_calibration.encoded_params()+");" ); return true; }else return false; } bool AmplificationCalibrationEdit::ConnectCalibrationToRun(const CalibrationForEquipment&cal,const size_t run_id){ if( (cal.calibration_id()!=0)&&(cal.type_id()==0)&& (cal.equipment_ids()[0]!=0) ){ DBHandler::getInstance().querry( "select * from connect_calibration_phmampl(" +to_string(cal.calibration_id())+","+to_string(run_id)+");" ); return true; }else return false; } AmplificationCalibration::AmplificationCalibration() :m_fields{"name","param_count","formula","param_values"}{} AmplificationCalibration::~AmplificationCalibration(){} const vector<CalibrationForEquipmentAndRun> AmplificationCalibration::ForRun(const size_t run_id) const{ vector<CalibrationForEquipmentAndRun> res; for(const auto&row: DBHandler::getInstance().querry( "select * from getcalibrations_phmampl_run("+to_string(run_id)+");" ) ) res.push_back(CalibrationForEquipmentAndRun( {row["id_phm"].as<size_t>()},run_id,row,m_fields )); return res; } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/lexical_cast.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include <map> #include <utility> #include <numeric> #include <cstdio> #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/smart_ban.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/aux_/session_impl.hpp" namespace libtorrent { namespace { struct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin> { smart_ban_plugin(torrent& t) : m_torrent(t) , m_salt(rand()) { } void on_piece_pass(int p) { #ifdef TORRENT_LOGGING (*m_torrent.session().m_logger) << time_now_string() << " PIECE PASS [ p: " << p << " | block_crc_size: " << m_block_crc.size() << " ]\n"; #endif // has this piece failed earlier? If it has, go through the // CRCs from the time it failed and ban the peers that // sent bad blocks std::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0)); if (i == m_block_crc.end() || i->first.piece_index != p) return; int size = m_torrent.torrent_file().piece_size(p); peer_request r = {p, 0, (std::min)(16*1024, size)}; piece_block pb(p, 0); while (size > 0) { if (i->first.block_index == pb.block_index) { m_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block , shared_from_this(), *i, _1, _2)); m_block_crc.erase(i++); } else { TORRENT_ASSERT(i->first.block_index > pb.block_index); } if (i == m_block_crc.end() || i->first.piece_index != p) break; r.start += 16*1024; size -= 16*1024; r.length = (std::min)(16*1024, size); ++pb.block_index; } #ifndef NDEBUG // make sure we actually removed all the entries for piece 'p' i = m_block_crc.lower_bound(piece_block(p, 0)); TORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p); #endif if (m_torrent.is_seed()) { std::map<piece_block, block_entry>().swap(m_block_crc); return; } } void on_piece_failed(int p) { // The piece failed the hash check. Record // the CRC and origin peer of every block std::vector<void*> downloaders; m_torrent.picker().get_downloaders(downloaders, p); int size = m_torrent.torrent_file().piece_size(p); peer_request r = {p, 0, (std::min)(16*1024, size)}; piece_block pb(p, 0); for (std::vector<void*>::iterator i = downloaders.begin() , end(downloaders.end()); i != end; ++i) { if (*i != 0) { m_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block , shared_from_this(), pb, (policy::peer*)*i, _1, _2)); } r.start += 16*1024; size -= 16*1024; r.length = (std::min)(16*1024, size); ++pb.block_index; } TORRENT_ASSERT(size <= 0); } private: // this entry ties a specific block CRC to // a peer. struct block_entry { policy::peer* peer; unsigned long crc; }; void on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j) { TORRENT_ASSERT(p); // ignore read errors if (ret != j.buffer_size) return; adler32_crc crc; crc.update(j.buffer, j.buffer_size); crc.update((char const*)&m_salt, sizeof(m_salt)); block_entry e = {p, crc.final()}; // since this callback is called directory from the disk io // thread, the session mutex is not locked when we get here aux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex); std::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b); if (i->first == b && i->second.peer == p) { // this peer has sent us this block before if (i->second.crc != e.crc) { // this time the crc of the block is different // from the first time it sent it // at least one of them must be bad if (p == 0) return; if (!m_torrent.get_policy().has_peer(p)) return; #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " BANNING PEER [ p: " << b.piece_index << " | b: " << b.block_index << " | c: " << client << " | crc1: " << i->second.crc << " | crc2: " << e.crc << " | ip: " << p->ip << " ]\n"; #endif p->banned = true; if (p->connection) p->connection->disconnect(); } // we already have this exact entry in the map // we don't have to insert it return; } m_block_crc.insert(i, std::make_pair(b, e)); #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " STORE BLOCK CRC [ p: " << b.piece_index << " | b: " << b.block_index << " | c: " << client << " | crc: " << e.crc << " | ip: " << p->ip << " ]\n"; #endif } void on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j) { // since this callback is called directory from the disk io // thread, the session mutex is not locked when we get here aux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex); // ignore read errors if (ret != j.buffer_size) return; adler32_crc crc; crc.update(j.buffer, j.buffer_size); crc.update((char const*)&m_salt, sizeof(m_salt)); unsigned long ok_crc = crc.final(); if (b.second.crc == ok_crc) return; policy::peer* p = b.second.peer; if (p == 0) return; if (!m_torrent.get_policy().has_peer(p)) return; #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " BANNING PEER [ p: " << b.first.piece_index << " | b: " << b.first.block_index << " | c: " << client << " | ok_crc: " << ok_crc << " | bad_crc: " << b.second.crc << " | ip: " << p->ip << " ]\n"; #endif p->banned = true; if (p->connection) p->connection->disconnect(); } torrent& m_torrent; // This table maps a piece_block (piece and block index // pair) to a peer and the block CRC. The CRC is calculated // from the data in the block + the salt std::map<piece_block, block_entry> m_block_crc; // This salt is a random value used to calculate the block CRCs // Since the CRC function that is used is not a one way function // the salt is required to avoid attacks where bad data is sent // that is forged to match the CRC of the good data. int m_salt; }; } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*) { return boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t)); } } <commit_msg>fix for #244<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/lexical_cast.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include <map> #include <utility> #include <numeric> #include <cstdio> #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/smart_ban.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/aux_/session_impl.hpp" namespace libtorrent { namespace { struct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin> { smart_ban_plugin(torrent& t) : m_torrent(t) , m_salt(rand()) { } void on_piece_pass(int p) { #ifdef TORRENT_LOGGING (*m_torrent.session().m_logger) << time_now_string() << " PIECE PASS [ p: " << p << " | block_crc_size: " << m_block_crc.size() << " ]\n"; #endif // has this piece failed earlier? If it has, go through the // CRCs from the time it failed and ban the peers that // sent bad blocks std::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0)); if (i == m_block_crc.end() || i->first.piece_index != p) return; int size = m_torrent.torrent_file().piece_size(p); peer_request r = {p, 0, (std::min)(16*1024, size)}; piece_block pb(p, 0); while (size > 0) { if (i->first.block_index == pb.block_index) { m_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block , shared_from_this(), *i, _1, _2)); m_block_crc.erase(i++); } else { TORRENT_ASSERT(i->first.block_index > pb.block_index); } if (i == m_block_crc.end() || i->first.piece_index != p) break; r.start += 16*1024; size -= 16*1024; r.length = (std::min)(16*1024, size); ++pb.block_index; } #ifndef NDEBUG // make sure we actually removed all the entries for piece 'p' i = m_block_crc.lower_bound(piece_block(p, 0)); TORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p); #endif if (m_torrent.is_seed()) { std::map<piece_block, block_entry>().swap(m_block_crc); return; } } void on_piece_failed(int p) { // The piece failed the hash check. Record // the CRC and origin peer of every block std::vector<void*> downloaders; m_torrent.picker().get_downloaders(downloaders, p); int size = m_torrent.torrent_file().piece_size(p); peer_request r = {p, 0, (std::min)(16*1024, size)}; piece_block pb(p, 0); for (std::vector<void*>::iterator i = downloaders.begin() , end(downloaders.end()); i != end; ++i) { if (*i != 0) { m_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block , shared_from_this(), pb, (policy::peer*)*i, _1, _2)); } r.start += 16*1024; size -= 16*1024; r.length = (std::min)(16*1024, size); ++pb.block_index; } TORRENT_ASSERT(size <= 0); } private: // this entry ties a specific block CRC to // a peer. struct block_entry { policy::peer* peer; unsigned long crc; }; void on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j) { TORRENT_ASSERT(p); // ignore read errors if (ret != j.buffer_size) return; adler32_crc crc; crc.update(j.buffer, j.buffer_size); crc.update((char const*)&m_salt, sizeof(m_salt)); block_entry e = {p, crc.final()}; // since this callback is called directory from the disk io // thread, the session mutex is not locked when we get here aux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex); std::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b); if (i != m_block_crc.end() && i->first == b && i->second.peer == p) { // this peer has sent us this block before if (i->second.crc != e.crc) { // this time the crc of the block is different // from the first time it sent it // at least one of them must be bad if (p == 0) return; if (!m_torrent.get_policy().has_peer(p)) return; #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " BANNING PEER [ p: " << b.piece_index << " | b: " << b.block_index << " | c: " << client << " | crc1: " << i->second.crc << " | crc2: " << e.crc << " | ip: " << p->ip << " ]\n"; #endif p->banned = true; if (p->connection) p->connection->disconnect(); } // we already have this exact entry in the map // we don't have to insert it return; } m_block_crc.insert(i, std::make_pair(b, e)); #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " STORE BLOCK CRC [ p: " << b.piece_index << " | b: " << b.block_index << " | c: " << client << " | crc: " << e.crc << " | ip: " << p->ip << " ]\n"; #endif } void on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j) { // since this callback is called directory from the disk io // thread, the session mutex is not locked when we get here aux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex); // ignore read errors if (ret != j.buffer_size) return; adler32_crc crc; crc.update(j.buffer, j.buffer_size); crc.update((char const*)&m_salt, sizeof(m_salt)); unsigned long ok_crc = crc.final(); if (b.second.crc == ok_crc) return; policy::peer* p = b.second.peer; if (p == 0) return; if (!m_torrent.get_policy().has_peer(p)) return; #ifdef TORRENT_LOGGING char const* client = "-"; peer_info info; if (p->connection) { p->connection->get_peer_info(info); client = info.client.c_str(); } (*m_torrent.session().m_logger) << time_now_string() << " BANNING PEER [ p: " << b.first.piece_index << " | b: " << b.first.block_index << " | c: " << client << " | ok_crc: " << ok_crc << " | bad_crc: " << b.second.crc << " | ip: " << p->ip << " ]\n"; #endif p->banned = true; if (p->connection) p->connection->disconnect(); } torrent& m_torrent; // This table maps a piece_block (piece and block index // pair) to a peer and the block CRC. The CRC is calculated // from the data in the block + the salt std::map<piece_block, block_entry> m_block_crc; // This salt is a random value used to calculate the block CRCs // Since the CRC function that is used is not a one way function // the salt is required to avoid attacks where bad data is sent // that is forged to match the CRC of the good data. int m_salt; }; } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*) { return boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t)); } } <|endoftext|>
<commit_before>/** * TLS Hello Messages * (C) 2004-2010 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_messages.h> #include <botan/internal/tls_reader.h> namespace Botan { /** * Encode and send a Handshake message */ void HandshakeMessage::send(Record_Writer& writer, HandshakeHash& hash) const { SecureVector<byte> buf = serialize(); SecureVector<byte> send_buf(4); u32bit buf_size = buf.size(); send_buf[0] = type(); send_buf[1] = get_byte(1, buf_size); send_buf[2] = get_byte(2, buf_size); send_buf[3] = get_byte(3, buf_size); send_buf.append(buf); hash.update(send_buf); writer.send(HANDSHAKE, send_buf, send_buf.size()); writer.flush(); } /** * Create a new Hello Request message */ Hello_Request::Hello_Request(Record_Writer& writer) { HandshakeHash dummy; // FIXME: *UGLY* send(writer, dummy); } /** * Serialize a Hello Request message */ SecureVector<byte> Hello_Request::serialize() const { return SecureVector<byte>(); } /** * Deserialize a Hello Request message */ void Hello_Request::deserialize(const MemoryRegion<byte>& buf) { if(buf.size()) throw Decoding_Error("Hello_Request: Must be empty, and is not"); } /** * Create a new Client Hello message */ Client_Hello::Client_Hello(RandomNumberGenerator& rng, Record_Writer& writer, const TLS_Policy* policy, HandshakeHash& hash) { c_random.resize(32); rng.randomize(c_random, c_random.size()); suites = policy->ciphersuites(); comp_algos = policy->compression(); c_version = policy->pref_version(); send(writer, hash); } /** * Serialize a Client Hello message */ SecureVector<byte> Client_Hello::serialize() const { SecureVector<byte> buf; buf.append(static_cast<byte>(c_version >> 8)); buf.append(static_cast<byte>(c_version )); buf.append(c_random); buf.append(static_cast<byte>(sess_id.size())); buf.append(sess_id); u16bit suites_size = 2*suites.size(); buf.append(get_byte(0, suites_size)); buf.append(get_byte(1, suites_size)); for(u32bit i = 0; i != suites.size(); i++) { buf.append(get_byte(0, suites[i])); buf.append(get_byte(1, suites[i])); } buf.append(static_cast<byte>(comp_algos.size())); for(u32bit i = 0; i != comp_algos.size(); i++) buf.append(comp_algos[i]); return buf; } void Client_Hello::deserialize_sslv2(const MemoryRegion<byte>& buf) { if(buf.size() < 12 || buf[0] != 1) throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); const u32bit cipher_spec_len = make_u16bit(buf[3], buf[4]); const u32bit sess_id_len = make_u16bit(buf[5], buf[6]); const u32bit challenge_len = make_u16bit(buf[7], buf[8]); const u32bit expected_size = (9 + sess_id_len + cipher_spec_len + challenge_len); if(buf.size() != expected_size) throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); if(sess_id_len != 0 || cipher_spec_len % 3 != 0 || (challenge_len < 16 || challenge_len > 32)) { throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); } for(u32bit i = 9; i != 9 + cipher_spec_len; i += 3) { if(buf[i] != 0) // a SSLv2 cipherspec; ignore it continue; suites.push_back(make_u16bit(buf[i+1], buf[i+2])); } c_version = static_cast<Version_Code>(make_u16bit(buf[1], buf[2])); c_random.set(&buf[9+cipher_spec_len+sess_id_len], challenge_len); } /** * Deserialize a Client Hello message */ void Client_Hello::deserialize(const MemoryRegion<byte>& buf) { if(buf.size() == 0) throw Decoding_Error("Client_Hello: Packet corrupted"); if(buf.size() < 41) throw Decoding_Error("Client_Hello: Packet corrupted"); TLS_Data_Reader reader(buf); c_version = static_cast<Version_Code>(reader.get_u16bit()); c_random = reader.get_fixed<byte>(32); sess_id = reader.get_range<byte>(1, 0, 32); suites = reader.get_range_vector<u16bit>(2, 1, 32767); comp_algos = reader.get_range_vector<byte>(1, 1, 255); if(reader.has_remaining()) { const u16bit all_extn_size = reader.get_u16bit(); if(reader.remaining_bytes() != all_extn_size) throw Decoding_Error("Client_Hello: Bad extension size"); while(reader.has_remaining()) { const u16bit extension_code = reader.get_u16bit(); const u16bit extension_size = reader.get_u16bit(); if(extension_code == TLSEXT_SERVER_NAME_INDICATION) { u16bit name_bytes = reader.get_u16bit(); while(name_bytes) { byte name_type = reader.get_byte(); name_bytes--; if(name_type == 0) // DNS { std::vector<byte> name = reader.get_range_vector<byte>(2, 1, 65535); requested_hostname.assign((const char*)&name[0], name.size()); name_bytes -= (2 + name.size()); } else { reader.discard_next(name_bytes); name_bytes = 0; } } } else { reader.discard_next(extension_size); } } } } /** * Check if we offered this ciphersuite */ bool Client_Hello::offered_suite(u16bit ciphersuite) const { for(u32bit i = 0; i != suites.size(); i++) if(suites[i] == ciphersuite) return true; return false; } /** * Create a new Server Hello message */ Server_Hello::Server_Hello(RandomNumberGenerator& rng, Record_Writer& writer, const TLS_Policy* policy, const std::vector<X509_Certificate>& certs, const Client_Hello& c_hello, Version_Code ver, HandshakeHash& hash) { bool have_rsa = false, have_dsa = false; for(u32bit i = 0; i != certs.size(); i++) { Public_Key* key = certs[i].subject_public_key(); if(key->algo_name() == "RSA") have_rsa = true; if(key->algo_name() == "DSA") have_dsa = true; } suite = policy->choose_suite(c_hello.ciphersuites(), have_rsa, have_dsa); comp_algo = policy->choose_compression(c_hello.compression_algos()); s_version = ver; s_random.resize(32); rng.randomize(s_random, s_random.size()); send(writer, hash); } /** * Serialize a Server Hello message */ SecureVector<byte> Server_Hello::serialize() const { SecureVector<byte> buf; buf.append(static_cast<byte>(s_version >> 8)); buf.append(static_cast<byte>(s_version )); buf.append(s_random); buf.append(static_cast<byte>(sess_id.size())); buf.append(sess_id); buf.append(get_byte(0, suite)); buf.append(get_byte(1, suite)); buf.append(comp_algo); return buf; } /** * Deserialize a Server Hello message */ void Server_Hello::deserialize(const MemoryRegion<byte>& buf) { if(buf.size() < 38) throw Decoding_Error("Server_Hello: Packet corrupted"); TLS_Data_Reader reader(buf); s_version = static_cast<Version_Code>(reader.get_u16bit()); if(s_version != SSL_V3 && s_version != TLS_V10 && s_version != TLS_V11) { throw TLS_Exception(PROTOCOL_VERSION, "Server_Hello: Unsupported server version"); } s_random = reader.get_fixed<byte>(32); sess_id = reader.get_range<byte>(1, 0, 32); suite = reader.get_u16bit(); comp_algo = reader.get_byte(); } /** * Create a new Server Hello Done message */ Server_Hello_Done::Server_Hello_Done(Record_Writer& writer, HandshakeHash& hash) { send(writer, hash); } /** * Serialize a Server Hello Done message */ SecureVector<byte> Server_Hello_Done::serialize() const { return SecureVector<byte>(); } /** * Deserialize a Server Hello Done message */ void Server_Hello_Done::deserialize(const MemoryRegion<byte>& buf) { if(buf.size()) throw Decoding_Error("Server_Hello_Done: Must be empty, and is not"); } } <commit_msg>If we couldn't agree on a suite, fail immediately<commit_after>/** * TLS Hello Messages * (C) 2004-2010 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_messages.h> #include <botan/internal/tls_reader.h> namespace Botan { /** * Encode and send a Handshake message */ void HandshakeMessage::send(Record_Writer& writer, HandshakeHash& hash) const { SecureVector<byte> buf = serialize(); SecureVector<byte> send_buf(4); u32bit buf_size = buf.size(); send_buf[0] = type(); send_buf[1] = get_byte(1, buf_size); send_buf[2] = get_byte(2, buf_size); send_buf[3] = get_byte(3, buf_size); send_buf.append(buf); hash.update(send_buf); writer.send(HANDSHAKE, send_buf, send_buf.size()); writer.flush(); } /** * Create a new Hello Request message */ Hello_Request::Hello_Request(Record_Writer& writer) { HandshakeHash dummy; // FIXME: *UGLY* send(writer, dummy); } /** * Serialize a Hello Request message */ SecureVector<byte> Hello_Request::serialize() const { return SecureVector<byte>(); } /** * Deserialize a Hello Request message */ void Hello_Request::deserialize(const MemoryRegion<byte>& buf) { if(buf.size()) throw Decoding_Error("Hello_Request: Must be empty, and is not"); } /** * Create a new Client Hello message */ Client_Hello::Client_Hello(RandomNumberGenerator& rng, Record_Writer& writer, const TLS_Policy* policy, HandshakeHash& hash) { c_random.resize(32); rng.randomize(c_random, c_random.size()); suites = policy->ciphersuites(); comp_algos = policy->compression(); c_version = policy->pref_version(); send(writer, hash); } /** * Serialize a Client Hello message */ SecureVector<byte> Client_Hello::serialize() const { SecureVector<byte> buf; buf.append(static_cast<byte>(c_version >> 8)); buf.append(static_cast<byte>(c_version )); buf.append(c_random); buf.append(static_cast<byte>(sess_id.size())); buf.append(sess_id); u16bit suites_size = 2*suites.size(); buf.append(get_byte(0, suites_size)); buf.append(get_byte(1, suites_size)); for(u32bit i = 0; i != suites.size(); i++) { buf.append(get_byte(0, suites[i])); buf.append(get_byte(1, suites[i])); } buf.append(static_cast<byte>(comp_algos.size())); for(u32bit i = 0; i != comp_algos.size(); i++) buf.append(comp_algos[i]); return buf; } void Client_Hello::deserialize_sslv2(const MemoryRegion<byte>& buf) { if(buf.size() < 12 || buf[0] != 1) throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); const u32bit cipher_spec_len = make_u16bit(buf[3], buf[4]); const u32bit sess_id_len = make_u16bit(buf[5], buf[6]); const u32bit challenge_len = make_u16bit(buf[7], buf[8]); const u32bit expected_size = (9 + sess_id_len + cipher_spec_len + challenge_len); if(buf.size() != expected_size) throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); if(sess_id_len != 0 || cipher_spec_len % 3 != 0 || (challenge_len < 16 || challenge_len > 32)) { throw Decoding_Error("Client_Hello: SSLv2 hello corrupted"); } for(u32bit i = 9; i != 9 + cipher_spec_len; i += 3) { if(buf[i] != 0) // a SSLv2 cipherspec; ignore it continue; suites.push_back(make_u16bit(buf[i+1], buf[i+2])); } c_version = static_cast<Version_Code>(make_u16bit(buf[1], buf[2])); c_random.set(&buf[9+cipher_spec_len+sess_id_len], challenge_len); } /** * Deserialize a Client Hello message */ void Client_Hello::deserialize(const MemoryRegion<byte>& buf) { if(buf.size() == 0) throw Decoding_Error("Client_Hello: Packet corrupted"); if(buf.size() < 41) throw Decoding_Error("Client_Hello: Packet corrupted"); TLS_Data_Reader reader(buf); c_version = static_cast<Version_Code>(reader.get_u16bit()); c_random = reader.get_fixed<byte>(32); sess_id = reader.get_range<byte>(1, 0, 32); suites = reader.get_range_vector<u16bit>(2, 1, 32767); comp_algos = reader.get_range_vector<byte>(1, 1, 255); if(reader.has_remaining()) { const u16bit all_extn_size = reader.get_u16bit(); if(reader.remaining_bytes() != all_extn_size) throw Decoding_Error("Client_Hello: Bad extension size"); while(reader.has_remaining()) { const u16bit extension_code = reader.get_u16bit(); const u16bit extension_size = reader.get_u16bit(); if(extension_code == TLSEXT_SERVER_NAME_INDICATION) { u16bit name_bytes = reader.get_u16bit(); while(name_bytes) { byte name_type = reader.get_byte(); name_bytes--; if(name_type == 0) // DNS { std::vector<byte> name = reader.get_range_vector<byte>(2, 1, 65535); requested_hostname.assign((const char*)&name[0], name.size()); name_bytes -= (2 + name.size()); } else { reader.discard_next(name_bytes); name_bytes = 0; } } } else { reader.discard_next(extension_size); } } } } /** * Check if we offered this ciphersuite */ bool Client_Hello::offered_suite(u16bit ciphersuite) const { for(u32bit i = 0; i != suites.size(); i++) if(suites[i] == ciphersuite) return true; return false; } /** * Create a new Server Hello message */ Server_Hello::Server_Hello(RandomNumberGenerator& rng, Record_Writer& writer, const TLS_Policy* policy, const std::vector<X509_Certificate>& certs, const Client_Hello& c_hello, Version_Code ver, HandshakeHash& hash) { bool have_rsa = false, have_dsa = false; for(u32bit i = 0; i != certs.size(); i++) { Public_Key* key = certs[i].subject_public_key(); if(key->algo_name() == "RSA") have_rsa = true; if(key->algo_name() == "DSA") have_dsa = true; } suite = policy->choose_suite(c_hello.ciphersuites(), have_rsa, have_dsa); if(suite == 0) throw TLS_Exception(PROTOCOL_VERSION, "Can't agree on a ciphersuite with client"); comp_algo = policy->choose_compression(c_hello.compression_algos()); s_version = ver; s_random.resize(32); rng.randomize(s_random, s_random.size()); send(writer, hash); } /** * Serialize a Server Hello message */ SecureVector<byte> Server_Hello::serialize() const { SecureVector<byte> buf; buf.append(static_cast<byte>(s_version >> 8)); buf.append(static_cast<byte>(s_version )); buf.append(s_random); buf.append(static_cast<byte>(sess_id.size())); buf.append(sess_id); buf.append(get_byte(0, suite)); buf.append(get_byte(1, suite)); buf.append(comp_algo); return buf; } /** * Deserialize a Server Hello message */ void Server_Hello::deserialize(const MemoryRegion<byte>& buf) { if(buf.size() < 38) throw Decoding_Error("Server_Hello: Packet corrupted"); TLS_Data_Reader reader(buf); s_version = static_cast<Version_Code>(reader.get_u16bit()); if(s_version != SSL_V3 && s_version != TLS_V10 && s_version != TLS_V11) { throw TLS_Exception(PROTOCOL_VERSION, "Server_Hello: Unsupported server version"); } s_random = reader.get_fixed<byte>(32); sess_id = reader.get_range<byte>(1, 0, 32); suite = reader.get_u16bit(); comp_algo = reader.get_byte(); } /** * Create a new Server Hello Done message */ Server_Hello_Done::Server_Hello_Done(Record_Writer& writer, HandshakeHash& hash) { send(writer, hash); } /** * Serialize a Server Hello Done message */ SecureVector<byte> Server_Hello_Done::serialize() const { return SecureVector<byte>(); } /** * Deserialize a Server Hello Done message */ void Server_Hello_Done::deserialize(const MemoryRegion<byte>& buf) { if(buf.size()) throw Decoding_Error("Server_Hello_Done: Must be empty, and is not"); } } <|endoftext|>
<commit_before>/* stalkware.cpp - stalkware(1) launcher * stalkware - blah bleh - (C) 2013, Timo Buhrmester * See README for contact-, COPYING for license information. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <cstdio> #include <cstdlib> #include <cstring> #include <getopt.h> #include "Kernel.h" using std::string; static char *g_stalkrc_path; static void process_args(int *argc, char ***argv); static void init(int *argc, char ***argv); static void usage(FILE *str, const char *a0, int ec); static void process_args(int *argc, char ***argv) { char *a0 = (*argv)[0]; for(int ch; (ch = getopt(*argc, *argv, "hf:")) != -1;) { switch (ch) { case 'h': usage(stdout, a0, EXIT_SUCCESS); break; case 'f': g_stalkrc_path = strdup(optarg); break; case '?': default: usage(stderr, a0, EXIT_FAILURE); } } *argc -= optind; *argv += optind; } static void init(int *argc, char ***argv) { process_args(argc, argv); if (!g_stalkrc_path || strlen(g_stalkrc_path) == 0) { char path[256]; const char *home = getenv("HOME"); if (!home) { fprintf(stderr, "no $HOME defined, using cwd\n"); home = "."; } snprintf(path, sizeof path, "%s/.stalkrc", home); g_stalkrc_path = strdup(path); } } static void usage(FILE *str, const char *a0, int ec) { #define I(STR) fputs(STR "\n", str) I("==========================="); I("== stalkware - blah bleh =="); I("==========================="); fprintf(str, "usage: %s [-h]\n", a0); I(""); I("\t-h: Display brief usage statement and terminate"); I(""); I("(C) 2013, Timo Buhrmester (contact: #fstd @ irc.freenode.org)"); #undef I exit(ec); } int main(int argc, char **argv) { init(&argc, &argv); Kernel *k = new Kernel; k->init(string(g_stalkrc_path)); bool ok = k->run(); delete k; return ok ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>update usage statement<commit_after>/* stalkware.cpp - stalkware(1) launcher * stalkware - blah bleh - (C) 2013, Timo Buhrmester * See README for contact-, COPYING for license information. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <cstdio> #include <cstdlib> #include <cstring> #include <getopt.h> #include "Kernel.h" using std::string; static char *g_stalkrc_path; static void process_args(int *argc, char ***argv); static void init(int *argc, char ***argv); static void usage(FILE *str, const char *a0, int ec); static void process_args(int *argc, char ***argv) { char *a0 = (*argv)[0]; for(int ch; (ch = getopt(*argc, *argv, "hf:")) != -1;) { switch (ch) { case 'h': usage(stdout, a0, EXIT_SUCCESS); break; case 'f': g_stalkrc_path = strdup(optarg); break; case '?': default: usage(stderr, a0, EXIT_FAILURE); } } *argc -= optind; *argv += optind; } static void init(int *argc, char ***argv) { process_args(argc, argv); if (!g_stalkrc_path || strlen(g_stalkrc_path) == 0) { char path[256]; const char *home = getenv("HOME"); if (!home) { fprintf(stderr, "no $HOME defined, using cwd\n"); home = "."; } snprintf(path, sizeof path, "%s/.stalkrc", home); g_stalkrc_path = strdup(path); } } static void usage(FILE *str, const char *a0, int ec) { #define I(STR) fputs(STR "\n", str) I("==========================="); I("== stalkware - blah bleh =="); I("==========================="); fprintf(str, "usage: %s [-h]\n", a0); I(""); I("\t-h: Display brief usage statement and terminate"); I("\t-f <path>: use this rcfile (default ~/.stalkrc)"); I(""); I("(C) 2013, Timo Buhrmester (contact: #fstd @ irc.freenode.org)"); #undef I exit(ec); } int main(int argc, char **argv) { init(&argc, &argv); Kernel *k = new Kernel; k->init(string(g_stalkrc_path)); bool ok = k->run(); delete k; return ok ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: asyncfilepicker.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-11-11 11:39:20 $ * * 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 "asyncfilepicker.hxx" #ifndef _IODLGIMPL_HXX #include "iodlg.hxx" #endif #ifndef _SVT_FILEVIEW_HXX #include "svtools/fileview.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include <memory> //........................................................................ namespace svt { //........................................................................ //==================================================================== //= AsyncPickerAction //==================================================================== DBG_NAME( AsyncPickerAction ) //-------------------------------------------------------------------- AsyncPickerAction::AsyncPickerAction( SvtFileDialog* _pDialog, SvtFileView* _pView, const Action _eAction ) :m_refCount ( 0 ) ,m_pDialog ( _pDialog ) ,m_pView ( _pView ) ,m_eAction ( _eAction ) ,m_bRunning ( false ) { DBG_CTOR( AsyncPickerAction, NULL ); DBG_ASSERT( m_pDialog, "AsyncPickerAction::AsyncPickerAction: invalid dialog!" ); DBG_ASSERT( m_pView, "AsyncPickerAction::AsyncPickerAction: invalid view!" ); } //-------------------------------------------------------------------- AsyncPickerAction::~AsyncPickerAction() { DBG_DTOR( AsyncPickerAction, NULL ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AsyncPickerAction::acquire() { return osl_incrementInterlockedCount( &m_refCount ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AsyncPickerAction::release() { if ( 0 == osl_decrementInterlockedCount( &m_refCount ) ) { delete this; return 0; } return m_refCount; } //-------------------------------------------------------------------- void AsyncPickerAction::cancel() { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance OSL_ENSURE( m_bRunning, "AsyncPickerAction::cancel: not running" ); if ( m_pView ) m_pView->CancelRunningAsyncAction(); } //-------------------------------------------------------------------- void AsyncPickerAction::execute( const String& _rURL, const String& _rFilter, sal_Int32 _nMinTimeout, sal_Int32 _nMaxTimeout ) { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance sal_Int32 nMinTimeout = _nMinTimeout; sal_Int32 nMaxTimeout = _nMaxTimeout; // normalizations if ( nMinTimeout < 0 ) // if negative, this is considered as "do it synchronously" nMinTimeout = 0; else if ( nMinTimeout < 1000 ) nMinTimeout = 1000; if ( nMaxTimeout <= nMinTimeout ) nMaxTimeout = nMinTimeout + 30000; ::std::auto_ptr< FileViewAsyncAction > pActionDescriptor; if ( nMinTimeout ) { pActionDescriptor.reset( new FileViewAsyncAction ); pActionDescriptor->nMinTimeout = nMinTimeout; pActionDescriptor->nMaxTimeout = nMaxTimeout; pActionDescriptor->aFinishHandler = LINK( this, AsyncPickerAction, OnActionDone ); } FileViewResult eResult = eFailure; m_sURL = _rURL; switch ( m_eAction ) { case ePrevLevel: eResult = m_pView->PreviousLevel( pActionDescriptor.get() ); break; case eOpenURL: eResult = m_pView->Initialize( _rURL, _rFilter, pActionDescriptor.get() ); break; case eExecuteFilter: // preserve the filename (FS: why?) m_sFileName = m_pDialog->getCurrentFileText(); // execute the new filter eResult = m_pView->ExecuteFilter( _rFilter, pActionDescriptor.get() ); break; default: DBG_ERROR( "AsyncPickerAction::execute: unknown action!" ); break; } acquire(); if ( ( eResult == eSuccess ) || ( eResult == eFailure ) ) { // the handler is only called if the action could not be finished within // the given minimum time period. In case of success, we need to call it // explicitly OnActionDone( reinterpret_cast< void* >( eResult ) ); } else if ( eResult == eStillRunning ) { m_bRunning = true; m_pDialog->onAsyncOperationStarted(); } } //-------------------------------------------------------------------- IMPL_LINK( AsyncPickerAction, OnActionDone, void*, pEmptyArg ) { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance FileViewResult eResult = static_cast< FileViewResult >( reinterpret_cast< sal_IntPtr >( pEmptyArg ) ); OSL_ENSURE( eStillRunning != eResult, "AsyncPickerAction::OnActionDone: invalid result!" ); // release once (since we acquired in |execute|), but keep alive until the // end of the method ::rtl::Reference< AsyncPickerAction > xKeepAlive( this ); release(); m_pDialog->onAsyncOperationFinished(); m_bRunning = true; if ( eFailure == eResult ) // TODO: do we need some kind of cleanup here? return 0L; if ( eTimeout == eResult ) { m_pDialog->displayIOException( m_sURL, ::com::sun::star::ucb::IOErrorCode_CANT_READ ); return 0L; } OSL_ENSURE( eSuccess == eResult, "AsyncPickerAction::OnActionDone: what else valid results are there?" ); switch ( m_eAction ) { case ePrevLevel: case eOpenURL: m_pDialog->UpdateControls( m_pView->GetViewURL() ); break; case eExecuteFilter: // restore the filename m_pView->SetNoSelection(); m_pDialog->setCurrentFileText( m_sFileName, true ); // notify listeners m_pDialog->FilterSelect(); break; default: DBG_ERROR( "AsyncPickerAction::OnActionDone: unknown action!" ); break; } return 1L; } //........................................................................ } // namespace svt //........................................................................ <commit_msg>INTEGRATION: CWS warnings01 (1.3.10); FILE MERGED 2006/01/25 20:29:41 sb 1.3.10.3: RESYNC: (1.4-1.5); FILE MERGED 2005/11/07 18:55:32 pl 1.3.10.2: RESYNC: (1.3-1.4); FILE MERGED 2005/10/27 10:43:16 os 1.3.10.1: #i53898# warnings removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: asyncfilepicker.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 00:12:17 $ * * 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 "asyncfilepicker.hxx" #ifndef _IODLGIMPL_HXX #include "iodlg.hxx" #endif #ifndef _SVT_FILEVIEW_HXX #include "svtools/fileview.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include <memory> //........................................................................ namespace svt { //........................................................................ //==================================================================== //= AsyncPickerAction //==================================================================== DBG_NAME( AsyncPickerAction ) //-------------------------------------------------------------------- AsyncPickerAction::AsyncPickerAction( SvtFileDialog* _pDialog, SvtFileView* _pView, const Action _eAction ) :m_refCount ( 0 ) ,m_eAction ( _eAction ) ,m_pView ( _pView ) ,m_pDialog ( _pDialog ) ,m_bRunning ( false ) { DBG_CTOR( AsyncPickerAction, NULL ); DBG_ASSERT( m_pDialog, "AsyncPickerAction::AsyncPickerAction: invalid dialog!" ); DBG_ASSERT( m_pView, "AsyncPickerAction::AsyncPickerAction: invalid view!" ); } //-------------------------------------------------------------------- AsyncPickerAction::~AsyncPickerAction() { DBG_DTOR( AsyncPickerAction, NULL ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AsyncPickerAction::acquire() { return osl_incrementInterlockedCount( &m_refCount ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AsyncPickerAction::release() { if ( 0 == osl_decrementInterlockedCount( &m_refCount ) ) { delete this; return 0; } return m_refCount; } //-------------------------------------------------------------------- void AsyncPickerAction::cancel() { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance OSL_ENSURE( m_bRunning, "AsyncPickerAction::cancel: not running" ); if ( m_pView ) m_pView->CancelRunningAsyncAction(); } //-------------------------------------------------------------------- void AsyncPickerAction::execute( const String& _rURL, const String& _rFilter, sal_Int32 _nMinTimeout, sal_Int32 _nMaxTimeout ) { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance sal_Int32 nMinTimeout = _nMinTimeout; sal_Int32 nMaxTimeout = _nMaxTimeout; // normalizations if ( nMinTimeout < 0 ) // if negative, this is considered as "do it synchronously" nMinTimeout = 0; else if ( nMinTimeout < 1000 ) nMinTimeout = 1000; if ( nMaxTimeout <= nMinTimeout ) nMaxTimeout = nMinTimeout + 30000; ::std::auto_ptr< FileViewAsyncAction > pActionDescriptor; if ( nMinTimeout ) { pActionDescriptor.reset( new FileViewAsyncAction ); pActionDescriptor->nMinTimeout = nMinTimeout; pActionDescriptor->nMaxTimeout = nMaxTimeout; pActionDescriptor->aFinishHandler = LINK( this, AsyncPickerAction, OnActionDone ); } FileViewResult eResult = eFailure; m_sURL = _rURL; switch ( m_eAction ) { case ePrevLevel: eResult = m_pView->PreviousLevel( pActionDescriptor.get() ); break; case eOpenURL: eResult = m_pView->Initialize( _rURL, _rFilter, pActionDescriptor.get() ); break; case eExecuteFilter: // preserve the filename (FS: why?) m_sFileName = m_pDialog->getCurrentFileText(); // execute the new filter eResult = m_pView->ExecuteFilter( _rFilter, pActionDescriptor.get() ); break; default: DBG_ERROR( "AsyncPickerAction::execute: unknown action!" ); break; } acquire(); if ( ( eResult == eSuccess ) || ( eResult == eFailure ) ) { // the handler is only called if the action could not be finished within // the given minimum time period. In case of success, we need to call it // explicitly OnActionDone( reinterpret_cast< void* >( eResult ) ); } else if ( eResult == eStillRunning ) { m_bRunning = true; m_pDialog->onAsyncOperationStarted(); } } //-------------------------------------------------------------------- IMPL_LINK( AsyncPickerAction, OnActionDone, void*, pEmptyArg ) { DBG_TESTSOLARMUTEX(); // if this asserts, we'd need to have an own mutex per instance FileViewResult eResult = static_cast< FileViewResult >( reinterpret_cast< sal_IntPtr >( pEmptyArg ) ); OSL_ENSURE( eStillRunning != eResult, "AsyncPickerAction::OnActionDone: invalid result!" ); // release once (since we acquired in |execute|), but keep alive until the // end of the method ::rtl::Reference< AsyncPickerAction > xKeepAlive( this ); release(); m_pDialog->onAsyncOperationFinished(); m_bRunning = true; if ( eFailure == eResult ) // TODO: do we need some kind of cleanup here? return 0L; if ( eTimeout == eResult ) { m_pDialog->displayIOException( m_sURL, ::com::sun::star::ucb::IOErrorCode_CANT_READ ); return 0L; } OSL_ENSURE( eSuccess == eResult, "AsyncPickerAction::OnActionDone: what else valid results are there?" ); switch ( m_eAction ) { case ePrevLevel: case eOpenURL: m_pDialog->UpdateControls( m_pView->GetViewURL() ); break; case eExecuteFilter: // restore the filename m_pView->SetNoSelection(); m_pDialog->setCurrentFileText( m_sFileName, true ); // notify listeners m_pDialog->FilterSelect(); break; default: DBG_ERROR( "AsyncPickerAction::OnActionDone: unknown action!" ); break; } return 1L; } //........................................................................ } // namespace svt //........................................................................ <|endoftext|>
<commit_before>// // Program Name - S7_Pointer_to_pointer.cpp // Series: GetOnToC++ Step: 7 // // Purpose: This program illustrates how to use arrays in functions // // Compile: g++ S7_Pointer_to_pointer.cpp -o S7_Pointer_to_pointer // Execute: ./S7_Pointer_to_pointer // // Created by Abinav Janakiraman on 15/9/13. // #include <iostream> using namespace std; int main(){ int x = 4; int y = 5; int *a = &x; int *b = &y; int **c = &a; cout << "*a = " << *a << endl << "*b = " << *b << endl; *c = &y; cout << "*a now = " << *a << endl << "*b now = " << *b << endl; return 0; } <commit_msg>Update S7_Pointer_to_pointer.cpp<commit_after>// // Program Name - S7_Pointer_to_pointer.cpp // Series: GetOnToC++ Step: 7 // // Purpose: This program illustrates how to use a pointer to a pointer. // // Compile: g++ S7_Pointer_to_pointer.cpp -o S7_Pointer_to_pointer // Execute: ./S7_Pointer_to_pointer // // Created by Abinav Janakiraman on 15/9/13. // #include <iostream> using namespace std; int main(){ int x = 4; int y = 5; int *a = &x; int *b = &y; int **c = &a; cout << "*a = " << *a << endl << "*b = " << *b << endl; *c = &y; cout << "*a now = " << *a << endl << "*b now = " << *b << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: urltransformer.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:01:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #define __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_OMUTEXMEMBER_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_URL_HPP_ #include <com/sun/star/util/URL.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short @descr - @implements XInterface XTypeProvider XServiceInfo XURLTransformer @base ThreadHelpBase OWeakObject *//*-*************************************************************************************************************/ class URLTransformer : public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::util::XURLTransformer , public ThreadHelpBase , public ::cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ URLTransformer( const css::uno::Reference< css::lang::XMultiServiceFactory >& sFactory ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ~URLTransformer(); //--------------------------------------------------------------------------------------------------------- // XInterface, XTypeProvider, XServiceInfo //--------------------------------------------------------------------------------------------------------- FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO //--------------------------------------------------------------------------------------------------------- // XURLTransformer //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL parseStrict( css::util::URL& aURL ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL parseSmart( css::util::URL& aURL , const ::rtl::OUString& sSmartProtocol ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL assemble( css::util::URL& aURL ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ::rtl::OUString SAL_CALL getPresentation( const css::util::URL& aURL , sal_Bool bWithPassword ) throw( css::uno::RuntimeException ); //------------------------------------------------------------------------------------------------------------- // protected methods //------------------------------------------------------------------------------------------------------------- protected: //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: //------------------------------------------------------------------------------------------------------------- // debug methods // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- // variables // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- private: css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// reference to factory, which has created this instance }; // class URLTransformer } // namespace framework #endif // #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.7.318); FILE MERGED 2008/04/01 15:18:24 thb 1.7.318.3: #i85898# Stripping all external header guards 2008/04/01 10:57:53 thb 1.7.318.2: #i85898# Stripping all external header guards 2008/03/28 15:34:51 rt 1.7.318.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: urltransformer.hxx,v $ * $Revision: 1.8 $ * * 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 __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ #define __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_OMUTEXMEMBER_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #include <macros/generic.hxx> #include <macros/debug.hxx> #include <macros/xinterface.hxx> #include <macros/xtypeprovider.hxx> #include <macros/xserviceinfo.hxx> #include <general.h> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/util/XURLTransformer.hpp> #include <com/sun/star/util/URL.hpp> //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <cppuhelper/weak.hxx> //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short @descr - @implements XInterface XTypeProvider XServiceInfo XURLTransformer @base ThreadHelpBase OWeakObject *//*-*************************************************************************************************************/ class URLTransformer : public css::lang::XTypeProvider , public css::lang::XServiceInfo , public css::util::XURLTransformer , public ThreadHelpBase , public ::cppu::OWeakObject { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ URLTransformer( const css::uno::Reference< css::lang::XMultiServiceFactory >& sFactory ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ~URLTransformer(); //--------------------------------------------------------------------------------------------------------- // XInterface, XTypeProvider, XServiceInfo //--------------------------------------------------------------------------------------------------------- FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO //--------------------------------------------------------------------------------------------------------- // XURLTransformer //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL parseStrict( css::util::URL& aURL ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL parseSmart( css::util::URL& aURL , const ::rtl::OUString& sSmartProtocol ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual sal_Bool SAL_CALL assemble( css::util::URL& aURL ) throw( css::uno::RuntimeException ); /*-****************************************************************************************************//** @short - @descr - @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ virtual ::rtl::OUString SAL_CALL getPresentation( const css::util::URL& aURL , sal_Bool bWithPassword ) throw( css::uno::RuntimeException ); //------------------------------------------------------------------------------------------------------------- // protected methods //------------------------------------------------------------------------------------------------------------- protected: //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: //------------------------------------------------------------------------------------------------------------- // debug methods // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- // variables // (should be private everyway!) //------------------------------------------------------------------------------------------------------------- private: css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory ; /// reference to factory, which has created this instance }; // class URLTransformer } // namespace framework #endif // #ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_ <|endoftext|>
<commit_before>//===------------------------ strstream.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 "strstream" #include "algorithm" #include "climits" #include "cstring" _LIBCPP_BEGIN_NAMESPACE_STD strstreambuf::strstreambuf(streamsize __alsize) : __strmode_(__dynamic), __alsize_(__alsize), __palloc_(nullptr), __pfree_(nullptr) { } strstreambuf::strstreambuf(void* (*__palloc)(size_t), void (*__pfree)(void*)) : __strmode_(__dynamic), __alsize_(__default_alsize), __palloc_(__palloc), __pfree_(__pfree) { } void strstreambuf::__init(char* __gnext, streamsize __n, char* __pbeg) { if (__n == 0) __n = static_cast<streamsize>(strlen(__gnext)); else if (__n < 0) __n = INT_MAX; if (__pbeg == nullptr) setg(__gnext, __gnext, __gnext + __n); else { setg(__gnext, __gnext, __pbeg); setp(__pbeg, __pbeg + __n); } } strstreambuf::strstreambuf(char* __gnext, streamsize __n, char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init(__gnext, __n, __pbeg); } strstreambuf::strstreambuf(const char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::strstreambuf(signed char* __gnext, streamsize __n, signed char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, (char*)__pbeg); } strstreambuf::strstreambuf(const signed char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::strstreambuf(unsigned char* __gnext, streamsize __n, unsigned char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, (char*)__pbeg); } strstreambuf::strstreambuf(const unsigned char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::~strstreambuf() { if (eback() && (__strmode_ & __allocated) != 0 && (__strmode_ & __frozen) == 0) { if (__pfree_) __pfree_(eback()); else delete [] eback(); } } void strstreambuf::swap(strstreambuf& __rhs) { streambuf::swap(__rhs); _VSTD::swap(__strmode_, __rhs.__strmode_); _VSTD::swap(__alsize_, __rhs.__alsize_); _VSTD::swap(__palloc_, __rhs.__palloc_); _VSTD::swap(__pfree_, __rhs.__pfree_); } void strstreambuf::freeze(bool __freezefl) { if (__strmode_ & __dynamic) { if (__freezefl) __strmode_ |= __frozen; else __strmode_ &= ~__frozen; } } char* strstreambuf::str() { if (__strmode_ & __dynamic) __strmode_ |= __frozen; return eback(); } int strstreambuf::pcount() const { return static_cast<int>(pptr() - pbase()); } strstreambuf::int_type strstreambuf::overflow(int_type __c) { if (__c == EOF) return int_type(0); if (pptr() == epptr()) { if ((__strmode_ & __dynamic) == 0 || (__strmode_ & __frozen) != 0) return int_type(EOF); streamsize old_size = (epptr() ? epptr() : egptr()) - eback(); streamsize new_size = max<streamsize>(__alsize_, 2*old_size); if (new_size == 0) new_size = __default_alsize; char* buf = nullptr; if (__palloc_) buf = static_cast<char*>(__palloc_(static_cast<size_t>(new_size))); else buf = new char[new_size]; if (buf == nullptr) return int_type(EOF); memcpy(buf, eback(), static_cast<size_t>(old_size)); ptrdiff_t ninp = gptr() - eback(); ptrdiff_t einp = egptr() - eback(); ptrdiff_t nout = pptr() - pbase(); ptrdiff_t eout = epptr() - pbase(); if (__strmode_ & __allocated) { if (__pfree_) __pfree_(eback()); else delete [] eback(); } setg(buf, buf + ninp, buf + einp); setp(buf + einp, buf + einp + eout); pbump(static_cast<int>(nout)); __strmode_ |= __allocated; } *pptr() = static_cast<char>(__c); pbump(1); return int_type((unsigned char)__c); } strstreambuf::int_type strstreambuf::pbackfail(int_type __c) { if (eback() == gptr()) return EOF; if (__c == EOF) { gbump(-1); return int_type(0); } if (__strmode_ & __constant) { if (gptr()[-1] == static_cast<char>(__c)) { gbump(-1); return __c; } return EOF; } gbump(-1); *gptr() = static_cast<char>(__c); return __c; } strstreambuf::int_type strstreambuf::underflow() { if (gptr() == egptr()) { if (egptr() >= pptr()) return EOF; setg(eback(), gptr(), pptr()); } return int_type((unsigned char)*gptr()); } strstreambuf::pos_type strstreambuf::seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __which) { off_type __p(-1); bool pos_in = __which & ios::in; bool pos_out = __which & ios::out; bool legal = false; switch (__way) { case ios::beg: case ios::end: if (pos_in || pos_out) legal = true; break; case ios::cur: if (pos_in != pos_out) legal = true; break; } if (pos_in && gptr() == nullptr) legal = false; if (pos_out && pptr() == nullptr) legal = false; if (legal) { off_type newoff; char* seekhigh = epptr() ? epptr() : egptr(); switch (__way) { case ios::beg: newoff = 0; break; case ios::cur: newoff = (pos_in ? gptr() : pptr()) - eback(); break; case ios::end: newoff = seekhigh - eback(); break; } newoff += __off; if (0 <= newoff && newoff <= seekhigh - eback()) { char* newpos = eback() + newoff; if (pos_in) setg(eback(), newpos, _VSTD::max(newpos, egptr())); if (pos_out) { // min(pbase, newpos), newpos, epptr() __off = epptr() - newpos; setp(min(pbase(), newpos), epptr()); pbump(static_cast<int>((epptr() - pbase()) - __off)); } __p = newoff; } } return pos_type(__p); } strstreambuf::pos_type strstreambuf::seekpos(pos_type __sp, ios_base::openmode __which) { off_type __p(-1); bool pos_in = __which & ios::in; bool pos_out = __which & ios::out; if (pos_in || pos_out) { if (!((pos_in && gptr() == nullptr) || (pos_out && pptr() == nullptr))) { off_type newoff = __sp; char* seekhigh = epptr() ? epptr() : egptr(); if (0 <= newoff && newoff <= seekhigh - eback()) { char* newpos = eback() + newoff; if (pos_in) setg(eback(), newpos, _VSTD::max(newpos, egptr())); if (pos_out) { // min(pbase, newpos), newpos, epptr() off_type temp = epptr() - newpos; setp(min(pbase(), newpos), epptr()); pbump(static_cast<int>((epptr() - pbase()) - temp)); } __p = newoff; } } } return pos_type(__p); } istrstream::~istrstream() { } ostrstream::~ostrstream() { } strstream::~strstream() { } _LIBCPP_END_NAMESPACE_STD <commit_msg>Fix signed/unsigned warnings when building libc++ in C++14 mode<commit_after>//===------------------------ strstream.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 "strstream" #include "algorithm" #include "climits" #include "cstring" _LIBCPP_BEGIN_NAMESPACE_STD strstreambuf::strstreambuf(streamsize __alsize) : __strmode_(__dynamic), __alsize_(__alsize), __palloc_(nullptr), __pfree_(nullptr) { } strstreambuf::strstreambuf(void* (*__palloc)(size_t), void (*__pfree)(void*)) : __strmode_(__dynamic), __alsize_(__default_alsize), __palloc_(__palloc), __pfree_(__pfree) { } void strstreambuf::__init(char* __gnext, streamsize __n, char* __pbeg) { if (__n == 0) __n = static_cast<streamsize>(strlen(__gnext)); else if (__n < 0) __n = INT_MAX; if (__pbeg == nullptr) setg(__gnext, __gnext, __gnext + __n); else { setg(__gnext, __gnext, __pbeg); setp(__pbeg, __pbeg + __n); } } strstreambuf::strstreambuf(char* __gnext, streamsize __n, char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init(__gnext, __n, __pbeg); } strstreambuf::strstreambuf(const char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::strstreambuf(signed char* __gnext, streamsize __n, signed char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, (char*)__pbeg); } strstreambuf::strstreambuf(const signed char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::strstreambuf(unsigned char* __gnext, streamsize __n, unsigned char* __pbeg) : __strmode_(), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, (char*)__pbeg); } strstreambuf::strstreambuf(const unsigned char* __gnext, streamsize __n) : __strmode_(__constant), __alsize_(__default_alsize), __palloc_(nullptr), __pfree_(nullptr) { __init((char*)__gnext, __n, nullptr); } strstreambuf::~strstreambuf() { if (eback() && (__strmode_ & __allocated) != 0 && (__strmode_ & __frozen) == 0) { if (__pfree_) __pfree_(eback()); else delete [] eback(); } } void strstreambuf::swap(strstreambuf& __rhs) { streambuf::swap(__rhs); _VSTD::swap(__strmode_, __rhs.__strmode_); _VSTD::swap(__alsize_, __rhs.__alsize_); _VSTD::swap(__palloc_, __rhs.__palloc_); _VSTD::swap(__pfree_, __rhs.__pfree_); } void strstreambuf::freeze(bool __freezefl) { if (__strmode_ & __dynamic) { if (__freezefl) __strmode_ |= __frozen; else __strmode_ &= ~__frozen; } } char* strstreambuf::str() { if (__strmode_ & __dynamic) __strmode_ |= __frozen; return eback(); } int strstreambuf::pcount() const { return static_cast<int>(pptr() - pbase()); } strstreambuf::int_type strstreambuf::overflow(int_type __c) { if (__c == EOF) return int_type(0); if (pptr() == epptr()) { if ((__strmode_ & __dynamic) == 0 || (__strmode_ & __frozen) != 0) return int_type(EOF); size_t old_size = static_cast<size_t> ((epptr() ? epptr() : egptr()) - eback()); size_t new_size = max<size_t>(static_cast<size_t>(__alsize_), 2*old_size); if (new_size == 0) new_size = __default_alsize; char* buf = nullptr; if (__palloc_) buf = static_cast<char*>(__palloc_(new_size)); else buf = new char[new_size]; if (buf == nullptr) return int_type(EOF); memcpy(buf, eback(), static_cast<size_t>(old_size)); ptrdiff_t ninp = gptr() - eback(); ptrdiff_t einp = egptr() - eback(); ptrdiff_t nout = pptr() - pbase(); ptrdiff_t eout = epptr() - pbase(); if (__strmode_ & __allocated) { if (__pfree_) __pfree_(eback()); else delete [] eback(); } setg(buf, buf + ninp, buf + einp); setp(buf + einp, buf + einp + eout); pbump(static_cast<int>(nout)); __strmode_ |= __allocated; } *pptr() = static_cast<char>(__c); pbump(1); return int_type((unsigned char)__c); } strstreambuf::int_type strstreambuf::pbackfail(int_type __c) { if (eback() == gptr()) return EOF; if (__c == EOF) { gbump(-1); return int_type(0); } if (__strmode_ & __constant) { if (gptr()[-1] == static_cast<char>(__c)) { gbump(-1); return __c; } return EOF; } gbump(-1); *gptr() = static_cast<char>(__c); return __c; } strstreambuf::int_type strstreambuf::underflow() { if (gptr() == egptr()) { if (egptr() >= pptr()) return EOF; setg(eback(), gptr(), pptr()); } return int_type((unsigned char)*gptr()); } strstreambuf::pos_type strstreambuf::seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __which) { off_type __p(-1); bool pos_in = __which & ios::in; bool pos_out = __which & ios::out; bool legal = false; switch (__way) { case ios::beg: case ios::end: if (pos_in || pos_out) legal = true; break; case ios::cur: if (pos_in != pos_out) legal = true; break; } if (pos_in && gptr() == nullptr) legal = false; if (pos_out && pptr() == nullptr) legal = false; if (legal) { off_type newoff; char* seekhigh = epptr() ? epptr() : egptr(); switch (__way) { case ios::beg: newoff = 0; break; case ios::cur: newoff = (pos_in ? gptr() : pptr()) - eback(); break; case ios::end: newoff = seekhigh - eback(); break; } newoff += __off; if (0 <= newoff && newoff <= seekhigh - eback()) { char* newpos = eback() + newoff; if (pos_in) setg(eback(), newpos, _VSTD::max(newpos, egptr())); if (pos_out) { // min(pbase, newpos), newpos, epptr() __off = epptr() - newpos; setp(min(pbase(), newpos), epptr()); pbump(static_cast<int>((epptr() - pbase()) - __off)); } __p = newoff; } } return pos_type(__p); } strstreambuf::pos_type strstreambuf::seekpos(pos_type __sp, ios_base::openmode __which) { off_type __p(-1); bool pos_in = __which & ios::in; bool pos_out = __which & ios::out; if (pos_in || pos_out) { if (!((pos_in && gptr() == nullptr) || (pos_out && pptr() == nullptr))) { off_type newoff = __sp; char* seekhigh = epptr() ? epptr() : egptr(); if (0 <= newoff && newoff <= seekhigh - eback()) { char* newpos = eback() + newoff; if (pos_in) setg(eback(), newpos, _VSTD::max(newpos, egptr())); if (pos_out) { // min(pbase, newpos), newpos, epptr() off_type temp = epptr() - newpos; setp(min(pbase(), newpos), epptr()); pbump(static_cast<int>((epptr() - pbase()) - temp)); } __p = newoff; } } } return pos_type(__p); } istrstream::~istrstream() { } ostrstream::~ostrstream() { } strstream::~strstream() { } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>#include "CloudBasicLayerRenderer.h" #include "CloudLayerDefinition.h" #include "SoftwareRenderer.h" #include "NoiseGenerator.h" #include "Curve.h" #include "AtmosphereRenderer.h" #include "AtmosphereResult.h" #include "LightComponent.h" #include "clouds/BaseCloudsModel.h" #include "SurfaceMaterial.h" typedef struct { Vector3 start; Vector3 end; double length; } CloudSegment; CloudBasicLayerRenderer::CloudBasicLayerRenderer(SoftwareRenderer* parent): BaseCloudLayerRenderer(parent) { } static inline double _getDistanceToBorder(BaseCloudsModel* model, Vector3 position) { return model->getDensity(position); } /** * Go through the cloud layer to find segments (parts of the lookup that are inside the cloud). * * @param definition The cloud layer * @param renderer The renderer environment * @param start Start position of the lookup (already optimized) * @param direction Normalized direction of the lookup * @param detail Level of noise detail required * @param max_segments Maximum number of segments to collect * @param max_inside_length Maximum length to spend inside the cloud * @param max_total_length Maximum lookup length * @param inside_length Resulting length inside cloud (sum of all segments length) * @param total_length Resulting lookup length * @param out_segments Allocated space to fill found segments * @return Number of segments found */ static int _findSegments(BaseCloudsModel* model, SoftwareRenderer* renderer, Vector3 start, Vector3 direction, double, int max_segments, double max_inside_length, double max_total_length, double* inside_length, double* total_length, CloudSegment* out_segments) { CloudLayerDefinition* layer = model->getLayer(); double ymin, ymax; int inside, segment_count; double current_total_length, current_inside_length; double step_length, segment_length; double noise_distance, last_noise_distance; Vector3 walker, step, segment_start; double render_precision; if (max_segments <= 0) { return 0; } model->getAltitudeRange(&ymin, &ymax); render_precision = 15.2 - 1.5 * (double)renderer->render_quality; render_precision = render_precision * layer->scaling / 50.0; if (render_precision > max_total_length / 10.0) { render_precision = max_total_length / 10.0; } else if (render_precision < max_total_length / 2000.0) { render_precision = max_total_length / 2000.0; } segment_count = 0; current_total_length = 0.0; current_inside_length = 0.0; segment_length = 0.0; walker = start; noise_distance = _getDistanceToBorder(model, start) * render_precision; inside = 0; step = direction.scale(render_precision); do { walker = walker.add(step); step_length = step.getNorm(); last_noise_distance = noise_distance; noise_distance = _getDistanceToBorder(model, walker) * render_precision; current_total_length += step_length; if (noise_distance > 0.0) { if (inside) { // inside the cloud segment_length += step_length; current_inside_length += step_length; step = direction.scale((noise_distance < render_precision) ? render_precision : noise_distance); } else { // entering the cloud inside = 1; segment_length = 0.0; segment_start = walker; current_inside_length += segment_length; step = direction.scale(render_precision); } } else { if (inside) { // exiting the cloud segment_length += step_length; current_inside_length += step_length; out_segments->start = segment_start; out_segments->end = walker; out_segments->length = segment_length; out_segments++; if (++segment_count >= max_segments) { break; } inside = 0; step = direction.scale(render_precision); } else { // searching for a cloud step = direction.scale((noise_distance > -render_precision) ? render_precision : -noise_distance); } } } while (inside || (walker.y >= ymin - 0.001 && walker.y <= ymax + 0.001 && current_total_length < max_total_length && current_inside_length < max_inside_length)); *total_length = current_total_length; *inside_length = current_inside_length; return segment_count; } Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location) { CloudLayerDefinition* layer = model->getLayer(); int i, segment_count; double max_length, detail, total_length, inside_length; Vector3 start, end, direction; Color result, col; CloudSegment segments[20]; start = eye; end = location; if (!optimizeSearchLimits(model, &start, &end)) { return COLOR_TRANSPARENT; } direction = end.sub(start); max_length = direction.getNorm(); direction = direction.normalize(); result = COLOR_TRANSPARENT; detail = parent->getPrecision(start) / layer->scaling; double transparency_depth = layer->scaling * 0.7; segment_count = _findSegments(model, parent, start, direction, detail, 20, transparency_depth, max_length, &inside_length, &total_length, segments); for (i = segment_count - 1; i >= 0; i--) { SurfaceMaterial material; material.base = colorToHSL(Color(3.0, 3.0, 3.0)); material.hardness = 0.25; material.reflection = 0.0; material.shininess = 0.0; materialValidate(&material); col = parent->applyLightingToSurface(segments[i].start, parent->getAtmosphereRenderer()->getSunDirection(), material); col.a = (segments[i].length >= transparency_depth) ? 1.0 : (segments[i].length / transparency_depth); result.mask(col); } if (inside_length >= transparency_depth) { result.a = 1.0; } double a = result.a; result = parent->getAtmosphereRenderer()->applyAerialPerspective(start, result).final; result.a = a; return result; } bool CloudBasicLayerRenderer::alterLight(BaseCloudsModel *model, LightComponent* light, const Vector3 &, const Vector3 &location) { Vector3 start, end, direction; double inside_depth, total_depth, factor; CloudSegment segments[20]; start = location; direction = light->direction.scale(-1.0); end = location.add(direction.scale(10000.0)); if (not optimizeSearchLimits(model, &start, &end)) { return false; } double light_traversal = model->getLayer()->scaling * 1.3; _findSegments(model, parent, start, direction, 0.1, 20, light_traversal, end.sub(start).getNorm(), &inside_depth, &total_depth, segments); if (light_traversal < 0.0001) { factor = 0.0; } else { factor = inside_depth / light_traversal; if (factor > 1.0) { factor = 1.0; } } double miminum_light = 0.3; factor = 1.0 - (1.0 - miminum_light) * factor; light->color.r *= factor; light->color.g *= factor; light->color.b *= factor; return true; } <commit_msg>Small cloud adjustments<commit_after>#include "CloudBasicLayerRenderer.h" #include "CloudLayerDefinition.h" #include "SoftwareRenderer.h" #include "NoiseGenerator.h" #include "Curve.h" #include "AtmosphereRenderer.h" #include "AtmosphereResult.h" #include "LightComponent.h" #include "clouds/BaseCloudsModel.h" #include "SurfaceMaterial.h" typedef struct { Vector3 start; Vector3 end; double length; } CloudSegment; CloudBasicLayerRenderer::CloudBasicLayerRenderer(SoftwareRenderer* parent): BaseCloudLayerRenderer(parent) { } static inline double _getDistanceToBorder(BaseCloudsModel* model, Vector3 position) { return model->getDensity(position); } /** * Go through the cloud layer to find segments (parts of the lookup that are inside the cloud). * * @param definition The cloud layer * @param renderer The renderer environment * @param start Start position of the lookup (already optimized) * @param direction Normalized direction of the lookup * @param detail Level of noise detail required * @param max_segments Maximum number of segments to collect * @param max_inside_length Maximum length to spend inside the cloud * @param max_total_length Maximum lookup length * @param inside_length Resulting length inside cloud (sum of all segments length) * @param total_length Resulting lookup length * @param out_segments Allocated space to fill found segments * @return Number of segments found */ static int _findSegments(BaseCloudsModel* model, SoftwareRenderer* renderer, Vector3 start, Vector3 direction, double, int max_segments, double max_inside_length, double max_total_length, double* inside_length, double* total_length, CloudSegment* out_segments) { CloudLayerDefinition* layer = model->getLayer(); double ymin, ymax; int inside, segment_count; double current_total_length, current_inside_length; double step_length, segment_length; double noise_distance, last_noise_distance; Vector3 walker, step, segment_start; double render_precision; if (max_segments <= 0) { return 0; } model->getAltitudeRange(&ymin, &ymax); render_precision = 15.2 - 1.5 * (double)renderer->render_quality; render_precision = render_precision * layer->scaling / 50.0; if (render_precision > max_total_length / 10.0) { render_precision = max_total_length / 10.0; } else if (render_precision < max_total_length / 2000.0) { render_precision = max_total_length / 2000.0; } segment_count = 0; current_total_length = 0.0; current_inside_length = 0.0; segment_length = 0.0; walker = start; noise_distance = _getDistanceToBorder(model, start) * render_precision; inside = 0; step = direction.scale(render_precision); do { walker = walker.add(step); step_length = step.getNorm(); last_noise_distance = noise_distance; noise_distance = _getDistanceToBorder(model, walker) * render_precision; current_total_length += step_length; if (noise_distance > 0.0) { if (inside) { // inside the cloud segment_length += step_length; current_inside_length += step_length; step = direction.scale((noise_distance < render_precision) ? render_precision : noise_distance); } else { // entering the cloud inside = 1; segment_length = 0.0; segment_start = walker; current_inside_length += segment_length; step = direction.scale(render_precision); } } else { if (inside) { // exiting the cloud segment_length += step_length; current_inside_length += step_length; out_segments->start = segment_start; out_segments->end = walker; out_segments->length = segment_length; out_segments++; if (++segment_count >= max_segments) { break; } inside = 0; step = direction.scale(render_precision); } else { // searching for a cloud step = direction.scale((noise_distance > -render_precision) ? render_precision : -noise_distance); } } } while (inside || (walker.y >= ymin - 0.001 && walker.y <= ymax + 0.001 && current_total_length < max_total_length && current_inside_length < max_inside_length)); *total_length = current_total_length; *inside_length = current_inside_length; return segment_count; } Color CloudBasicLayerRenderer::getColor(BaseCloudsModel *model, const Vector3 &eye, const Vector3 &location) { CloudLayerDefinition* layer = model->getLayer(); int i, segment_count; double max_length, detail, total_length, inside_length; Vector3 start, end, direction; Color result, col; CloudSegment segments[20]; start = eye; end = location; if (!optimizeSearchLimits(model, &start, &end)) { return COLOR_TRANSPARENT; } direction = end.sub(start); max_length = direction.getNorm(); direction = direction.normalize(); result = COLOR_TRANSPARENT; detail = parent->getPrecision(start) / layer->scaling; double transparency_depth = layer->scaling * 1.5; segment_count = _findSegments(model, parent, start, direction, detail, 20, transparency_depth, max_length, &inside_length, &total_length, segments); for (i = segment_count - 1; i >= 0; i--) { SurfaceMaterial material; material.base = colorToHSL(Color(3.0, 3.0, 3.0)); material.hardness = 0.25; material.reflection = 0.0; material.shininess = 0.0; materialValidate(&material); col = parent->applyLightingToSurface(segments[i].start, parent->getAtmosphereRenderer()->getSunDirection(), material); col.a = (segments[i].length >= transparency_depth) ? 1.0 : (segments[i].length / transparency_depth); result.mask(col); } if (inside_length >= transparency_depth) { result.a = 1.0; } double a = result.a; result = parent->getAtmosphereRenderer()->applyAerialPerspective(start, result).final; result.a = a; return result; } bool CloudBasicLayerRenderer::alterLight(BaseCloudsModel *model, LightComponent* light, const Vector3 &, const Vector3 &location) { Vector3 start, end, direction; double inside_depth, total_depth, factor; CloudSegment segments[20]; start = location; direction = light->direction.scale(-1.0); end = location.add(direction.scale(10000.0)); if (not optimizeSearchLimits(model, &start, &end)) { return false; } double light_traversal = model->getLayer()->scaling * 5.0; _findSegments(model, parent, start, direction, 0.1, 20, light_traversal, end.sub(start).getNorm(), &inside_depth, &total_depth, segments); if (light_traversal < 0.0001) { factor = 0.0; } else { factor = inside_depth / light_traversal; if (factor > 1.0) { factor = 1.0; } } double miminum_light = 0.3; factor = 1.0 - (1.0 - miminum_light) * factor; light->color.r *= factor; light->color.g *= factor; light->color.b *= factor; return true; } <|endoftext|>
<commit_before>#ifndef RBX_UTIL_THREAD_HPP #define RBX_UTIL_THREAD_HPP // #define DEBUG_LOCKGUARD #define USE_PTHREADS #ifdef USE_PTHREADS #include <pthread.h> #include <errno.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <sstream> #include <iostream> #include "util/atomic.hpp" #include "logger.hpp" intptr_t thread_debug_self(); #define pthread_check(expr) if((expr) != 0) { fail(#expr); } #if defined(__APPLE__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060) // This is behind a silly define, so we just pull it out here. extern "C" int pthread_setname_np(const char*); #define HAVE_PTHREAD_SETNAME #endif namespace rubinius { namespace utilities { namespace thread { static inline void fail(const char* str) { std::cerr << "utilities::thread: " << str << std::endl; abort(); } enum Code { cLocked, cUnlocked, cLockBusy, cNotYours, cReady, cTimedOut }; template <typename T = void*> class ThreadData { pthread_key_t native_; public: ThreadData() { pthread_check(pthread_key_create(&native_, NULL)); } ~ThreadData() { pthread_check(pthread_key_delete(native_)); } T get() const { return reinterpret_cast<T>(pthread_getspecific(native_)); } void set(T val) { pthread_check(pthread_setspecific(native_, reinterpret_cast<void*>(val))); } }; class Thread { pthread_t native_; bool delete_on_exit_; size_t stack_size_; const char* name_; static void* trampoline(void* arg) { Thread* self = reinterpret_cast<Thread*>(arg); self->perform(); if(self->delete_on_exit()) delete self; return NULL; } public: Thread(size_t stack_size = 0, bool delete_on_exit = true) : delete_on_exit_(delete_on_exit) , stack_size_(stack_size) , name_(NULL) {} virtual ~Thread() { } // Set the name of the thread. Be sure to call this inside perform // so that the system can see the proper thread to set if that is // available (OS X only atm) static void set_os_name(const char* name) { #ifdef HAVE_PTHREAD_SETNAME pthread_setname_np(name); #endif } void set_name(const char* name) { name_ = name; set_os_name(name); } static pthread_t self() { return pthread_self(); } static bool equal_p(pthread_t t1, pthread_t t2) { return pthread_equal(t1, t2); } static void signal(pthread_t thr, int signal) { pthread_kill(thr, signal); } const pthread_t* native() const { return &native_; } size_t stack_size() const { return stack_size_; } int run() { pthread_attr_t attrs; pthread_attr_init(&attrs); if(stack_size_) { pthread_attr_setstacksize(&attrs, stack_size_); } pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE); int status = pthread_create(&native_, &attrs, trampoline, (void*)this); pthread_attr_destroy(&attrs); return status; } virtual void perform() { } void detach() { pthread_check(pthread_detach(native_)); } bool equal(Thread& other) const { if(pthread_equal(native_, *other.native())) { return true; } return false; } void join() { void* bunk; int err = pthread_join(native_, &bunk); if(err != 0) { if(err == EDEADLK) fail("Thread::join: deadlock"); // Ignore the other errors, since they mean there is no thread // so we can consider us already joined to it. } } bool in_self_p() const { return pthread_equal(pthread_self(), native_); } void cancel() { pthread_check(pthread_cancel(native_)); } void kill(int sig) { pthread_check(pthread_kill(native_, sig)); } int priority() { int _policy; struct sched_param params; pthread_check(pthread_getschedparam(native_, &_policy, &params)); return params.sched_priority; } bool set_priority(int priority) { int _policy; struct sched_param params; pthread_check(pthread_getschedparam(native_, &_policy, &params)); #ifdef __OpenBSD__ // The shed_get_priority_max function is not exposed. int max = 31; int min = 0; #else int max = sched_get_priority_max(_policy); int min = sched_get_priority_min(_policy); #endif if(min > priority) { priority = min; } else if(max < priority) { priority = max; } params.sched_priority = priority; int err = pthread_setschedparam(native_, _policy, &params); if(err == ENOTSUP) return false; return true; } bool delete_on_exit() const { return delete_on_exit_; } void set_delete_on_exit() { delete_on_exit_ = true; } }; /* * A stacklet object for locking and unlocking. */ #ifdef DEBUG_LOCKGUARD const bool cDebugLockGuard = true; #else const bool cDebugLockGuard = false; #endif template <class T> class LockGuardTemplate { public: T& lock_; LockGuardTemplate(T& in_lock, bool initial = false) : lock_(in_lock) { if(initial) lock_.lock(); } LockGuardTemplate(T* in_lock, bool initial = false) : lock_(*in_lock) { if(initial) lock_.lock(); } void lock() { if(cDebugLockGuard) { logger::debug("%d: Locking %s", thread_debug_self(), lock_.describe()); } lock_.lock(); if(cDebugLockGuard) { logger::debug("%d: Locked %s", thread_debug_self(), lock_.describe()); } } void unlock() { if(cDebugLockGuard) { logger::debug("%d: Unlocking %s", thread_debug_self(), lock_.describe()); } lock_.unlock(); } }; template <class T> class StackLockGuard : public LockGuardTemplate<T> { public: StackLockGuard(T& in_lock) : LockGuardTemplate<T>(in_lock, false) { this->lock(); } ~StackLockGuard() { this->unlock(); } }; template <class T> class StackUnlockGuard : public LockGuardTemplate<T> { public: StackUnlockGuard(T& lock_obj) : LockGuardTemplate<T>(lock_obj, true) { this->unlock(); } ~StackUnlockGuard() { this->lock(); } }; class Mutex { public: // Types typedef StackLockGuard<Mutex> LockGuard; typedef StackUnlockGuard<Mutex> UnlockGuard; private: pthread_mutex_t native_; pthread_t owner_; public: void init(bool rec=false) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); if(rec) { pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); } else { pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); } pthread_check(pthread_mutex_init(&native_, &attr)); } Mutex(bool rec=false) { init(rec); } ~Mutex() { int err = pthread_mutex_destroy(&native_); if(err != 0) { switch(err) { case EBUSY: fail("~Mutex: mutex is busy"); break; case EINVAL: fail("~Mutex: mutex is dead"); break; default: fail("~Mutex: unknown error"); } } } pthread_t owner() const { return owner_; } pthread_mutex_t* native() { return &native_; } void lock() { if(cDebugLockGuard) { logger::debug("%d MLocking %s", thread_debug_self(), describe()); } int err = pthread_mutex_lock(&native_); switch(err) { case 0: break; case EDEADLK: fail("Mutex::lock: deadlock"); break; case EINVAL: fail("Mutex::lock: invalid"); break; } owner_ = pthread_self(); if(cDebugLockGuard) { logger::debug("%d MLocked %s", thread_debug_self(), describe()); } } Code try_lock() { int err = pthread_mutex_trylock(&native_); if(err != 0) { if(err == EBUSY) return cLockBusy; fail("Mutex::try_lock: unknown error"); } owner_ = pthread_self(); return cLocked; } Code unlock() { if(cDebugLockGuard) { logger::debug("%d MUnlocking %s", thread_debug_self(), describe()); } int err = pthread_mutex_unlock(&native_); if(err != 0) { if(err == EPERM) return cNotYours; fail("Mutex::unlock: unknown error"); } return cUnlocked; } const char* describe() const { std::ostringstream ss; ss << "Mutex "; ss << (void*)this; return ss.str().c_str(); } }; class Condition { pthread_cond_t native_; public: void init() { pthread_check(pthread_cond_init(&native_, NULL)); } Condition() { init(); } ~Condition() { int err = pthread_cond_destroy(&native_); if(err != 0) { switch(err) { case EBUSY: fail("~Condition: locked by another thread"); break; case EINVAL: fail("~Condition: invalid value"); break; default: fail("~Condition: unknown error"); } } } void signal() { pthread_check(pthread_cond_signal(&native_)); } void broadcast() { pthread_check(pthread_cond_broadcast(&native_)); } void wait(Mutex& mutex) { if(cDebugLockGuard) { logger::debug("%d CUnlocking %s", thread_debug_self(), mutex.describe()); } pthread_check(pthread_cond_wait(&native_, mutex.native())); if(cDebugLockGuard) { logger::debug("%d CLocked %s", thread_debug_self(), mutex.describe()); } } #define NS_PER_SEC 1000000000 #define NS_PER_USEC 1000 void offset(struct timespec* ts, double sec) { struct timeval tv = {0,0}; gettimeofday(&tv, 0); uint64_t ns = (uint64_t)(sec * NS_PER_SEC + tv.tv_usec * NS_PER_USEC); ts->tv_sec = (time_t)(tv.tv_sec + ns / NS_PER_SEC); ts->tv_nsec = (long)(ns % NS_PER_SEC); } Code wait_until(Mutex& mutex, const struct timespec* ts) { if(cDebugLockGuard) { logger::debug("%d CUnlocking %s", thread_debug_self(), mutex.describe()); } int err = pthread_cond_timedwait(&native_, mutex.native(), ts); if(cDebugLockGuard) { logger::debug("%d CLocked %s", thread_debug_self(), mutex.describe()); } if(err != 0) { if(err == ETIMEDOUT) { return cTimedOut; } switch(err) { case EINVAL: // This is not really correct, but it works for us: // We treat this error as ONLY ts being invalid, ie, it's for // a time in the past. Thus we can just say everything is ready. // // EINVAL can mean that both native_ and mutex.native() are invalid // too, but we've got no recourse if that is true. return cReady; default: fail("Condition::wait_until: unknown failure from pthread_cond_timedwait"); } } return cReady; } }; } } } #ifdef HAVE_OSX_SPINLOCK #include <libkern/OSAtomic.h> namespace rubinius { namespace utilities { namespace thread { class SpinLock { public: // Types typedef StackLockGuard<SpinLock> LockGuard; typedef StackUnlockGuard<SpinLock> UnlockGuard; private: OSSpinLock native_; public: SpinLock() : native_(0) {} void init() { native_ = 0; } void lock() { OSSpinLockLock(&native_); } void unlock() { OSSpinLockUnlock(&native_); } Code try_lock() { if(OSSpinLockTry(&native_)) { return cLockBusy; } return cLocked; } const char* describe() const { std::ostringstream ss; ss << "SpinLock "; ss << (void*)this; return ss.str().c_str(); } }; }; } } #else namespace rubinius { namespace utilities { namespace thread { class SpinLock { public: // Types typedef StackLockGuard<SpinLock> LockGuard; typedef StackUnlockGuard<SpinLock> UnlockGuard; private: int lock_; public: SpinLock() : lock_(0) {} void init() { lock_ = 0; } void lock() { while(!atomic::compare_and_swap(&lock_, 0, 1)) { atomic::pause(); } } void unlock() { atomic::compare_and_swap(&lock_, 1, 0); } Code try_lock() { if(atomic::compare_and_swap(&lock_, 0, 1)) { return cLocked; } return cLockBusy; } const char* describe() const { std::ostringstream ss; ss << "SpinLock "; ss << (void*)this; return ss.str().c_str(); } }; } } } #endif #else #error "No thread implementation defined" #endif #endif <commit_msg>Remove abort from legacy util/thread.<commit_after>#ifndef RBX_UTIL_THREAD_HPP #define RBX_UTIL_THREAD_HPP // #define DEBUG_LOCKGUARD #define USE_PTHREADS #ifdef USE_PTHREADS #include <pthread.h> #include <errno.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <sstream> #include <iostream> #include "util/atomic.hpp" #include "logger.hpp" intptr_t thread_debug_self(); #define pthread_check(expr) if((expr) != 0) { fail(#expr); } #if defined(__APPLE__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060) // This is behind a silly define, so we just pull it out here. extern "C" int pthread_setname_np(const char*); #define HAVE_PTHREAD_SETNAME #endif namespace rubinius { namespace utilities { namespace thread { static inline void fail(const char* str) { std::cerr << "utilities::thread: " << strerror(errno) << ", " << str << std::endl; } enum Code { cLocked, cUnlocked, cLockBusy, cNotYours, cReady, cTimedOut }; template <typename T = void*> class ThreadData { pthread_key_t native_; public: ThreadData() { pthread_check(pthread_key_create(&native_, NULL)); } ~ThreadData() { pthread_check(pthread_key_delete(native_)); } T get() const { return reinterpret_cast<T>(pthread_getspecific(native_)); } void set(T val) { pthread_check(pthread_setspecific(native_, reinterpret_cast<void*>(val))); } }; class Thread { pthread_t native_; bool delete_on_exit_; size_t stack_size_; const char* name_; static void* trampoline(void* arg) { Thread* self = reinterpret_cast<Thread*>(arg); self->perform(); if(self->delete_on_exit()) delete self; return NULL; } public: Thread(size_t stack_size = 0, bool delete_on_exit = true) : delete_on_exit_(delete_on_exit) , stack_size_(stack_size) , name_(NULL) {} virtual ~Thread() { } // Set the name of the thread. Be sure to call this inside perform // so that the system can see the proper thread to set if that is // available (OS X only atm) static void set_os_name(const char* name) { #ifdef HAVE_PTHREAD_SETNAME pthread_setname_np(name); #endif } void set_name(const char* name) { name_ = name; set_os_name(name); } static pthread_t self() { return pthread_self(); } static bool equal_p(pthread_t t1, pthread_t t2) { return pthread_equal(t1, t2); } static void signal(pthread_t thr, int signal) { pthread_kill(thr, signal); } const pthread_t* native() const { return &native_; } size_t stack_size() const { return stack_size_; } int run() { pthread_attr_t attrs; pthread_attr_init(&attrs); if(stack_size_) { pthread_attr_setstacksize(&attrs, stack_size_); } pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE); int status = pthread_create(&native_, &attrs, trampoline, (void*)this); pthread_attr_destroy(&attrs); return status; } virtual void perform() { } void detach() { pthread_check(pthread_detach(native_)); } bool equal(Thread& other) const { if(pthread_equal(native_, *other.native())) { return true; } return false; } void join() { void* bunk; int err = pthread_join(native_, &bunk); if(err != 0) { if(err == EDEADLK) fail("Thread::join: deadlock"); // Ignore the other errors, since they mean there is no thread // so we can consider us already joined to it. } } bool in_self_p() const { return pthread_equal(pthread_self(), native_); } void cancel() { pthread_check(pthread_cancel(native_)); } void kill(int sig) { pthread_check(pthread_kill(native_, sig)); } int priority() { int _policy; struct sched_param params; pthread_check(pthread_getschedparam(native_, &_policy, &params)); return params.sched_priority; } bool set_priority(int priority) { int _policy; struct sched_param params; pthread_check(pthread_getschedparam(native_, &_policy, &params)); #ifdef __OpenBSD__ // The shed_get_priority_max function is not exposed. int max = 31; int min = 0; #else int max = sched_get_priority_max(_policy); int min = sched_get_priority_min(_policy); #endif if(min > priority) { priority = min; } else if(max < priority) { priority = max; } params.sched_priority = priority; int err = pthread_setschedparam(native_, _policy, &params); if(err == ENOTSUP) return false; return true; } bool delete_on_exit() const { return delete_on_exit_; } void set_delete_on_exit() { delete_on_exit_ = true; } }; /* * A stacklet object for locking and unlocking. */ #ifdef DEBUG_LOCKGUARD const bool cDebugLockGuard = true; #else const bool cDebugLockGuard = false; #endif template <class T> class LockGuardTemplate { public: T& lock_; LockGuardTemplate(T& in_lock, bool initial = false) : lock_(in_lock) { if(initial) lock_.lock(); } LockGuardTemplate(T* in_lock, bool initial = false) : lock_(*in_lock) { if(initial) lock_.lock(); } void lock() { if(cDebugLockGuard) { logger::debug("%d: Locking %s", thread_debug_self(), lock_.describe()); } lock_.lock(); if(cDebugLockGuard) { logger::debug("%d: Locked %s", thread_debug_self(), lock_.describe()); } } void unlock() { if(cDebugLockGuard) { logger::debug("%d: Unlocking %s", thread_debug_self(), lock_.describe()); } lock_.unlock(); } }; template <class T> class StackLockGuard : public LockGuardTemplate<T> { public: StackLockGuard(T& in_lock) : LockGuardTemplate<T>(in_lock, false) { this->lock(); } ~StackLockGuard() { this->unlock(); } }; template <class T> class StackUnlockGuard : public LockGuardTemplate<T> { public: StackUnlockGuard(T& lock_obj) : LockGuardTemplate<T>(lock_obj, true) { this->unlock(); } ~StackUnlockGuard() { this->lock(); } }; class Mutex { public: // Types typedef StackLockGuard<Mutex> LockGuard; typedef StackUnlockGuard<Mutex> UnlockGuard; private: pthread_mutex_t native_; pthread_t owner_; public: void init(bool rec=false) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); if(rec) { pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); } else { pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); } pthread_check(pthread_mutex_init(&native_, &attr)); } Mutex(bool rec=false) { init(rec); } ~Mutex() { int err = pthread_mutex_destroy(&native_); if(err != 0) { switch(err) { case EBUSY: fail("~Mutex: mutex is busy"); break; case EINVAL: fail("~Mutex: mutex is dead"); break; default: fail("~Mutex: unknown error"); } } } pthread_t owner() const { return owner_; } pthread_mutex_t* native() { return &native_; } void lock() { if(cDebugLockGuard) { logger::debug("%d MLocking %s", thread_debug_self(), describe()); } int err = pthread_mutex_lock(&native_); switch(err) { case 0: break; case EDEADLK: fail("Mutex::lock: deadlock"); break; case EINVAL: fail("Mutex::lock: invalid"); break; } owner_ = pthread_self(); if(cDebugLockGuard) { logger::debug("%d MLocked %s", thread_debug_self(), describe()); } } Code try_lock() { int err = pthread_mutex_trylock(&native_); if(err != 0) { if(err == EBUSY) return cLockBusy; fail("Mutex::try_lock: unknown error"); } owner_ = pthread_self(); return cLocked; } Code unlock() { if(cDebugLockGuard) { logger::debug("%d MUnlocking %s", thread_debug_self(), describe()); } int err = pthread_mutex_unlock(&native_); if(err != 0) { if(err == EPERM) return cNotYours; fail("Mutex::unlock: unknown error"); } return cUnlocked; } const char* describe() const { std::ostringstream ss; ss << "Mutex "; ss << (void*)this; return ss.str().c_str(); } }; class Condition { pthread_cond_t native_; public: void init() { pthread_check(pthread_cond_init(&native_, NULL)); } Condition() { init(); } ~Condition() { int err = pthread_cond_destroy(&native_); if(err != 0) { switch(err) { case EBUSY: fail("~Condition: locked by another thread"); break; case EINVAL: fail("~Condition: invalid value"); break; default: fail("~Condition: unknown error"); } } } void signal() { pthread_check(pthread_cond_signal(&native_)); } void broadcast() { pthread_check(pthread_cond_broadcast(&native_)); } void wait(Mutex& mutex) { if(cDebugLockGuard) { logger::debug("%d CUnlocking %s", thread_debug_self(), mutex.describe()); } pthread_check(pthread_cond_wait(&native_, mutex.native())); if(cDebugLockGuard) { logger::debug("%d CLocked %s", thread_debug_self(), mutex.describe()); } } #define NS_PER_SEC 1000000000 #define NS_PER_USEC 1000 void offset(struct timespec* ts, double sec) { struct timeval tv = {0,0}; gettimeofday(&tv, 0); uint64_t ns = (uint64_t)(sec * NS_PER_SEC + tv.tv_usec * NS_PER_USEC); ts->tv_sec = (time_t)(tv.tv_sec + ns / NS_PER_SEC); ts->tv_nsec = (long)(ns % NS_PER_SEC); } Code wait_until(Mutex& mutex, const struct timespec* ts) { if(cDebugLockGuard) { logger::debug("%d CUnlocking %s", thread_debug_self(), mutex.describe()); } int err = pthread_cond_timedwait(&native_, mutex.native(), ts); if(cDebugLockGuard) { logger::debug("%d CLocked %s", thread_debug_self(), mutex.describe()); } if(err != 0) { if(err == ETIMEDOUT) { return cTimedOut; } switch(err) { case EINVAL: // This is not really correct, but it works for us: // We treat this error as ONLY ts being invalid, ie, it's for // a time in the past. Thus we can just say everything is ready. // // EINVAL can mean that both native_ and mutex.native() are invalid // too, but we've got no recourse if that is true. return cReady; default: fail("Condition::wait_until: unknown failure from pthread_cond_timedwait"); } } return cReady; } }; } } } #ifdef HAVE_OSX_SPINLOCK #include <libkern/OSAtomic.h> namespace rubinius { namespace utilities { namespace thread { class SpinLock { public: // Types typedef StackLockGuard<SpinLock> LockGuard; typedef StackUnlockGuard<SpinLock> UnlockGuard; private: OSSpinLock native_; public: SpinLock() : native_(0) {} void init() { native_ = 0; } void lock() { OSSpinLockLock(&native_); } void unlock() { OSSpinLockUnlock(&native_); } Code try_lock() { if(OSSpinLockTry(&native_)) { return cLockBusy; } return cLocked; } const char* describe() const { std::ostringstream ss; ss << "SpinLock "; ss << (void*)this; return ss.str().c_str(); } }; }; } } #else namespace rubinius { namespace utilities { namespace thread { class SpinLock { public: // Types typedef StackLockGuard<SpinLock> LockGuard; typedef StackUnlockGuard<SpinLock> UnlockGuard; private: int lock_; public: SpinLock() : lock_(0) {} void init() { lock_ = 0; } void lock() { while(!atomic::compare_and_swap(&lock_, 0, 1)) { atomic::pause(); } } void unlock() { atomic::compare_and_swap(&lock_, 1, 0); } Code try_lock() { if(atomic::compare_and_swap(&lock_, 0, 1)) { return cLocked; } return cLockBusy; } const char* describe() const { std::ostringstream ss; ss << "SpinLock "; ss << (void*)this; return ss.str().c_str(); } }; } } } #endif #else #error "No thread implementation defined" #endif #endif <|endoftext|>
<commit_before>#include "HumbugWindow.h" #include "HumbugAboutDialog.h" #include "HumbugTrayIcon.h" #include "ui_HumbugWindow.h" #include <iostream> #include <QDir> #include <QMenuBar> #include <QSystemTrayIcon> #include <QWebFrame> #include <QWebSettings> #include <QNetworkAccessManager> #include <QDesktopServices> #include <phonon/MediaObject> #include <phonon/MediaSource> #include <phonon/AudioOutput> #include <stdio.h> HumbugWindow::HumbugWindow(QWidget *parent) : QMainWindow(parent), m_ui(new Ui::HumbugWindow) { m_ui->setupUi(this); m_start = QUrl("https://humbughq.com/"); QDir data_dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); // Create the directory if it doesn't already exist data_dir.mkdir(data_dir.absolutePath()); CookieJar *m_cookies = new CookieJar(data_dir.absoluteFilePath("default.dat")); m_ui->webView->load(m_start); m_ui->webView->page()->networkAccessManager()->setCookieJar(m_cookies); statusBar()->hide(); m_tray = new HumbugTrayIcon(this); m_tray->setIcon(QIcon(":/images/hat.svg")); QMenu *menu = new QMenu(this); QAction *about_action = menu->addAction("About"); connect(about_action, SIGNAL(triggered()), this, SLOT(showAbout())); QAction *exit_action = menu->addAction("Exit"); connect(exit_action, SIGNAL(triggered()), this, SLOT(userQuit())); connect(m_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked())); m_tray->setContextMenu(menu); m_tray->show(); m_bellsound = new Phonon::MediaObject(this); Phonon::createPath(m_bellsound, new Phonon::AudioOutput(Phonon::MusicCategory, this)); m_bellsound->setCurrentSource(Phonon::MediaSource(QString("/home/lfaraone/orgs/humbug/desktop/src/humbug.ogg"))); m_bridge = new HumbugWebBridge(this); connect(m_ui->webView->page(), SIGNAL(linkClicked(QUrl)), this, SLOT(linkClicked(QUrl))); connect(m_ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject())); connect(m_bridge, SIGNAL(notificationRequested(QString,QString)), this, SLOT(displayPopup(QString,QString))); connect(m_bridge, SIGNAL(countUpdated(int,int)), this, SLOT(updateIcon(int,int))); connect(m_bridge, SIGNAL(bellTriggered()), m_bellsound, SLOT(play())); m_ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks); } void HumbugWindow::setUrl(const QUrl &url) { m_start = url; m_ui->webView->load(m_start); } void HumbugWindow::showAbout() { HumbugAboutDialog *d = new HumbugAboutDialog(this); d->show(); } void HumbugWindow::userQuit() { QApplication::quit(); } void HumbugWindow::trayClicked() { raise(); activateWindow(); } void HumbugWindow::linkClicked(const QUrl& url) { if (url.host() == m_start.host()) { m_ui->webView->load(url); } else { QDesktopServices::openUrl(url); } return; } void HumbugWindow::addJavaScriptObject() { // Ref: http://www.developer.nokia.com/Community/Wiki/Exposing_QObjects_to_Qt_Webkit // Don't expose the JS bridge outside our start domain if (m_ui->webView->url().host() != m_start.host()) { return; } m_ui->webView->page() ->mainFrame() ->addToJavaScriptWindowObject("bridge", m_bridge); } void HumbugWindow::updateIcon(int current, int previous) { if (current == previous) { return; } else if (current <= 0) { m_tray->setIcon(QIcon(":/images/hat.svg")); } else if (current >= 99) { m_tray->setIcon(QIcon(":/images/favicon/favicon-infinite.png")); } else { m_tray->setIcon(QIcon(QString(":/images/favicon/favicon-%1.png").arg(current))); } } void HumbugWindow::displayPopup(const QString &title, const QString &content) { m_tray->showMessage(title, content); } HumbugWindow::~HumbugWindow() { delete m_ui; } <commit_msg>Set the cookie jar before loading pages.<commit_after>#include "HumbugWindow.h" #include "HumbugAboutDialog.h" #include "HumbugTrayIcon.h" #include "ui_HumbugWindow.h" #include <iostream> #include <QDir> #include <QMenuBar> #include <QSystemTrayIcon> #include <QWebFrame> #include <QWebSettings> #include <QNetworkAccessManager> #include <QDesktopServices> #include <phonon/MediaObject> #include <phonon/MediaSource> #include <phonon/AudioOutput> #include <stdio.h> HumbugWindow::HumbugWindow(QWidget *parent) : QMainWindow(parent), m_ui(new Ui::HumbugWindow) { m_ui->setupUi(this); m_start = QUrl("https://humbughq.com/"); QDir data_dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); // Create the directory if it doesn't already exist data_dir.mkdir(data_dir.absolutePath()); CookieJar *m_cookies = new CookieJar(data_dir.absoluteFilePath("default.dat")); m_ui->webView->page()->networkAccessManager()->setCookieJar(m_cookies); m_ui->webView->load(m_start); statusBar()->hide(); m_tray = new HumbugTrayIcon(this); m_tray->setIcon(QIcon(":/images/hat.svg")); QMenu *menu = new QMenu(this); QAction *about_action = menu->addAction("About"); connect(about_action, SIGNAL(triggered()), this, SLOT(showAbout())); QAction *exit_action = menu->addAction("Exit"); connect(exit_action, SIGNAL(triggered()), this, SLOT(userQuit())); connect(m_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked())); m_tray->setContextMenu(menu); m_tray->show(); m_bellsound = new Phonon::MediaObject(this); Phonon::createPath(m_bellsound, new Phonon::AudioOutput(Phonon::MusicCategory, this)); m_bellsound->setCurrentSource(Phonon::MediaSource(QString("/home/lfaraone/orgs/humbug/desktop/src/humbug.ogg"))); m_bridge = new HumbugWebBridge(this); connect(m_ui->webView->page(), SIGNAL(linkClicked(QUrl)), this, SLOT(linkClicked(QUrl))); connect(m_ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject())); connect(m_bridge, SIGNAL(notificationRequested(QString,QString)), this, SLOT(displayPopup(QString,QString))); connect(m_bridge, SIGNAL(countUpdated(int,int)), this, SLOT(updateIcon(int,int))); connect(m_bridge, SIGNAL(bellTriggered()), m_bellsound, SLOT(play())); m_ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks); } void HumbugWindow::setUrl(const QUrl &url) { m_start = url; m_ui->webView->load(m_start); } void HumbugWindow::showAbout() { HumbugAboutDialog *d = new HumbugAboutDialog(this); d->show(); } void HumbugWindow::userQuit() { QApplication::quit(); } void HumbugWindow::trayClicked() { raise(); activateWindow(); } void HumbugWindow::linkClicked(const QUrl& url) { if (url.host() == m_start.host()) { m_ui->webView->load(url); } else { QDesktopServices::openUrl(url); } return; } void HumbugWindow::addJavaScriptObject() { // Ref: http://www.developer.nokia.com/Community/Wiki/Exposing_QObjects_to_Qt_Webkit // Don't expose the JS bridge outside our start domain if (m_ui->webView->url().host() != m_start.host()) { return; } m_ui->webView->page() ->mainFrame() ->addToJavaScriptWindowObject("bridge", m_bridge); } void HumbugWindow::updateIcon(int current, int previous) { if (current == previous) { return; } else if (current <= 0) { m_tray->setIcon(QIcon(":/images/hat.svg")); } else if (current >= 99) { m_tray->setIcon(QIcon(":/images/favicon/favicon-infinite.png")); } else { m_tray->setIcon(QIcon(QString(":/images/favicon/favicon-%1.png").arg(current))); } } void HumbugWindow::displayPopup(const QString &title, const QString &content) { m_tray->showMessage(title, content); } HumbugWindow::~HumbugWindow() { delete m_ui; } <|endoftext|>
<commit_before>/*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ // Qt includes #include <QDebug> #include <QtPlugin> // Slicer includes #include <qSlicerCoreApplication.h> #include <qSlicerModuleManager.h> // Logic includes #include <vtkSlicerAstroVolumeLogic.h> #include <vtkSlicerAstroModelingLogic.h> #include <vtkSlicerMarkupsLogic.h> // AstroModeling includes #include "qSlicerAstroModelingModule.h" #include "qSlicerAstroModelingModuleWidget.h" //----------------------------------------------------------------------------- #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #include <QtPlugin> Q_EXPORT_PLUGIN2(qSlicerAstroModelingModule, qSlicerAstroModelingModule); #endif //----------------------------------------------------------------------------- /// \ingroup SlicerAstro_QtModules_AstroModeling class qSlicerAstroModelingModulePrivate { public: qSlicerAstroModelingModulePrivate(); }; //----------------------------------------------------------------------------- // qSlicerAstroModelingModulePrivate methods //----------------------------------------------------------------------------- qSlicerAstroModelingModulePrivate::qSlicerAstroModelingModulePrivate() { } //----------------------------------------------------------------------------- // qSlicerAstroModelingModule methods //----------------------------------------------------------------------------- qSlicerAstroModelingModule::qSlicerAstroModelingModule(QObject* _parent) : Superclass(_parent) , d_ptr(new qSlicerAstroModelingModulePrivate) { } //----------------------------------------------------------------------------- qSlicerAstroModelingModule::~qSlicerAstroModelingModule() { } //----------------------------------------------------------------------------- QString qSlicerAstroModelingModule::helpText()const { return "AstroModeling module fits tilted-ring models on a HI datacube using 3DBarolo " "(http://editeodoro.github.io/Bbarolo/). " "Specifically, SlicerAstro wraps a branch of 3DBarolo " "(https://github.com/Punzo/Bbarolo) which corresponds to " "3DBarolo v1.3 (git tag: 3c9a1fa39e9154f3120d0ded0847d77314275e17)"; } //----------------------------------------------------------------------------- QString qSlicerAstroModelingModule::acknowledgementText()const { return "This module was developed by Davide Punzo. <br>" "This work was supported by ERC grant nr. 291531, " "and Slicer community. <br>" " Special thanks to Enrico di Teodoro (Australian National University)" " for support regarding 3DBarolo wrapping in SlicerAstro. <br>"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::contributors()const { QStringList moduleContributors; moduleContributors << QString("Davide Punzo (Kapteyn Astronomical Institute)"); moduleContributors << QString("Thijs van der Hulst (Kapteyn Astronomical Institute)"); moduleContributors << QString("Jos Roerdink (Johann Bernoulli Institute)"); return moduleContributors; } //----------------------------------------------------------------------------- QIcon qSlicerAstroModelingModule::icon()const { return QIcon(":/Icons/AstroModeling.png"); } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::categories()const { return QStringList() << "Astronomy" << "Quantification"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::associatedNodeTypes() const { return QStringList() << "vtkMRMLAstroModelingParametersNode"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::dependencies()const { return QStringList() << "AstroVolume" << "Markups" << "Segmentations" ; } //----------------------------------------------------------------------------- void qSlicerAstroModelingModule::setup() { this->Superclass::setup(); // Register logic vtkSlicerAstroModelingLogic* AstroModelingLogic = vtkSlicerAstroModelingLogic::SafeDownCast(this->logic()); // Register AstroVolume module logic qSlicerAbstractCoreModule* astroVolumeModule = qSlicerCoreApplication::application()->moduleManager()->module("AstroVolume"); if (!astroVolumeModule) { qCritical() << "AstroVolume module is not found"; return; } vtkSlicerAstroVolumeLogic* astroVolumeLogic = vtkSlicerAstroVolumeLogic::SafeDownCast(astroVolumeModule->logic()); if (!astroVolumeLogic) { qCritical() << "AstroVolume logic is not found"; return; } AstroModelingLogic->SetAstroVolumeLogic(astroVolumeLogic); // Register Markups module logic qSlicerAbstractCoreModule* markupsModule = qSlicerCoreApplication::application()->moduleManager()->module("Markups"); if (!markupsModule) { qCritical() << "Markups module is not found"; return; } vtkSlicerMarkupsLogic* markupsLogic = vtkSlicerMarkupsLogic::SafeDownCast(markupsModule->logic()); if (!markupsLogic) { qCritical() << "Markups logic is not found"; return; } AstroModelingLogic->SetMarkupsLogic(markupsLogic); } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation * qSlicerAstroModelingModule::createWidgetRepresentation() { return new qSlicerAstroModelingModuleWidget; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerAstroModelingModule::createLogic() { return vtkSlicerAstroModelingLogic::New(); } <commit_msg>STYLE: update helptext of Modeling module<commit_after>/*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ // Qt includes #include <QDebug> #include <QtPlugin> // Slicer includes #include <qSlicerCoreApplication.h> #include <qSlicerModuleManager.h> // Logic includes #include <vtkSlicerAstroVolumeLogic.h> #include <vtkSlicerAstroModelingLogic.h> #include <vtkSlicerMarkupsLogic.h> // AstroModeling includes #include "qSlicerAstroModelingModule.h" #include "qSlicerAstroModelingModuleWidget.h" //----------------------------------------------------------------------------- #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #include <QtPlugin> Q_EXPORT_PLUGIN2(qSlicerAstroModelingModule, qSlicerAstroModelingModule); #endif //----------------------------------------------------------------------------- /// \ingroup SlicerAstro_QtModules_AstroModeling class qSlicerAstroModelingModulePrivate { public: qSlicerAstroModelingModulePrivate(); }; //----------------------------------------------------------------------------- // qSlicerAstroModelingModulePrivate methods //----------------------------------------------------------------------------- qSlicerAstroModelingModulePrivate::qSlicerAstroModelingModulePrivate() { } //----------------------------------------------------------------------------- // qSlicerAstroModelingModule methods //----------------------------------------------------------------------------- qSlicerAstroModelingModule::qSlicerAstroModelingModule(QObject* _parent) : Superclass(_parent) , d_ptr(new qSlicerAstroModelingModulePrivate) { } //----------------------------------------------------------------------------- qSlicerAstroModelingModule::~qSlicerAstroModelingModule() { } //----------------------------------------------------------------------------- QString qSlicerAstroModelingModule::helpText()const { return "AstroModeling module fits tilted-ring models on a HI datacube using 3DBarolo " "(http://editeodoro.github.io/Bbarolo/). " "Specifically, SlicerAstro wraps a branch of 3DBarolo " "(https://github.com/Punzo/Bbarolo) which corresponds to " "3DBarolo v1.4 (git tag: cffc01c97dabfa7f9fe98d94b8e743088df56562)"; } //----------------------------------------------------------------------------- QString qSlicerAstroModelingModule::acknowledgementText()const { return "This module was developed by Davide Punzo. <br>" "This work was supported by ERC grant nr. 291531, " "and Slicer community. <br>" " Special thanks to Enrico di Teodoro (Australian National University)" " for support regarding 3DBarolo wrapping in SlicerAstro. <br>"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::contributors()const { QStringList moduleContributors; moduleContributors << QString("Davide Punzo (Kapteyn Astronomical Institute)"); moduleContributors << QString("Thijs van der Hulst (Kapteyn Astronomical Institute)"); moduleContributors << QString("Jos Roerdink (Johann Bernoulli Institute)"); return moduleContributors; } //----------------------------------------------------------------------------- QIcon qSlicerAstroModelingModule::icon()const { return QIcon(":/Icons/AstroModeling.png"); } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::categories()const { return QStringList() << "Astronomy" << "Quantification"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::associatedNodeTypes() const { return QStringList() << "vtkMRMLAstroModelingParametersNode"; } //----------------------------------------------------------------------------- QStringList qSlicerAstroModelingModule::dependencies()const { return QStringList() << "AstroVolume" << "Markups" << "Segmentations" ; } //----------------------------------------------------------------------------- void qSlicerAstroModelingModule::setup() { this->Superclass::setup(); // Register logic vtkSlicerAstroModelingLogic* AstroModelingLogic = vtkSlicerAstroModelingLogic::SafeDownCast(this->logic()); // Register AstroVolume module logic qSlicerAbstractCoreModule* astroVolumeModule = qSlicerCoreApplication::application()->moduleManager()->module("AstroVolume"); if (!astroVolumeModule) { qCritical() << "AstroVolume module is not found"; return; } vtkSlicerAstroVolumeLogic* astroVolumeLogic = vtkSlicerAstroVolumeLogic::SafeDownCast(astroVolumeModule->logic()); if (!astroVolumeLogic) { qCritical() << "AstroVolume logic is not found"; return; } AstroModelingLogic->SetAstroVolumeLogic(astroVolumeLogic); // Register Markups module logic qSlicerAbstractCoreModule* markupsModule = qSlicerCoreApplication::application()->moduleManager()->module("Markups"); if (!markupsModule) { qCritical() << "Markups module is not found"; return; } vtkSlicerMarkupsLogic* markupsLogic = vtkSlicerMarkupsLogic::SafeDownCast(markupsModule->logic()); if (!markupsLogic) { qCritical() << "Markups logic is not found"; return; } AstroModelingLogic->SetMarkupsLogic(markupsLogic); } //----------------------------------------------------------------------------- qSlicerAbstractModuleRepresentation * qSlicerAstroModelingModule::createWidgetRepresentation() { return new qSlicerAstroModelingModuleWidget; } //----------------------------------------------------------------------------- vtkMRMLAbstractLogic* qSlicerAstroModelingModule::createLogic() { return vtkSlicerAstroModelingLogic::New(); } <|endoftext|>
<commit_before>#include <RenHook/RenHook.hpp> #include <RenHook/Hooks/Hook.hpp> #include <RenHook/Memory/Protection.hpp> #include <RenHook/Threads/Threads.hpp> RenHook::Hook::Hook(const uintptr_t Address, const uintptr_t Detour) : m_address(Address) , m_size(GetMinimumSize(Address)) , m_memoryBlock(nullptr) { if (m_size >= 5) { // Create our memory block with hook size + necessary size for conditional jumps. m_memoryBlock = std::make_unique<RenHook::Memory::Block>(Address, m_size + (CountConditionalJumps(Address) * 16)); RenHook::Managers::Threads Threads; Threads.Suspend(); // Backup the original bytes. m_memoryBlock->CopyFrom(Address, m_size); Memory::Protection Protection(Address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Relocate RIP addresses with our address. RelocateRIP(Address, m_memoryBlock->GetAddress()); auto HookSize = WriteJump(Address, Detour, m_size); // Jump back to the original code (16 bytes). WriteJump(m_memoryBlock->GetAddress() + m_size, Address + m_size, 16); // Set unused bytes as NOP. if (HookSize < m_size) { std::memset(reinterpret_cast<uintptr_t*>(Address + HookSize), 0x90, m_size - HookSize); } Protection.Restore(); Threads.Resume(); } else { LOG_ERROR << L"Can't create a new hook at address " << std::hex << std::showbase << Address << L"because size is lower than 5, size is " << std::dec << m_size << LOG_LINE_SEPARATOR; } } RenHook::Hook::~Hook() { if (m_memoryBlock != nullptr) { RenHook::Managers::Threads Threads; Threads.Suspend(); Memory::Protection Protection(m_address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Restore the original bytes. m_memoryBlock->CopyTo(m_address, m_size); // Relocate RIP addresses back to their original value. RelocateRIP(m_memoryBlock->GetAddress(), m_address); Protection.Restore(); Threads.Resume(); #ifdef _DEBUG LOG_DEBUG << L"Hook for " << std::hex << std::showbase << m_address << L" was removed" << LOG_LINE_SEPARATOR; #endif } } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const uintptr_t Address) { return RenHook::Managers::Hooks::Get(Address); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Key) { return RenHook::Managers::Hooks::Get(Key); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Get(Module, Function); } void RenHook::Hook::Remove(const uintptr_t Address) { return RenHook::Managers::Hooks::Remove(Address); } void RenHook::Hook::Remove(const std::wstring& Key) { return RenHook::Managers::Hooks::Remove(Key); } void RenHook::Hook::Remove(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Remove(Module, Function); } void RenHook::Hook::RemoveAll() { RenHook::Managers::Hooks::RemoveAll(); } const bool RenHook::Hook::IsValid() const { return m_size >= 5 && m_memoryBlock != nullptr && m_memoryBlock->GetAddress() > 0; } const size_t RenHook::Hook::CheckSize(const RenHook::Capstone& Capstone, const size_t MinimumSize) const { size_t Size = 0; for (size_t i = 0; i < Capstone.GetTotalNumberOfInstruction(); i++) { Size += Capstone.GetInstructionSize(i); if (Size >= MinimumSize) { return Size; } } return 0; } const size_t RenHook::Hook::CountConditionalJumps(const uintptr_t Address) const { size_t Result = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, m_size); for (size_t i = 0; i < Capstone.GetTotalNumberOfInstructions(); i++) { auto Instruction = Capstone.GetInstructionAt(i); auto& Structure = Instruction->detail->x86; // Check all operands. for (size_t j = 0; j < Structure.op_count; j++) { auto& Operand = Structure.operands[j]; if (Operand.type == X86_OP_IMM && IsConditionalJump(Instruction->bytes, Instruction->size) == true) { Result++; } } } return Result; } const size_t RenHook::Hook::GetMinimumSize(const uintptr_t Address) const { size_t Size = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, 128); // Check if we can do a 16 byte jump. Size = CheckSize(Capstone, 16); // Check if we can do a 6 byte jump if we can't do a 16 byte jump. if (Size == 0) { Size = CheckSize(Capstone, 6); // Check if we can do a 5 byte jump if we can't do a 6 byte jump. if (Size == 0) { Size = CheckSize(Capstone, 5); } } return Size; } const bool RenHook::Hook::IsConditionalJump(const uint8_t* Bytes, const size_t Size) const { if (Size > 0) { // See https://software.intel.com/sites/default/files/managed/a4/60/325383-sdm-vol-2abcd.pdf (Jcc - Jump if Condition Is Met). if (Bytes[0] == 0xE3) { return true; } else if (Bytes[0] >= 0x70 && Bytes[0] <= 0x7F) { return true; } else if ((Bytes[0] == 0x0F && Size > 1) && (Bytes[1] >= 0x80 && Bytes[1] <= 0x8F)) { return true; } } return false; } const void RenHook::Hook::RelocateRIP(const uintptr_t From, const uintptr_t To) const { RenHook::Capstone Capstone; auto Instructions = Capstone.Disassemble(From, m_size); size_t NumberOfConditionalJumps = 0; for (size_t i = 0; i < Instructions; i++) { auto Instruction = Capstone.GetInstructionAt(i); auto& Structure = Instruction->detail->x86; // Check all operands. for (size_t j = 0; j < Structure.op_count; j++) { auto& Operand = Structure.operands[j]; uintptr_t DisplacementAddress = 0; if (Operand.type == X86_OP_MEM && Operand.mem.base == X86_REG_RIP) { // Calculate the displacement address. DisplacementAddress = Instruction->address + Instruction->size + Structure.disp; } else if (Operand.type == X86_OP_IMM) { // Skip instructions like "sub something, something". if (Structure.op_count > 1) { continue; } // Calculate the displacement address. DisplacementAddress = Structure.operands[0].imm; } if (DisplacementAddress > 0) { size_t UsedBytes = 0; if (Structure.rex > 0) { UsedBytes++; } for (int i = 0; i < sizeof(Structure.opcode); i++) { if (Structure.opcode[i] == 0) { break; } UsedBytes++; } if (Structure.modrm > 0) { UsedBytes++; } auto DisplacementSize = Instruction->size - UsedBytes; auto InstructionAddress = To + Instruction->address - From; if (IsConditionalJump(Instruction->bytes, Instruction->size) == true) { NumberOfConditionalJumps++; // block_base_address + size_of_the_hook + (size_of_trampoline * total_number_of_conditional_jumps_until_now) auto JumpAddress = m_memoryBlock->GetAddress() + m_size + (16 * NumberOfConditionalJumps); WriteJump(JumpAddress, DisplacementAddress, 16); DisplacementAddress = JumpAddress; } switch (DisplacementSize) { case 1: { *reinterpret_cast<int8_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int8_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int8_t)); break; } case 2: { *reinterpret_cast<int16_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int16_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int16_t)); break; } case 4: { *reinterpret_cast<int32_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int32_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int32_t)); break; } default: { LOG_ERROR << L"Invalid displacement size. Size is " << std::dec << DisplacementSize << L" bytes" << LOG_LINE_SEPARATOR; break; } } } } } } const size_t RenHook::Hook::WriteJump(const uintptr_t From, const uintptr_t To, const size_t Size) const { std::vector<uint8_t> Bytes; // Should we do a x64 or x86 jump? if (Size >= 16) { /* * push rax * mov rax, 0xCCCCCCCCCCCCCCCC * xchg rax, [rsp] * ret */ Bytes = { 0x50, 0x48, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x48, 0x87, 0x04, 0x24, 0xC3 }; // Set our detour function. *reinterpret_cast<uintptr_t*>(Bytes.data() + 3) = To; } else { // If the displacement is less than 2048 MB do a near jump or if the hook size is equal with 5, otherwise do a far jump. if (std::abs(reinterpret_cast<uintptr_t*>(From) - reinterpret_cast<uintptr_t*>(To)) <= 0x7fff0000 || Size == 5) { /* * jmp 0xCCCCCCCC */ Bytes = { 0xE9, 0xCC, 0xCC, 0xCC, 0xCC }; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 1) = CalculateDisplacement<int32_t>(From, To, Bytes.size()); } else { /* * jmp qword ptr ds:[0xCCCCCCCC] */ Bytes = { 0xFF, 0x25, 0xCC, 0xCC, 0xCC, 0xCC }; // Add the displacement right after our jump back to the original function which is located at "m_memoryBlock->GetAddress() + Size" and has a size of 16 bytes. auto Displacement = m_memoryBlock->GetAddress() + Size + 17; // Write the address in memory at RIP + Displacement. *reinterpret_cast<uintptr_t*>(Displacement) = To; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 2) = CalculateDisplacement<int32_t>(From, Displacement, Bytes.size()); } } // Calculate the hook size in bytes. auto HookSize = sizeof(uint8_t) * Bytes.size(); // Override the original bytes. std::memcpy(reinterpret_cast<uintptr_t*>(From), Bytes.data(), HookSize); return HookSize; }<commit_msg>Fix compilation error<commit_after>#include <RenHook/RenHook.hpp> #include <RenHook/Hooks/Hook.hpp> #include <RenHook/Memory/Protection.hpp> #include <RenHook/Threads/Threads.hpp> RenHook::Hook::Hook(const uintptr_t Address, const uintptr_t Detour) : m_address(Address) , m_size(GetMinimumSize(Address)) , m_memoryBlock(nullptr) { if (m_size >= 5) { // Create our memory block with hook size + necessary size for conditional jumps. m_memoryBlock = std::make_unique<RenHook::Memory::Block>(Address, m_size + (CountConditionalJumps(Address) * 16)); RenHook::Managers::Threads Threads; Threads.Suspend(); // Backup the original bytes. m_memoryBlock->CopyFrom(Address, m_size); Memory::Protection Protection(Address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Relocate RIP addresses with our address. RelocateRIP(Address, m_memoryBlock->GetAddress()); auto HookSize = WriteJump(Address, Detour, m_size); // Jump back to the original code (16 bytes). WriteJump(m_memoryBlock->GetAddress() + m_size, Address + m_size, 16); // Set unused bytes as NOP. if (HookSize < m_size) { std::memset(reinterpret_cast<uintptr_t*>(Address + HookSize), 0x90, m_size - HookSize); } Protection.Restore(); Threads.Resume(); } else { LOG_ERROR << L"Can't create a new hook at address " << std::hex << std::showbase << Address << L"because size is lower than 5, size is " << std::dec << m_size << LOG_LINE_SEPARATOR; } } RenHook::Hook::~Hook() { if (m_memoryBlock != nullptr) { RenHook::Managers::Threads Threads; Threads.Suspend(); Memory::Protection Protection(m_address, m_size); Protection.Change(PAGE_EXECUTE_READWRITE); // Restore the original bytes. m_memoryBlock->CopyTo(m_address, m_size); // Relocate RIP addresses back to their original value. RelocateRIP(m_memoryBlock->GetAddress(), m_address); Protection.Restore(); Threads.Resume(); #ifdef _DEBUG LOG_DEBUG << L"Hook for " << std::hex << std::showbase << m_address << L" was removed" << LOG_LINE_SEPARATOR; #endif } } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const uintptr_t Address) { return RenHook::Managers::Hooks::Get(Address); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Key) { return RenHook::Managers::Hooks::Get(Key); } std::shared_ptr<RenHook::Hook> RenHook::Hook::Get(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Get(Module, Function); } void RenHook::Hook::Remove(const uintptr_t Address) { return RenHook::Managers::Hooks::Remove(Address); } void RenHook::Hook::Remove(const std::wstring& Key) { return RenHook::Managers::Hooks::Remove(Key); } void RenHook::Hook::Remove(const std::wstring& Module, const std::wstring& Function) { return RenHook::Managers::Hooks::Remove(Module, Function); } void RenHook::Hook::RemoveAll() { RenHook::Managers::Hooks::RemoveAll(); } const bool RenHook::Hook::IsValid() const { return m_size >= 5 && m_memoryBlock != nullptr && m_memoryBlock->GetAddress() > 0; } const size_t RenHook::Hook::CheckSize(const RenHook::Capstone& Capstone, const size_t MinimumSize) const { size_t Size = 0; for (size_t i = 0; i < Capstone.GetTotalNumberOfInstructions(); i++) { Size += Capstone.GetInstructionSize(i); if (Size >= MinimumSize) { return Size; } } return 0; } const size_t RenHook::Hook::CountConditionalJumps(const uintptr_t Address) const { size_t Result = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, m_size); for (size_t i = 0; i < Capstone.GetTotalNumberOfInstructions(); i++) { auto Instruction = Capstone.GetInstructionAt(i); auto& Structure = Instruction->detail->x86; // Check all operands. for (size_t j = 0; j < Structure.op_count; j++) { auto& Operand = Structure.operands[j]; if (Operand.type == X86_OP_IMM && IsConditionalJump(Instruction->bytes, Instruction->size) == true) { Result++; } } } return Result; } const size_t RenHook::Hook::GetMinimumSize(const uintptr_t Address) const { size_t Size = 0; RenHook::Capstone Capstone; Capstone.Disassemble(Address, 128); // Check if we can do a 16 byte jump. Size = CheckSize(Capstone, 16); // Check if we can do a 6 byte jump if we can't do a 16 byte jump. if (Size == 0) { Size = CheckSize(Capstone, 6); // Check if we can do a 5 byte jump if we can't do a 6 byte jump. if (Size == 0) { Size = CheckSize(Capstone, 5); } } return Size; } const bool RenHook::Hook::IsConditionalJump(const uint8_t* Bytes, const size_t Size) const { if (Size > 0) { // See https://software.intel.com/sites/default/files/managed/a4/60/325383-sdm-vol-2abcd.pdf (Jcc - Jump if Condition Is Met). if (Bytes[0] == 0xE3) { return true; } else if (Bytes[0] >= 0x70 && Bytes[0] <= 0x7F) { return true; } else if ((Bytes[0] == 0x0F && Size > 1) && (Bytes[1] >= 0x80 && Bytes[1] <= 0x8F)) { return true; } } return false; } const void RenHook::Hook::RelocateRIP(const uintptr_t From, const uintptr_t To) const { RenHook::Capstone Capstone; auto Instructions = Capstone.Disassemble(From, m_size); size_t NumberOfConditionalJumps = 0; for (size_t i = 0; i < Instructions; i++) { auto Instruction = Capstone.GetInstructionAt(i); auto& Structure = Instruction->detail->x86; // Check all operands. for (size_t j = 0; j < Structure.op_count; j++) { auto& Operand = Structure.operands[j]; uintptr_t DisplacementAddress = 0; if (Operand.type == X86_OP_MEM && Operand.mem.base == X86_REG_RIP) { // Calculate the displacement address. DisplacementAddress = Instruction->address + Instruction->size + Structure.disp; } else if (Operand.type == X86_OP_IMM) { // Skip instructions like "sub something, something". if (Structure.op_count > 1) { continue; } // Calculate the displacement address. DisplacementAddress = Structure.operands[0].imm; } if (DisplacementAddress > 0) { size_t UsedBytes = 0; if (Structure.rex > 0) { UsedBytes++; } for (int i = 0; i < sizeof(Structure.opcode); i++) { if (Structure.opcode[i] == 0) { break; } UsedBytes++; } if (Structure.modrm > 0) { UsedBytes++; } auto DisplacementSize = Instruction->size - UsedBytes; auto InstructionAddress = To + Instruction->address - From; if (IsConditionalJump(Instruction->bytes, Instruction->size) == true) { NumberOfConditionalJumps++; // block_base_address + size_of_the_hook + (size_of_trampoline * total_number_of_conditional_jumps_until_now) auto JumpAddress = m_memoryBlock->GetAddress() + m_size + (16 * NumberOfConditionalJumps); WriteJump(JumpAddress, DisplacementAddress, 16); DisplacementAddress = JumpAddress; } switch (DisplacementSize) { case 1: { *reinterpret_cast<int8_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int8_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int8_t)); break; } case 2: { *reinterpret_cast<int16_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int16_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int16_t)); break; } case 4: { *reinterpret_cast<int32_t*>(InstructionAddress + UsedBytes) = CalculateDisplacement<int32_t>(InstructionAddress, DisplacementAddress, UsedBytes + sizeof(int32_t)); break; } default: { LOG_ERROR << L"Invalid displacement size. Size is " << std::dec << DisplacementSize << L" bytes" << LOG_LINE_SEPARATOR; break; } } } } } } const size_t RenHook::Hook::WriteJump(const uintptr_t From, const uintptr_t To, const size_t Size) const { std::vector<uint8_t> Bytes; // Should we do a x64 or x86 jump? if (Size >= 16) { /* * push rax * mov rax, 0xCCCCCCCCCCCCCCCC * xchg rax, [rsp] * ret */ Bytes = { 0x50, 0x48, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x48, 0x87, 0x04, 0x24, 0xC3 }; // Set our detour function. *reinterpret_cast<uintptr_t*>(Bytes.data() + 3) = To; } else { // If the displacement is less than 2048 MB do a near jump or if the hook size is equal with 5, otherwise do a far jump. if (std::abs(reinterpret_cast<uintptr_t*>(From) - reinterpret_cast<uintptr_t*>(To)) <= 0x7fff0000 || Size == 5) { /* * jmp 0xCCCCCCCC */ Bytes = { 0xE9, 0xCC, 0xCC, 0xCC, 0xCC }; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 1) = CalculateDisplacement<int32_t>(From, To, Bytes.size()); } else { /* * jmp qword ptr ds:[0xCCCCCCCC] */ Bytes = { 0xFF, 0x25, 0xCC, 0xCC, 0xCC, 0xCC }; // Add the displacement right after our jump back to the original function which is located at "m_memoryBlock->GetAddress() + Size" and has a size of 16 bytes. auto Displacement = m_memoryBlock->GetAddress() + Size + 17; // Write the address in memory at RIP + Displacement. *reinterpret_cast<uintptr_t*>(Displacement) = To; // Set our detour function. *reinterpret_cast<int32_t*>(Bytes.data() + 2) = CalculateDisplacement<int32_t>(From, Displacement, Bytes.size()); } } // Calculate the hook size in bytes. auto HookSize = sizeof(uint8_t) * Bytes.size(); // Override the original bytes. std::memcpy(reinterpret_cast<uintptr_t*>(From), Bytes.data(), HookSize); return HookSize; }<|endoftext|>
<commit_before> #include "StdSynan.h" #include "RusSentence.h" void InitCopulList(StringVector& v_CopulList) { v_CopulList.clear(); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); } bool HasAdjInNom(const CSynWord& _W) { for (int i = 0; i < _W.m_Homonyms.size(); i++) if (_W.m_Homonyms[i].HasPos(ADJ_FULL) && _W.m_Homonyms[i].HasGrammem(rNominativ)) return true; return false; } bool HasNounInGen(const CSynWord& _W) { for (int i = 0; i < _W.m_Homonyms.size(); i++) if ( _W.m_Homonyms[i].IsSynNoun() && _W.m_Homonyms[i].HasGrammem(rGenitiv) ) return true; return false; } bool HasGenderNumberCaseNP(const CSynWord& _W1, const CSynWord& _W2) { for (int i = 0; i < _W1.m_Homonyms.size(); i++) for (int k = 0; k < _W2.m_Homonyms.size(); k++) if (_W1.GetOpt()->GetGramTab()->GleicheGenderNumberCase(_W2.m_Homonyms[k].m_CommonGramCode.c_str(), _W1.m_Homonyms[i].m_GramCodes.c_str(), _W2.m_Homonyms[k].m_GramCodes.c_str())) return true; return false; } bool HasNounInNomSgPl(const CSynWord &W) { for (int i = 0; i < W.m_Homonyms.size(); i++) if ( W.m_Homonyms[i].IsSynNoun() ) if ( W.m_Homonyms[i].HasGrammem(rNominativ) && W.m_Homonyms[i].HasGrammem(rSingular) && W.m_Homonyms[i].HasGrammem(rPlural) ) return true; return false; } CSynWord CreateDash(CSentence* pSent) { CSynWord W (pSent); CSynHomonym NewDashHom (pSent); NewDashHom.SetLemma("-"); W.SetWordStr("-", pSent->GetOpt()->m_Language); W.m_bDash = true; W.AddDes(OPun); W.AddDes(OHyp); W.m_bArtificialCreated = true; W.m_Homonyms.push_back(NewDashHom); return W; }; void CRusSentence::BuildDash(int iClauseNum, int iWrdAfter, bool bCopul) { SClauseType type; CClause& pClause = GetClause(iClauseNum); if (bCopul) { pClause.ChangeAllClauseTypesToOneType(SClauseType(COPUL_T, -1,-1)); return; } if ( m_Words[iWrdAfter].IsInOborot() ) return; if (pClause.IsInTermin(iWrdAfter)) return; if (IsBetweenGraphematicalPairDescriptors(iWrdAfter)) return; int DashWordNo = iWrdAfter + 1; m_Words.insert(m_Words.begin() + DashWordNo, CreateDash(this)); RecalculateIndicesAfterInsertingWord(DashWordNo); pClause.ChangeAllClauseTypesToOneType(SClauseType(DASH_T, DashWordNo, 0) ); } void CRusSentence::TryToRebuildDashInClause() { StringVector v_CopulList; InitCopulList(v_CopulList); for (int ClauseNo = 0; ClauseNo < GetClausesCount(); ClauseNo++) { CClause& pClause = GetClause(ClauseNo); if (!pClause.m_vectorTypes.empty()) continue; bool bHasDash = false; if ( pClause.m_iFirstWord != 0 ) for ( int tt = pClause.m_iFirstWord; tt <= pClause.m_iLastWord; tt++ ) if ( m_Words[tt].m_bDash ) { bHasDash = true; break; } if ( bHasDash ) continue; int j = pClause.m_iFirstWord; for (; j <= pClause.m_iLastWord; j++) if ( !m_Words[j].GetSynHomonym(0).IsLemma("") && m_Words[j].GetHomonymByPOS(PREP) != -1 ) break; if ( j < pClause.m_iLastWord ) continue; vector<int> Noun_Nom, Adj_Nom, Eto, Noun_Gen, Copul_Words, Noun_NomSgPl; int Prep_U = -1; bool Vozrast = false; for (j = pClause.m_iFirstWord; j <= pClause.m_iLastWord; j++) { if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) { Eto.push_back(j); continue; } for (int ll = 0; ll < v_CopulList.size(); ll++) if ( m_Words[j].m_strWord == v_CopulList[ll].c_str() ) { Copul_Words.push_back(j); continue; } if ( m_Words[j].GetHomonymsCount() > 1 ) continue; if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) continue; if ( HasNounInNom( m_Words[j]) && !m_Words[j].HasDes(OFAM2) ) { Noun_Nom.push_back(j); continue; } if ( HasAdjInNom(m_Words[j]) && !m_Words[j].HasDes(OFAM2) ) { Adj_Nom.push_back(j); continue; } if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) { Prep_U = j; continue; } if ( HasNounInGen(m_Words[j]) ) Noun_Gen.push_back(j); if ( HasNounInNomSgPl( m_Words[j] ) ) Noun_NomSgPl.push_back(j); if (0 == Adj_Nom.size() && 0 == Noun_Nom.size() && isdigit((BYTE)m_Words[j].m_strWord[0]) // 33. && m_Words[j].m_strWord.find("-") == -1) { Vozrast = true; Adj_Nom.push_back(j); continue; } } if (0 == Noun_Nom.size() && 0 == Eto.size() && 0 == Adj_Nom.size() && -1 == Prep_U) continue; if (0 == Noun_Nom.size() && 0 == Eto.size() && 1 == Adj_Nom.size() && -1 == Prep_U) // . for (j = pClause.m_iFirstWord; j <= pClause.m_iLastWord; j++) { m_Words[j].SetHomonymsDel(true); for (int i = 0; i < m_Words[j].m_Homonyms.size() && 0 == Noun_Nom.size(); i++) { if ( m_Words[j].m_Homonyms[i].IsSynNoun() ) { if ( m_Words[j].m_Homonyms[i].HasGrammem(rNominativ) || (Vozrast && m_Words[j].m_Homonyms[i].HasGrammem(rDativ))) // 33. { m_Words[j].m_Homonyms[i].m_bDelete = false; Noun_Nom.push_back(j); } } } if (Noun_Nom.size() > 0 && find(Noun_Nom.begin(), Noun_Nom.end(), j) != Noun_Nom.end()) m_Words[j].DeleteMarkedHomonymsBeforeClauses(); else m_Words[j].SetHomonymsDel(false); } else Vozrast = false; if (Noun_Nom.size() > 1) { BYTE up_let = m_Words[Noun_Nom[1]].m_strWord[0]; if (!is_russian_upper(up_let)) { int k = 0; for (; k < Copul_Words.size(); k++) if (Copul_Words[k] > Noun_Nom[0] && Copul_Words[k] < Noun_Nom[1]) { BuildDash(ClauseNo, -1, true); break; } if ( k == Copul_Words.size()) BuildDash(ClauseNo, Noun_Nom[0]); } continue; } if ( Noun_Nom.size() > 0 && Eto.size() > 0 ) { QWORD tormoz = _QM(rNeutrum) | _QM(rSingular) | _QM(rNominativ); for (int k = 0; k < Eto.size() && k < Noun_Nom.size(); k++) // "" " " if (!m_Words[Noun_Nom[k]].GetSynHomonym(0).HasSetOfGrammemsExact(tormoz) ) if (Noun_Nom[k] > Eto[k]) { BuildDash(ClauseNo, Eto[k]); continue; } } bool bPersCl, bEncCl; bPersCl = bEncCl = false; int cc = ClauseNo-1; for (; ClauseNo > 1 && cc >= 0; cc--) { CClause& pClauseBefore = GetClause(cc); if ( pClauseBefore.HasType(VERB_PERS_T) && pClauseBefore.HasLeftStarter() ) { bEncCl = true; continue; } if ( pClauseBefore.HasType(PARTICIPLE_T) || pClauseBefore.HasType(ADVERB_PARTICIPLE_T) ) { bEncCl = true; continue; } if ( pClauseBefore.HasType(DASH_T) ) break; if ( ( !pClauseBefore.HasType(INFINITIVE_T) && !pClauseBefore.m_vectorTypes.empty() ) || !(pClauseBefore.m_vectorTypes.size() == 1) ) { if (bEncCl) bPersCl = true; break; } } if (bPersCl) continue; bPersCl = bEncCl = false; for (cc = ClauseNo+1; ClauseNo < GetClausesCount()-2 && cc < GetClausesCount(); cc++) { CClause& pClauseAfter = GetClause(cc); if ( pClauseAfter.HasType(VERB_PERS_T) && pClauseAfter.HasLeftStarter() ) { bEncCl = true; continue; } if ( pClauseAfter.HasType(PARTICIPLE_T) || pClauseAfter.HasType(ADVERB_PARTICIPLE_T) ) { bEncCl = true; continue; } if ( pClauseAfter.HasType(DASH_T) ) break; if ( ( !pClauseAfter.HasType(INFINITIVE_T) && !pClauseAfter.m_vectorTypes.empty() ) || !(pClauseAfter.m_vectorTypes.size() == 1) ) { if (bEncCl) bPersCl = true; break; } } if (bPersCl) continue; if ( Noun_Nom.size() > 0 && Adj_Nom.size() > 0 ) { for (int k = 0; k < Noun_Nom.size() && k < Adj_Nom.size(); k++) if ( Noun_Nom[k] < Adj_Nom[k] && (pClause.m_iLastWord == Adj_Nom[k] || !HasGenderNumberCaseNP(m_Words[Adj_Nom[k]], m_Words[Adj_Nom[k]+1]) || Vozrast) // 33 ) { if(Vozrast) m_Words[Adj_Nom[k]].GetSynHomonym(0).ModifyGrammems( _QM(rPlural) | _QM(rNominativ) | _QM(rAccusativ)); BuildDash(ClauseNo, Noun_Nom[k]); } continue; } if (-1 != Prep_U && Noun_Gen.size() > 0 && ( Noun_Nom.size() > 0 || Noun_NomSgPl.size() > 0 ) ) { for (int m = 0; m < Noun_Gen.size(); m++) if (Prep_U < Noun_Gen[m]) { Prep_U = Noun_Gen[m]; break; } if ( Noun_Nom.size() > 0 ) { if ( Prep_U > Noun_Nom[0] ) BuildDash(ClauseNo, Noun_Nom[0]); else BuildDash(ClauseNo, Prep_U); continue; } int iNomSgPl = -1; for ( int tt = 0; tt < Noun_NomSgPl.size(); tt++ ) if ( Prep_U != Noun_NomSgPl[tt] ) { iNomSgPl = Noun_NomSgPl[tt]; break; } if ( -1 != iNomSgPl ) if ( Prep_U > iNomSgPl ) BuildDash(ClauseNo, iNomSgPl); else BuildDash(ClauseNo, Prep_U); } } } <commit_msg>small fix<commit_after> #include "StdSynan.h" #include "RusSentence.h" void InitCopulList(StringVector& v_CopulList) { v_CopulList.clear(); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); v_CopulList.push_back(""); } bool HasAdjInNom(const CSynWord& _W) { for (int i = 0; i < _W.m_Homonyms.size(); i++) if (_W.m_Homonyms[i].HasPos(ADJ_FULL) && _W.m_Homonyms[i].HasGrammem(rNominativ)) return true; return false; } bool HasNounInGen(const CSynWord& _W) { for (int i = 0; i < _W.m_Homonyms.size(); i++) if ( _W.m_Homonyms[i].IsSynNoun() && _W.m_Homonyms[i].HasGrammem(rGenitiv) ) return true; return false; } bool HasGenderNumberCaseNP(const CSynWord& _W1, const CSynWord& _W2) { for (int i = 0; i < _W1.m_Homonyms.size(); i++) for (int k = 0; k < _W2.m_Homonyms.size(); k++) if (_W1.GetOpt()->GetGramTab()->GleicheGenderNumberCase(_W2.m_Homonyms[k].m_CommonGramCode.c_str(), _W1.m_Homonyms[i].m_GramCodes.c_str(), _W2.m_Homonyms[k].m_GramCodes.c_str())) return true; return false; } bool HasNounInNomSgPl(const CSynWord &W) { for (int i = 0; i < W.m_Homonyms.size(); i++) if ( W.m_Homonyms[i].IsSynNoun() ) if ( W.m_Homonyms[i].HasGrammem(rNominativ) && W.m_Homonyms[i].HasGrammem(rSingular) && W.m_Homonyms[i].HasGrammem(rPlural) ) return true; return false; } CSynWord CreateDash(CSentence* pSent) { CSynWord W (pSent); CSynHomonym NewDashHom (pSent); NewDashHom.SetLemma("-"); W.SetWordStr("-", pSent->GetOpt()->m_Language); W.m_bDash = true; W.AddDes(OPun); W.AddDes(OHyp); W.m_bArtificialCreated = true; W.m_Homonyms.push_back(NewDashHom); return W; }; void CRusSentence::BuildDash(int iClauseNum, int iWrdAfter, bool bCopul) { SClauseType type; CClause& pClause = GetClause(iClauseNum); if (bCopul) { pClause.ChangeAllClauseTypesToOneType(SClauseType(COPUL_T, -1,-1)); return; } if ( m_Words[iWrdAfter].IsInOborot() ) return; if (pClause.IsInTermin(iWrdAfter)) return; if (IsBetweenGraphematicalPairDescriptors(iWrdAfter)) return; int DashWordNo = iWrdAfter + 1; m_Words.insert(m_Words.begin() + DashWordNo, CreateDash(this)); RecalculateIndicesAfterInsertingWord(DashWordNo); pClause.ChangeAllClauseTypesToOneType(SClauseType(DASH_T, DashWordNo, 0) ); } void CRusSentence::TryToRebuildDashInClause() { StringVector v_CopulList; InitCopulList(v_CopulList); for (int ClauseNo = 0; ClauseNo < GetClausesCount(); ClauseNo++) { CClause& pClause = GetClause(ClauseNo); if (!pClause.m_vectorTypes.empty()) continue; bool bHasDash = false; if ( pClause.m_iFirstWord != 0 ) for ( int tt = pClause.m_iFirstWord; tt <= pClause.m_iLastWord; tt++ ) if ( m_Words[tt].m_bDash ) { bHasDash = true; break; } if ( bHasDash ) continue; int j = pClause.m_iFirstWord; for (; j <= pClause.m_iLastWord; j++) if ( !m_Words[j].GetSynHomonym(0).IsLemma("") && m_Words[j].GetHomonymByPOS(PREP) != -1 ) break; if ( j < pClause.m_iLastWord ) continue; vector<int> Noun_Nom, Adj_Nom, Eto, Noun_Gen, Copul_Words, Noun_NomSgPl; int Prep_U = -1; bool Vozrast = false; for (j = pClause.m_iFirstWord; j <= pClause.m_iLastWord; j++) { if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) { Eto.push_back(j); continue; } for (int ll = 0; ll < v_CopulList.size(); ll++) if ( m_Words[j].m_strWord == v_CopulList[ll].c_str() ) { Copul_Words.push_back(j); continue; } if ( m_Words[j].GetHomonymsCount() > 1 ) continue; if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) continue; if ( HasNounInNom( m_Words[j]) && !m_Words[j].HasDes(OFAM2) ) { Noun_Nom.push_back(j); continue; } if ( HasAdjInNom(m_Words[j]) && !m_Words[j].HasDes(OFAM2) ) { Adj_Nom.push_back(j); continue; } if ( m_Words[j].GetSynHomonym(0).IsLemma("") ) { Prep_U = j; continue; } if ( HasNounInGen(m_Words[j]) ) Noun_Gen.push_back(j); if ( HasNounInNomSgPl( m_Words[j] ) ) Noun_NomSgPl.push_back(j); if (0 == Adj_Nom.size() && 0 == Noun_Nom.size() && isdigit((BYTE)m_Words[j].m_strWord[0]) // 33. && m_Words[j].m_strWord.find("-") == -1) { Vozrast = true; Adj_Nom.push_back(j); continue; } } if (0 == Noun_Nom.size() && 0 == Eto.size() && 0 == Adj_Nom.size() && -1 == Prep_U) continue; if (0 == Noun_Nom.size() && 0 == Eto.size() && 1 == Adj_Nom.size() && -1 == Prep_U) // . for (j = pClause.m_iFirstWord; j <= pClause.m_iLastWord; j++) { m_Words[j].SetHomonymsDel(true); for (int i = 0; i < m_Words[j].m_Homonyms.size() && 0 == Noun_Nom.size(); i++) { if ( m_Words[j].m_Homonyms[i].IsSynNoun() ) { if ( (m_Words[j].m_Homonyms[i].HasGrammem(rNominativ) && (m_Words[j].m_Homonyms[i].m_iGrammems & rAllNumbers & m_Words[Adj_Nom[0]].GetGrammems())>0 && (m_Words[j].m_Homonyms[i].m_iGrammems & rAllGenders & m_Words[Adj_Nom[0]].GetGrammems())>0) || (Vozrast && m_Words[j].m_Homonyms[i].HasGrammem(rDativ))) // 33. { m_Words[j].m_Homonyms[i].m_bDelete = false; Noun_Nom.push_back(j); } } } if (Noun_Nom.size() > 0 && find(Noun_Nom.begin(), Noun_Nom.end(), j) != Noun_Nom.end()) m_Words[j].DeleteMarkedHomonymsBeforeClauses(); else m_Words[j].SetHomonymsDel(false); } else Vozrast = false; if (Noun_Nom.size() > 1) { BYTE up_let = m_Words[Noun_Nom[1]].m_strWord[0]; if (!is_russian_upper(up_let)) { int k = 0; for (; k < Copul_Words.size(); k++) if (Copul_Words[k] > Noun_Nom[0] && Copul_Words[k] < Noun_Nom[1]) { BuildDash(ClauseNo, -1, true); break; } if ( k == Copul_Words.size()) BuildDash(ClauseNo, Noun_Nom[0]); } continue; } if ( Noun_Nom.size() > 0 && Eto.size() > 0 ) { QWORD tormoz = _QM(rNeutrum) | _QM(rSingular) | _QM(rNominativ); for (int k = 0; k < Eto.size() && k < Noun_Nom.size(); k++) // "" " " if (!m_Words[Noun_Nom[k]].GetSynHomonym(0).HasSetOfGrammemsExact(tormoz) ) if (Noun_Nom[k] > Eto[k]) { BuildDash(ClauseNo, Eto[k]); continue; } } bool bPersCl, bEncCl; bPersCl = bEncCl = false; int cc = ClauseNo-1; for (; ClauseNo > 1 && cc >= 0; cc--) { CClause& pClauseBefore = GetClause(cc); if ( pClauseBefore.HasType(VERB_PERS_T) && pClauseBefore.HasLeftStarter() ) { bEncCl = true; continue; } if ( pClauseBefore.HasType(PARTICIPLE_T) || pClauseBefore.HasType(ADVERB_PARTICIPLE_T) ) { bEncCl = true; continue; } if ( pClauseBefore.HasType(DASH_T) ) break; if ( ( !pClauseBefore.HasType(INFINITIVE_T) && !pClauseBefore.m_vectorTypes.empty() ) || !(pClauseBefore.m_vectorTypes.size() == 1) ) { if (bEncCl) bPersCl = true; break; } } if (bPersCl) continue; bPersCl = bEncCl = false; for (cc = ClauseNo+1; ClauseNo < GetClausesCount()-2 && cc < GetClausesCount(); cc++) { CClause& pClauseAfter = GetClause(cc); if ( pClauseAfter.HasType(VERB_PERS_T) && pClauseAfter.HasLeftStarter() ) { bEncCl = true; continue; } if ( pClauseAfter.HasType(PARTICIPLE_T) || pClauseAfter.HasType(ADVERB_PARTICIPLE_T) ) { bEncCl = true; continue; } if ( pClauseAfter.HasType(DASH_T) ) break; if ( ( !pClauseAfter.HasType(INFINITIVE_T) && !pClauseAfter.m_vectorTypes.empty() ) || !(pClauseAfter.m_vectorTypes.size() == 1) ) { if (bEncCl) bPersCl = true; break; } } if (bPersCl) continue; if ( Noun_Nom.size() > 0 && Adj_Nom.size() > 0 ) { for (int k = 0; k < Noun_Nom.size() && k < Adj_Nom.size(); k++) if ( Noun_Nom[k] < Adj_Nom[k] && (pClause.m_iLastWord == Adj_Nom[k] || !HasGenderNumberCaseNP(m_Words[Adj_Nom[k]], m_Words[Adj_Nom[k]+1]) || Vozrast) // 33 ) { if(Vozrast) m_Words[Adj_Nom[k]].GetSynHomonym(0).ModifyGrammems( _QM(rPlural) | _QM(rNominativ) | _QM(rAccusativ)); BuildDash(ClauseNo, Noun_Nom[k]); } continue; } if (-1 != Prep_U && Noun_Gen.size() > 0 && ( Noun_Nom.size() > 0 || Noun_NomSgPl.size() > 0 ) ) { for (int m = 0; m < Noun_Gen.size(); m++) if (Prep_U < Noun_Gen[m]) { Prep_U = Noun_Gen[m]; break; } if ( Noun_Nom.size() > 0 ) { if ( Prep_U > Noun_Nom[0] ) BuildDash(ClauseNo, Noun_Nom[0]); else BuildDash(ClauseNo, Prep_U); continue; } int iNomSgPl = -1; for ( int tt = 0; tt < Noun_NomSgPl.size(); tt++ ) if ( Prep_U != Noun_NomSgPl[tt] ) { iNomSgPl = Noun_NomSgPl[tt]; break; } if ( -1 != iNomSgPl ) if ( Prep_U > iNomSgPl ) BuildDash(ClauseNo, iNomSgPl); else BuildDash(ClauseNo, Prep_U); } } } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file rdofile.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 07.11.2020 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ----------------------------------------------------------------------- INCLUDES #ifdef COMPILER_VISUAL_STUDIO # include <Windows.h> #else # include <unistd.h> #endif // COMPILER_VISUAL_STUDIO #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/rdocommon.h" // -------------------------------------------------------------------------------- OPEN_RDO_NAMESPACE rbool File::read_only(CREF(tstring) name) { #ifdef COMPILER_VISUAL_STUDIO return _access(name.c_str(), 04) == 0 && _access(name.c_str(), 06) == -1; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC return access(name.c_str(), R_OK) == 0 && access(name.c_str(), W_OK) == -1; #endif // COMPILER_GCC } rbool File::splitpath(CREF(tstring) name, REF(tstring) fileDir, REF(tstring) fileName, REF(tstring) fileExt) { boost::filesystem::path from(name); boost::filesystem::path parentDir(from.parent_path()); boost::filesystem::path rootName = parentDir.root_name(); boost::filesystem::path rootDirectory = parentDir.root_directory(); if (parentDir != (rootName / rootDirectory)) { parentDir /= rootDirectory; } fileDir = parentDir.string(); fileName = from.stem().string(); fileExt = from.extension().string(); return true; } tstring File::getTempFileName() { #ifdef COMPILER_VISUAL_STUDIO const ruint BUFSIZE = 4096; tchar lpPathBuffer[BUFSIZE]; if (::GetTempPath(BUFSIZE, lpPathBuffer) == 0) { return tstring(); } tchar szTempName[MAX_PATH]; if (::GetTempFileName(lpPathBuffer, NULL, 0, szTempName) == 0) { return tstring(); } return szTempName; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC boost::uuids::random_generator random_gen; tstring tempFileName = tstring("/tmp/rdo_temp_file_num_") + boost::uuids::to_string(random_gen()); create(tempFileName); return tempFileName; #endif // COMPILER_GCC } tstring File::extractFilePath(CREF(tstring) fileName) { boost::filesystem::path fullFileName(fileName); tstring result = (fullFileName.make_preferred().parent_path() / boost::filesystem::path("/").make_preferred()).string(); return result; } rbool File::trimLeft(CREF(tstring) name) { boost::filesystem::ifstream inputStream(name.c_str(), std::ios::binary); std::stringstream sstream; if (!inputStream.good()) { return false; } rbool empty = true; while (!inputStream.eof()) { char byte; inputStream.get(byte); if (empty) { if (byte != ' ' && byte != '\t' && byte != '\n' && byte != '\r') { empty = false; } } if (!empty) { sstream.write(&byte, 1); } } inputStream.close(); boost::filesystem::path to (name); try { if (!boost::filesystem::remove(to)) { return false; } boost::filesystem::ofstream outStream(name.c_str(), std::ios::binary); outStream << sstream.str(); } catch (CREF(boost::system::error_code)) { return false; } return true; } CLOSE_RDO_NAMESPACE <commit_msg> - исправлена генерации пути под линуксом<commit_after>/*! \copyright (c) RDO-Team, 2011 \file rdofile.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 07.11.2020 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ----------------------------------------------------------------------- INCLUDES #ifdef COMPILER_VISUAL_STUDIO # include <Windows.h> #else # include <unistd.h> #endif // COMPILER_VISUAL_STUDIO #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/rdocommon.h" // -------------------------------------------------------------------------------- OPEN_RDO_NAMESPACE rbool File::read_only(CREF(tstring) name) { #ifdef COMPILER_VISUAL_STUDIO return _access(name.c_str(), 04) == 0 && _access(name.c_str(), 06) == -1; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC return access(name.c_str(), R_OK) == 0 && access(name.c_str(), W_OK) == -1; #endif // COMPILER_GCC } rbool File::splitpath(CREF(tstring) name, REF(tstring) fileDir, REF(tstring) fileName, REF(tstring) fileExt) { boost::filesystem::path from(name); boost::filesystem::path parentDir(from.parent_path()); boost::filesystem::path rootName = parentDir.root_name(); boost::filesystem::path rootDirectory = parentDir.root_directory(); if ((rootName.empty() && rootDirectory.empty()) || parentDir != (rootName / rootDirectory)) { parentDir /= boost::filesystem::path("/").make_preferred(); } fileDir = parentDir.string(); fileName = from.stem().string(); fileExt = from.extension().string(); return true; } tstring File::getTempFileName() { #ifdef COMPILER_VISUAL_STUDIO const ruint BUFSIZE = 4096; tchar lpPathBuffer[BUFSIZE]; if (::GetTempPath(BUFSIZE, lpPathBuffer) == 0) { return tstring(); } tchar szTempName[MAX_PATH]; if (::GetTempFileName(lpPathBuffer, NULL, 0, szTempName) == 0) { return tstring(); } return szTempName; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC boost::uuids::random_generator random_gen; tstring tempFileName = tstring("/tmp/rdo_temp_file_num_") + boost::uuids::to_string(random_gen()); create(tempFileName); return tempFileName; #endif // COMPILER_GCC } tstring File::extractFilePath(CREF(tstring) fileName) { boost::filesystem::path fullFileName(fileName); tstring result = (fullFileName.make_preferred().parent_path() / boost::filesystem::path("/").make_preferred()).string(); return result; } rbool File::trimLeft(CREF(tstring) name) { boost::filesystem::ifstream inputStream(name.c_str(), std::ios::binary); std::stringstream sstream; if (!inputStream.good()) { return false; } rbool empty = true; while (!inputStream.eof()) { char byte; inputStream.get(byte); if (empty) { if (byte != ' ' && byte != '\t' && byte != '\n' && byte != '\r') { empty = false; } } if (!empty) { sstream.write(&byte, 1); } } inputStream.close(); boost::filesystem::path to (name); try { if (!boost::filesystem::remove(to)) { return false; } boost::filesystem::ofstream outStream(name.c_str(), std::ios::binary); outStream << sstream.str(); } catch (CREF(boost::system::error_code)) { return false; } return true; } CLOSE_RDO_NAMESPACE <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" #include "PlayerState.h" #include "Pack.h" #include "Protocol.h" #include "StateDatabase.h" PlayerState::PlayerState() : order(0), status(DeadStatus), azimuth(0.0f), angVel(0.0f) { pos[0] = pos[1] = pos[2] = 0.0f; velocity[0] = velocity[0] = velocity[2] = 0.0f; } void* PlayerState::pack(void* buf, uint16_t& code) { order++; buf = nboPackInt(buf, int32_t(order)); buf = nboPackShort(buf, int16_t(status)); if (BZDB.eval(StateDatabase::BZDB_NOSMALLPACKETS) > 0.0f) { code = MsgPlayerUpdate; buf = nboPackVector(buf, pos); buf = nboPackVector(buf, velocity); buf = nboPackFloat(buf, azimuth); buf = nboPackFloat(buf, angVel); } else { code = MsgPlayerUpdateSmall; float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); float maxVel = BZDB.eval(StateDatabase::BZDB_MAXVEL); float maxAngVel = BZDB.eval(StateDatabase::BZDB_MAXANGVEL); float tmpf; int16_t posShort[3], velShort[3], aziShort, angVelShort; printf ("maxVel = %f, maxAngVel = %f\n", maxVel, maxAngVel); for (int i=0; i<3; i++) { if (pos[i] >= worldSize) posShort[i] = 32767; else if (pos[i] <= -worldSize) posShort[i] = -32767; else { posShort[i] = (int16_t) ((pos[i] * 32767.0f) / worldSize); } if (velocity[i] >= maxVel) velShort[i] = 32767; else if (velocity[i] <= -maxVel) velShort[i] = -32767; else { velShort[i] = (int16_t) ((velocity[i] * 32767.0f) / maxVel); } } tmpf = fmodf (azimuth + M_PI, 2.0f * M_PI) - M_PI; // between -M_PI and M_PI aziShort = (int16_t) ((tmpf * 32767.0f) / M_PI); angVelShort = (int16_t) ((angVel * 32767.0f) / maxAngVel); buf = nboPackShort(buf, posShort[0]); buf = nboPackShort(buf, posShort[1]); buf = nboPackShort(buf, posShort[2]); buf = nboPackShort(buf, velShort[0]); buf = nboPackShort(buf, velShort[1]); buf = nboPackShort(buf, velShort[2]); buf = nboPackShort(buf, aziShort); buf = nboPackShort(buf, angVelShort); } return buf; } void* PlayerState::unpack(void* buf, uint16_t code) { int32_t inOrder; int16_t inStatus; buf = nboUnpackInt(buf, inOrder); buf = nboUnpackShort(buf, inStatus); order = int(inOrder); status = short(inStatus); if (code == MsgPlayerUpdate) { buf = nboUnpackVector(buf, pos); buf = nboUnpackVector(buf, velocity); buf = nboUnpackFloat(buf, azimuth); buf = nboUnpackFloat(buf, angVel); } else { float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); float maxVel = BZDB.eval(StateDatabase::BZDB_MAXVEL); float maxAngVel = BZDB.eval(StateDatabase::BZDB_MAXANGVEL); int16_t posShort[3], velShort[3], aziShort, angVelShort; buf = nboUnpackShort(buf, posShort[0]); buf = nboUnpackShort(buf, posShort[1]); buf = nboUnpackShort(buf, posShort[2]); buf = nboUnpackShort(buf, velShort[0]); buf = nboUnpackShort(buf, velShort[1]); buf = nboUnpackShort(buf, velShort[2]); buf = nboUnpackShort(buf, aziShort); buf = nboUnpackShort(buf, angVelShort); for (int i=0; i<3; i++) { pos[i] = ((float)posShort[i] * worldSize) / 32767.0f; velocity[i] = ((float)velShort[i] * maxVel) / 32767.0f; } azimuth = ((float)aziShort * M_PI) / 32767.0f; angVel = ((float)angVelShort * maxAngVel) / 32767.0f; } return buf; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>remove the printf()<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" #include "PlayerState.h" #include "Pack.h" #include "Protocol.h" #include "StateDatabase.h" PlayerState::PlayerState() : order(0), status(DeadStatus), azimuth(0.0f), angVel(0.0f) { pos[0] = pos[1] = pos[2] = 0.0f; velocity[0] = velocity[0] = velocity[2] = 0.0f; } void* PlayerState::pack(void* buf, uint16_t& code) { order++; buf = nboPackInt(buf, int32_t(order)); buf = nboPackShort(buf, int16_t(status)); if (BZDB.eval(StateDatabase::BZDB_NOSMALLPACKETS) > 0.0f) { code = MsgPlayerUpdate; buf = nboPackVector(buf, pos); buf = nboPackVector(buf, velocity); buf = nboPackFloat(buf, azimuth); buf = nboPackFloat(buf, angVel); } else { code = MsgPlayerUpdateSmall; float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); float maxVel = BZDB.eval(StateDatabase::BZDB_MAXVEL); float maxAngVel = BZDB.eval(StateDatabase::BZDB_MAXANGVEL); float tmpf; int16_t posShort[3], velShort[3], aziShort, angVelShort; for (int i=0; i<3; i++) { if (pos[i] >= worldSize) posShort[i] = 32767; else if (pos[i] <= -worldSize) posShort[i] = -32767; else { posShort[i] = (int16_t) ((pos[i] * 32767.0f) / worldSize); } if (velocity[i] >= maxVel) velShort[i] = 32767; else if (velocity[i] <= -maxVel) velShort[i] = -32767; else { velShort[i] = (int16_t) ((velocity[i] * 32767.0f) / maxVel); } } tmpf = fmodf (azimuth + M_PI, 2.0f * M_PI) - M_PI; // between -M_PI and M_PI aziShort = (int16_t) ((tmpf * 32767.0f) / M_PI); angVelShort = (int16_t) ((angVel * 32767.0f) / maxAngVel); buf = nboPackShort(buf, posShort[0]); buf = nboPackShort(buf, posShort[1]); buf = nboPackShort(buf, posShort[2]); buf = nboPackShort(buf, velShort[0]); buf = nboPackShort(buf, velShort[1]); buf = nboPackShort(buf, velShort[2]); buf = nboPackShort(buf, aziShort); buf = nboPackShort(buf, angVelShort); } return buf; } void* PlayerState::unpack(void* buf, uint16_t code) { int32_t inOrder; int16_t inStatus; buf = nboUnpackInt(buf, inOrder); buf = nboUnpackShort(buf, inStatus); order = int(inOrder); status = short(inStatus); if (code == MsgPlayerUpdate) { buf = nboUnpackVector(buf, pos); buf = nboUnpackVector(buf, velocity); buf = nboUnpackFloat(buf, azimuth); buf = nboUnpackFloat(buf, angVel); } else { float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); float maxVel = BZDB.eval(StateDatabase::BZDB_MAXVEL); float maxAngVel = BZDB.eval(StateDatabase::BZDB_MAXANGVEL); int16_t posShort[3], velShort[3], aziShort, angVelShort; buf = nboUnpackShort(buf, posShort[0]); buf = nboUnpackShort(buf, posShort[1]); buf = nboUnpackShort(buf, posShort[2]); buf = nboUnpackShort(buf, velShort[0]); buf = nboUnpackShort(buf, velShort[1]); buf = nboUnpackShort(buf, velShort[2]); buf = nboUnpackShort(buf, aziShort); buf = nboUnpackShort(buf, angVelShort); for (int i=0; i<3; i++) { pos[i] = ((float)posShort[i] * worldSize) / 32767.0f; velocity[i] = ((float)velShort[i] * maxVel) / 32767.0f; } azimuth = ((float)aziShort * M_PI) / 32767.0f; angVel = ((float)angVelShort * maxAngVel) / 32767.0f; } return buf; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2017 Baldur Karlsson * * 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 "api/replay/renderdoc_replay.h" #include "api/replay/version.h" #include "serialise/string_utils.h" #include <errno.h> #include <sys/stat.h> #include <unistd.h> #include "vk_core.h" #include "vk_replay.h" void VulkanReplay::OutputWindow::SetWindowHandle(WindowingSystem system, void *data) { m_WindowSystem = system; #if ENABLED(RDOC_XLIB) if(system == WindowingSystem::Xlib) { XlibWindowData *xdata = (XlibWindowData *)data; xlib.display = xdata->display; xlib.window = xdata->window; return; } #endif #if ENABLED(RDOC_XCB) if(system == WindowingSystem::XCB) { XCBWindowData *xdata = (XCBWindowData *)data; xcb.connection = xdata->connection; xcb.window = xdata->window; return; } #endif RDCERR("Unrecognised/unsupported window system %d", system); } void VulkanReplay::OutputWindow::CreateSurface(VkInstance inst) { #if ENABLED(RDOC_XLIB) if(m_WindowSystem == WindowingSystem::Xlib) { VkXlibSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.dpy = xlib.display; createInfo.window = xlib.window; VkResult vkr = ObjDisp(inst)->CreateXlibSurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface); RDCASSERTEQUAL(vkr, VK_SUCCESS); return; } #endif #if ENABLED(RDOC_XCB) if(m_WindowSystem == WindowingSystem::XCB) { VkXcbSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.connection = xcb.connection; createInfo.window = xcb.window; VkResult vkr = ObjDisp(inst)->CreateXcbSurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface); RDCASSERTEQUAL(vkr, VK_SUCCESS); return; } #endif RDCERR("Unrecognised/unsupported window system %d", m_WindowSystem); } void VulkanReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h) { if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end()) return; OutputWindow &outw = m_OutputWindows[id]; #if ENABLED(RDOC_XLIB) if(outw.m_WindowSystem == WindowingSystem::Xlib) { XWindowAttributes attr = {}; XGetWindowAttributes(outw.xlib.display, outw.xlib.window, &attr); w = (int32_t)attr.width; h = (int32_t)attr.height; return; } #endif #if ENABLED(RDOC_XCB) if(outw.m_WindowSystem == WindowingSystem::XCB) { xcb_get_geometry_cookie_t geomCookie = xcb_get_geometry(outw.xcb.connection, outw.xcb.window); // window is a xcb_drawable_t xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(outw.xcb.connection, geomCookie, NULL); w = (int32_t)geom->width; h = (int32_t)geom->height; free(geom); return; } #endif RDCERR("Unrecognised/unsupported window system %d", outw.m_WindowSystem); } const char *VulkanLibraryName = "libvulkan.so.1"; // embedded data file extern unsigned char driver_vulkan_renderdoc_json[]; extern int driver_vulkan_renderdoc_json_len; static std::string GenerateJSON(const std::string &sopath) { char *txt = (char *)driver_vulkan_renderdoc_json; int len = driver_vulkan_renderdoc_json_len; string json = string(txt, txt + len); const char dllPathString[] = ".\\\\renderdoc.dll"; size_t idx = json.find(dllPathString); json = json.substr(0, idx) + sopath + json.substr(idx + sizeof(dllPathString) - 1); const char majorString[] = "[MAJOR]"; idx = json.find(majorString); while(idx != string::npos) { json = json.substr(0, idx) + STRINGIZE(RENDERDOC_VERSION_MAJOR) + json.substr(idx + sizeof(majorString) - 1); idx = json.find(majorString); } const char minorString[] = "[MINOR]"; idx = json.find(minorString); while(idx != string::npos) { json = json.substr(0, idx) + STRINGIZE(RENDERDOC_VERSION_MINOR) + json.substr(idx + sizeof(minorString) - 1); idx = json.find(minorString); } return json; } static bool FileExists(const std::string &path) { return access(path.c_str(), F_OK) == 0; } static std::string GetSOFromJSON(const std::string &json) { char *json_string = new char[1024]; memset(json_string, 0, 1024); FILE *f = fopen(json.c_str(), "r"); if(f) { fread(json_string, 1, 1024, f); fclose(f); } string ret = ""; // The line is: // "library_path": "/foo/bar/librenderdoc.so", char *c = strstr(json_string, "library_path"); if(c) { c += sizeof("library_path\": \"") - 1; char *quote = strchr(c, '"'); if(quote) { *quote = 0; ret = c; } } delete[] json_string; return ret; } enum { USR, ETC, HOME, COUNT }; string layerRegistrationPath[COUNT] = { "/usr/share/vulkan/implicit_layer.d/renderdoc_capture.json", "/etc/vulkan/implicit_layer.d/renderdoc_capture.json", string(getenv("HOME")) + "/.local/share/vulkan/implicit_layer.d/renderdoc_capture.json"}; string GetThisLibPath() { string librenderdoc_path; FILE *f = fopen("/proc/self/maps", "r"); if(f) { // read the whole thing in one go. There's no need to try and be tight with // this allocation, so just make sure we can read everything. char *map_string = new char[1024 * 1024]; memset(map_string, 0, 1024 * 1024); fread(map_string, 1, 1024 * 1024, f); fclose(f); char *c = strstr(map_string, "/librenderdoc.so"); if(c) { // walk backwards until we hit the start of the line while(c > map_string) { c--; if(c[0] == '\n') { c++; break; } } // walk forwards across the address range (00400000-0040c000) while(isalnum(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // permissions (r-xp) while(isalpha(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // offset (0000b000) while(isalnum(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // dev while(isalnum(c[0]) || c[0] == ':') c++; // whitespace while(c[0] == ' ') c++; // inode while(isdigit(c[0])) c++; // whitespace while(c[0] == ' ') c++; // FINALLY we are at the start of the actual path char *end = strchr(c, '\n'); if(end) librenderdoc_path = string(c, end - c); } delete[] map_string; } return librenderdoc_path; } void MakeParentDirs(std::string file) { std::string dir = dirname(file); if(dir == "/" || dir.empty()) return; MakeParentDirs(dir); if(FileExists(dir)) return; mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } bool VulkanReplay::CheckVulkanLayer(VulkanLayerFlags &flags, std::vector<std::string> &myJSONs, std::vector<std::string> &otherJSONs) { // see if the user has suppressed all this checking as a "I know what I'm doing" measure if(FileExists(string(getenv("HOME")) + "/.renderdoc/ignore_vulkan_layer_issues")) { flags = VulkanLayerFlags::ThisInstallRegistered; return false; } //////////////////////////////////////////////////////////////////////////////////////// // check that there's only one layer registered, and it points to the same .so file that // we are running with in this instance of renderdoccmd // this is a hack, but the only reliable way to find the absolute path to the library. // dladdr would be fine but it returns the wrong result for symbols in the library string librenderdoc_path = GetThisLibPath(); // it's impractical to determine whether the currently running RenderDoc build is just a loose // extract of a tarball or a distribution that decided to put all the files in the same folder, // and whether or not the library is in ld's searchpath. // // Instead we just make the requirement that renderdoc.json will always contain an absolute path // to the matching librenderdoc.so, so that we can check if it points to this build or another // build etc. // // Note there are three places to register layers - /usr, /etc and /home. The first is reserved // for distribution packages, so if it conflicts or needs to be deleted for this install to run, // we can't do that and have to just prompt the user. /etc we can mess with since that's for // non-distribution packages, but it will need root permissions. bool exist[COUNT]; bool match[COUNT]; int numExist = 0; int numMatch = 0; for(int i = 0; i < COUNT; i++) { exist[i] = FileExists(layerRegistrationPath[i]); match[i] = (GetSOFromJSON(layerRegistrationPath[i]) == librenderdoc_path); if(exist[i]) numExist++; if(match[i]) numMatch++; } flags = VulkanLayerFlags::CouldElevate | VulkanLayerFlags::UpdateAllowed; if(numMatch >= 1) flags |= VulkanLayerFlags::ThisInstallRegistered; // if we only have one registration, check that it points to us. If so, we're good if(numExist == 1 && numMatch == 1) return false; if(exist[USR] && !match[USR]) otherJSONs.push_back(layerRegistrationPath[USR]); if(exist[ETC] && !match[ETC]) otherJSONs.push_back(layerRegistrationPath[ETC]); if(exist[HOME] && !match[HOME]) otherJSONs.push_back(layerRegistrationPath[HOME]); if(!otherJSONs.empty()) flags |= VulkanLayerFlags::OtherInstallsRegistered; if(exist[USR] && match[USR]) { // just need to unregister others } else { myJSONs.push_back(layerRegistrationPath[ETC]); myJSONs.push_back(layerRegistrationPath[HOME]); } if(exist[USR] && !match[USR]) { flags = VulkanLayerFlags::Unfixable | VulkanLayerFlags::OtherInstallsRegistered; otherJSONs.clear(); otherJSONs.push_back(layerRegistrationPath[USR]); } return true; } void VulkanReplay::InstallVulkanLayer(bool systemLevel) { // if we want to install to the system and there's a registration in $HOME, delete it if(systemLevel && FileExists(layerRegistrationPath[HOME])) { if(unlink(layerRegistrationPath[HOME].c_str()) < 0) { const char *const errtext = strerror(errno); RDCERR("Error removing %s: %s", layerRegistrationPath[HOME].c_str(), errtext); } } // and vice-versa if(!systemLevel && FileExists(layerRegistrationPath[ETC])) { if(unlink(layerRegistrationPath[ETC].c_str()) < 0) { const char *const errtext = strerror(errno); RDCERR("Error removing %s: %s", layerRegistrationPath[ETC].c_str(), errtext); } } int idx = systemLevel ? ETC : HOME; string path = GetSOFromJSON(layerRegistrationPath[idx]); string libPath = GetThisLibPath(); if(path != libPath) { MakeParentDirs(layerRegistrationPath[idx]); FILE *f = fopen(layerRegistrationPath[idx].c_str(), "w"); if(f) { fputs(GenerateJSON(libPath).c_str(), f); fclose(f); } else { const char *const errtext = strerror(errno); RDCERR("Error writing %s: %s", layerRegistrationPath[idx].c_str(), errtext); } } }<commit_msg>Change home vk layer path to use $XDG_DATA_HOME if present. Refs #723<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2017 Baldur Karlsson * * 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 "api/replay/renderdoc_replay.h" #include "api/replay/version.h" #include "serialise/string_utils.h" #include <errno.h> #include <sys/stat.h> #include <unistd.h> #include "vk_core.h" #include "vk_replay.h" void VulkanReplay::OutputWindow::SetWindowHandle(WindowingSystem system, void *data) { m_WindowSystem = system; #if ENABLED(RDOC_XLIB) if(system == WindowingSystem::Xlib) { XlibWindowData *xdata = (XlibWindowData *)data; xlib.display = xdata->display; xlib.window = xdata->window; return; } #endif #if ENABLED(RDOC_XCB) if(system == WindowingSystem::XCB) { XCBWindowData *xdata = (XCBWindowData *)data; xcb.connection = xdata->connection; xcb.window = xdata->window; return; } #endif RDCERR("Unrecognised/unsupported window system %d", system); } void VulkanReplay::OutputWindow::CreateSurface(VkInstance inst) { #if ENABLED(RDOC_XLIB) if(m_WindowSystem == WindowingSystem::Xlib) { VkXlibSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.dpy = xlib.display; createInfo.window = xlib.window; VkResult vkr = ObjDisp(inst)->CreateXlibSurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface); RDCASSERTEQUAL(vkr, VK_SUCCESS); return; } #endif #if ENABLED(RDOC_XCB) if(m_WindowSystem == WindowingSystem::XCB) { VkXcbSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; createInfo.connection = xcb.connection; createInfo.window = xcb.window; VkResult vkr = ObjDisp(inst)->CreateXcbSurfaceKHR(Unwrap(inst), &createInfo, NULL, &surface); RDCASSERTEQUAL(vkr, VK_SUCCESS); return; } #endif RDCERR("Unrecognised/unsupported window system %d", m_WindowSystem); } void VulkanReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h) { if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end()) return; OutputWindow &outw = m_OutputWindows[id]; #if ENABLED(RDOC_XLIB) if(outw.m_WindowSystem == WindowingSystem::Xlib) { XWindowAttributes attr = {}; XGetWindowAttributes(outw.xlib.display, outw.xlib.window, &attr); w = (int32_t)attr.width; h = (int32_t)attr.height; return; } #endif #if ENABLED(RDOC_XCB) if(outw.m_WindowSystem == WindowingSystem::XCB) { xcb_get_geometry_cookie_t geomCookie = xcb_get_geometry(outw.xcb.connection, outw.xcb.window); // window is a xcb_drawable_t xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(outw.xcb.connection, geomCookie, NULL); w = (int32_t)geom->width; h = (int32_t)geom->height; free(geom); return; } #endif RDCERR("Unrecognised/unsupported window system %d", outw.m_WindowSystem); } const char *VulkanLibraryName = "libvulkan.so.1"; // embedded data file extern unsigned char driver_vulkan_renderdoc_json[]; extern int driver_vulkan_renderdoc_json_len; static std::string GenerateJSON(const std::string &sopath) { char *txt = (char *)driver_vulkan_renderdoc_json; int len = driver_vulkan_renderdoc_json_len; string json = string(txt, txt + len); const char dllPathString[] = ".\\\\renderdoc.dll"; size_t idx = json.find(dllPathString); json = json.substr(0, idx) + sopath + json.substr(idx + sizeof(dllPathString) - 1); const char majorString[] = "[MAJOR]"; idx = json.find(majorString); while(idx != string::npos) { json = json.substr(0, idx) + STRINGIZE(RENDERDOC_VERSION_MAJOR) + json.substr(idx + sizeof(majorString) - 1); idx = json.find(majorString); } const char minorString[] = "[MINOR]"; idx = json.find(minorString); while(idx != string::npos) { json = json.substr(0, idx) + STRINGIZE(RENDERDOC_VERSION_MINOR) + json.substr(idx + sizeof(minorString) - 1); idx = json.find(minorString); } return json; } static bool FileExists(const std::string &path) { return access(path.c_str(), F_OK) == 0; } static std::string GetSOFromJSON(const std::string &json) { char *json_string = new char[1024]; memset(json_string, 0, 1024); FILE *f = fopen(json.c_str(), "r"); if(f) { fread(json_string, 1, 1024, f); fclose(f); } string ret = ""; // The line is: // "library_path": "/foo/bar/librenderdoc.so", char *c = strstr(json_string, "library_path"); if(c) { c += sizeof("library_path\": \"") - 1; char *quote = strchr(c, '"'); if(quote) { *quote = 0; ret = c; } } delete[] json_string; return ret; } enum class LayerPath : int { usr, First = usr, etc, home, Count, }; ITERABLE_OPERATORS(LayerPath); string LayerRegistrationPath(LayerPath path) { switch(path) { case LayerPath::usr: return "/usr/share/vulkan/implicit_layer.d/renderdoc_capture.json"; case LayerPath::etc: return "/etc/vulkan/implicit_layer.d/renderdoc_capture.json"; case LayerPath::home: { const char *xdg = getenv("XDG_DATA_HOME"); if(xdg && FileIO::exists(xdg)) return string(xdg) + "/vulkan/implicit_layer.d/renderdoc_capture.json"; return string(getenv("HOME")) + "/.local/share/vulkan/implicit_layer.d/renderdoc_capture.json"; } default: break; } return ""; } string GetThisLibPath() { string librenderdoc_path; FILE *f = fopen("/proc/self/maps", "r"); if(f) { // read the whole thing in one go. There's no need to try and be tight with // this allocation, so just make sure we can read everything. char *map_string = new char[1024 * 1024]; memset(map_string, 0, 1024 * 1024); fread(map_string, 1, 1024 * 1024, f); fclose(f); char *c = strstr(map_string, "/librenderdoc.so"); if(c) { // walk backwards until we hit the start of the line while(c > map_string) { c--; if(c[0] == '\n') { c++; break; } } // walk forwards across the address range (00400000-0040c000) while(isalnum(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // permissions (r-xp) while(isalpha(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // offset (0000b000) while(isalnum(c[0]) || c[0] == '-') c++; // whitespace while(c[0] == ' ') c++; // dev while(isalnum(c[0]) || c[0] == ':') c++; // whitespace while(c[0] == ' ') c++; // inode while(isdigit(c[0])) c++; // whitespace while(c[0] == ' ') c++; // FINALLY we are at the start of the actual path char *end = strchr(c, '\n'); if(end) librenderdoc_path = string(c, end - c); } delete[] map_string; } return librenderdoc_path; } void MakeParentDirs(std::string file) { std::string dir = dirname(file); if(dir == "/" || dir.empty()) return; MakeParentDirs(dir); if(FileExists(dir)) return; mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } bool VulkanReplay::CheckVulkanLayer(VulkanLayerFlags &flags, std::vector<std::string> &myJSONs, std::vector<std::string> &otherJSONs) { // see if the user has suppressed all this checking as a "I know what I'm doing" measure if(FileExists(string(getenv("HOME")) + "/.renderdoc/ignore_vulkan_layer_issues")) { flags = VulkanLayerFlags::ThisInstallRegistered; return false; } //////////////////////////////////////////////////////////////////////////////////////// // check that there's only one layer registered, and it points to the same .so file that // we are running with in this instance of renderdoccmd // this is a hack, but the only reliable way to find the absolute path to the library. // dladdr would be fine but it returns the wrong result for symbols in the library string librenderdoc_path = GetThisLibPath(); // it's impractical to determine whether the currently running RenderDoc build is just a loose // extract of a tarball or a distribution that decided to put all the files in the same folder, // and whether or not the library is in ld's searchpath. // // Instead we just make the requirement that renderdoc.json will always contain an absolute path // to the matching librenderdoc.so, so that we can check if it points to this build or another // build etc. // // Note there are three places to register layers - /usr, /etc and /home. The first is reserved // for distribution packages, so if it conflicts or needs to be deleted for this install to run, // we can't do that and have to just prompt the user. /etc we can mess with since that's for // non-distribution packages, but it will need root permissions. bool exist[arraydim<LayerPath>()]; bool match[arraydim<LayerPath>()]; int numExist = 0; int numMatch = 0; for(LayerPath i : values<LayerPath>()) { exist[(int)i] = FileExists(LayerRegistrationPath(i)); match[(int)i] = (GetSOFromJSON(LayerRegistrationPath(i)) == librenderdoc_path); if(exist[(int)i]) numExist++; if(match[(int)i]) numMatch++; } flags = VulkanLayerFlags::CouldElevate | VulkanLayerFlags::UpdateAllowed; if(numMatch >= 1) flags |= VulkanLayerFlags::ThisInstallRegistered; // if we only have one registration, check that it points to us. If so, we're good if(numExist == 1 && numMatch == 1) return false; if(exist[(int)LayerPath::usr] && !match[(int)LayerPath::usr]) otherJSONs.push_back(LayerRegistrationPath(LayerPath::usr)); if(exist[(int)LayerPath::etc] && !match[(int)LayerPath::etc]) otherJSONs.push_back(LayerRegistrationPath(LayerPath::etc)); if(exist[(int)LayerPath::home] && !match[(int)LayerPath::home]) otherJSONs.push_back(LayerRegistrationPath(LayerPath::home)); if(!otherJSONs.empty()) flags |= VulkanLayerFlags::OtherInstallsRegistered; if(exist[(int)LayerPath::usr] && match[(int)LayerPath::usr]) { // just need to unregister others } else { myJSONs.push_back(LayerRegistrationPath(LayerPath::etc)); myJSONs.push_back(LayerRegistrationPath(LayerPath::home)); } if(exist[(int)LayerPath::usr] && !match[(int)LayerPath::usr]) { flags = VulkanLayerFlags::Unfixable | VulkanLayerFlags::OtherInstallsRegistered; otherJSONs.clear(); otherJSONs.push_back(LayerRegistrationPath(LayerPath::usr)); } return true; } void VulkanReplay::InstallVulkanLayer(bool systemLevel) { std::string homePath = LayerRegistrationPath(LayerPath::home); // if we want to install to the system and there's a registration in $HOME, delete it if(systemLevel && FileExists(homePath)) { if(unlink(homePath.c_str()) < 0) { const char *const errtext = strerror(errno); RDCERR("Error removing %s: %s", homePath.c_str(), errtext); } } std::string etcPath = LayerRegistrationPath(LayerPath::etc); // and vice-versa if(!systemLevel && FileExists(etcPath)) { if(unlink(etcPath.c_str()) < 0) { const char *const errtext = strerror(errno); RDCERR("Error removing %s: %s", etcPath.c_str(), errtext); } } LayerPath idx = systemLevel ? LayerPath::etc : LayerPath::home; string jsonPath = LayerRegistrationPath(idx); string path = GetSOFromJSON(jsonPath); string libPath = GetThisLibPath(); if(path != libPath) { MakeParentDirs(jsonPath); FILE *f = fopen(jsonPath.c_str(), "w"); if(f) { fputs(GenerateJSON(libPath).c_str(), f); fclose(f); } else { const char *const errtext = strerror(errno); RDCERR("Error writing %s: %s", jsonPath.c_str(), errtext); } } }<|endoftext|>
<commit_before>#include "core/global.h" #include "core/RoleFactory.h" #include "DBEngineFactory.h" #include "IDatabaseEngine.h" #include <fstream> ConfigVariable<channel_t> control_channel("control", 0); ConfigVariable<unsigned int> id_start("generate/min", 1000); ConfigVariable<unsigned int> id_end("generate/max", 2000); ConfigVariable<std::string> engine_type("engine/type", "filesystem"); LogCategory db_log("db", "Database"); class DatabaseServer : public Role { private: IDatabaseEngine *m_db_engine; public: DatabaseServer(RoleConfig roleconfig) : Role(roleconfig), m_db_engine(DBEngineFactory::singleton.instantiate(engine_type.get_rval(roleconfig), roleconfig["engine"], id_start.get_rval(roleconfig))) { if(!m_db_engine) { db_log.fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl; exit(1); } subscribe_channel(control_channel.get_rval(m_roleconfig)); } virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msg_type = dgi.read_uint16(); switch(msg_type) { case DBSERVER_CREATE_STORED_OBJECT: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_CREATE_STORED_OBJECT_RESP); resp.add_uint32(context); DCClass *dcc = gDCF->get_class(dgi.read_uint16()); if(!dcc) { db_log.error() << "Unknown dcclass" << std::endl; resp.add_uint32(0); send(resp); return; } unsigned short field_count = dgi.read_uint16(); unsigned int do_id = m_db_engine->get_next_id(); if(do_id > id_end.get_rval(m_roleconfig) || do_id == 0) { db_log.error() << "Ran out of DistributedObject ids while creating new object." << std::endl; resp.add_uint32(0); send(resp); return; } DatabaseObject dbo; dbo.do_id = do_id; dbo.dc_id = dcc->get_number(); db_log.spam() << "Unpacking fields..." << std::endl; try { for(unsigned int i = 0; i < field_count; ++i) { unsigned short field_id = dgi.read_uint16(); DCField *field = dcc->get_field_by_index(field_id); if(field) { if(field->is_db()) { dgi.unpack_field(field, dbo.fields[field]); } else { dgi.unpack_field(field, std::string()); } } } } catch(std::exception &e) { db_log.error() << "Error while unpacking fields, msg may be truncated. e.what(): " << e.what() << std::endl; resp.add_uint32(0); send(resp); return; } db_log.spam() << "Checking all required fields exist..." << std::endl; for(unsigned int i = 0; i < dcc->get_num_inherited_fields(); ++i) { DCField *field = dcc->get_inherited_field(i); if(field->is_required() && field->is_db() && !field->as_molecular_field()) { if(dbo.fields.find(field) == dbo.fields.end()) { db_log.error() << "Field " << field->get_name() << " missing when trying to create " "object of type " << dcc->get_name(); resp.add_uint32(0); send(resp); return; } } } db_log.spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl; if(m_db_engine->create_object(dbo)) { resp.add_uint32(do_id); } else { resp.add_uint32(0); } send(resp); } break; case DBSERVER_SELECT_STORED_OBJECT_ALL: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_SELECT_STORED_OBJECT_ALL_RESP); resp.add_uint32(context); DatabaseObject dbo; dbo.do_id = dgi.read_uint32(); if(m_db_engine->get_object(dbo)) { resp.add_uint8(1); resp.add_uint16(dbo.dc_id); resp.add_uint16(dbo.fields.size()); for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it) { resp.add_uint16(it->first->get_number()); resp.add_data(it->second); } } else { resp.add_uint8(0); } send(resp); } break; case DBSERVER_DELETE_STORED_OBJECT: { if(dgi.read_uint32() == 'Die!') { unsigned int do_id = dgi.read_uint32(); m_db_engine->delete_object(do_id); } else { db_log.warning() << "Wrong delete verify code." << std::endl; } } break; /*case DBSERVER_DELETE_STORED_OBJECT: { unsigned int verify = dgi.read_uint32(); unsigned int do_id = dgi.read_uint32(); m_log->spam() << "Deleting object with ID... " << do_id << std::endl; if(verify == 0x44696521) { m_db_engine->delete_object(do_id); m_freed_ids.push(do_id); m_log->spam() << "... delete successful." << std::endl; } else { m_log->spam() << "... delete failed." << std::endl; } }*/ break; default: db_log.error() << "Recieved unknown MsgType: " << msg_type << std::endl; }; } }; RoleFactoryItem<DatabaseServer> dbserver_fact("database"); <commit_msg>DBServer: Fixes compilation on GCC<commit_after>#include "core/global.h" #include "core/RoleFactory.h" #include "DBEngineFactory.h" #include "IDatabaseEngine.h" #include <fstream> ConfigVariable<channel_t> control_channel("control", 0); ConfigVariable<unsigned int> id_start("generate/min", 1000); ConfigVariable<unsigned int> id_end("generate/max", 2000); ConfigVariable<std::string> engine_type("engine/type", "filesystem"); LogCategory db_log("db", "Database"); class DatabaseServer : public Role { private: IDatabaseEngine *m_db_engine; public: DatabaseServer(RoleConfig roleconfig) : Role(roleconfig), m_db_engine(DBEngineFactory::singleton.instantiate(engine_type.get_rval(roleconfig), roleconfig["engine"], id_start.get_rval(roleconfig))) { if(!m_db_engine) { db_log.fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl; exit(1); } subscribe_channel(control_channel.get_rval(m_roleconfig)); } virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msg_type = dgi.read_uint16(); switch(msg_type) { case DBSERVER_CREATE_STORED_OBJECT: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_CREATE_STORED_OBJECT_RESP); resp.add_uint32(context); DCClass *dcc = gDCF->get_class(dgi.read_uint16()); if(!dcc) { db_log.error() << "Unknown dcclass" << std::endl; resp.add_uint32(0); send(resp); return; } unsigned short field_count = dgi.read_uint16(); unsigned int do_id = m_db_engine->get_next_id(); if(do_id > id_end.get_rval(m_roleconfig) || do_id == 0) { db_log.error() << "Ran out of DistributedObject ids while creating new object." << std::endl; resp.add_uint32(0); send(resp); return; } DatabaseObject dbo; dbo.do_id = do_id; dbo.dc_id = dcc->get_number(); db_log.spam() << "Unpacking fields..." << std::endl; try { for(unsigned int i = 0; i < field_count; ++i) { unsigned short field_id = dgi.read_uint16(); DCField *field = dcc->get_field_by_index(field_id); if(field) { if(field->is_db()) { dgi.unpack_field(field, dbo.fields[field]); } else { std::string tmp; dgi.unpack_field(field, tmp); } } } } catch(std::exception &e) { db_log.error() << "Error while unpacking fields, msg may be truncated. e.what(): " << e.what() << std::endl; resp.add_uint32(0); send(resp); return; } db_log.spam() << "Checking all required fields exist..." << std::endl; for(unsigned int i = 0; i < dcc->get_num_inherited_fields(); ++i) { DCField *field = dcc->get_inherited_field(i); if(field->is_required() && field->is_db() && !field->as_molecular_field()) { if(dbo.fields.find(field) == dbo.fields.end()) { db_log.error() << "Field " << field->get_name() << " missing when trying to create " "object of type " << dcc->get_name(); resp.add_uint32(0); send(resp); return; } } } db_log.spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl; if(m_db_engine->create_object(dbo)) { resp.add_uint32(do_id); } else { resp.add_uint32(0); } send(resp); } break; case DBSERVER_SELECT_STORED_OBJECT_ALL: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, control_channel.get_rval(m_roleconfig), DBSERVER_SELECT_STORED_OBJECT_ALL_RESP); resp.add_uint32(context); DatabaseObject dbo; dbo.do_id = dgi.read_uint32(); if(m_db_engine->get_object(dbo)) { resp.add_uint8(1); resp.add_uint16(dbo.dc_id); resp.add_uint16(dbo.fields.size()); for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it) { resp.add_uint16(it->first->get_number()); resp.add_data(it->second); } } else { resp.add_uint8(0); } send(resp); } break; case DBSERVER_DELETE_STORED_OBJECT: { if(dgi.read_uint32() == 'Die!') { unsigned int do_id = dgi.read_uint32(); m_db_engine->delete_object(do_id); } else { db_log.warning() << "Wrong delete verify code." << std::endl; } } break; /*case DBSERVER_DELETE_STORED_OBJECT: { unsigned int verify = dgi.read_uint32(); unsigned int do_id = dgi.read_uint32(); m_log->spam() << "Deleting object with ID... " << do_id << std::endl; if(verify == 0x44696521) { m_db_engine->delete_object(do_id); m_freed_ids.push(do_id); m_log->spam() << "... delete successful." << std::endl; } else { m_log->spam() << "... delete failed." << std::endl; } }*/ break; default: db_log.error() << "Recieved unknown MsgType: " << msg_type << std::endl; }; } }; RoleFactoryItem<DatabaseServer> dbserver_fact("database"); <|endoftext|>
<commit_before>#include <stan/agrad/rev/functions/asin.hpp> #include <test/unit/agrad/util.hpp> #include <gtest/gtest.h> #include <stan/math/constants.hpp> #include <stan/agrad/rev/numeric_limits.hpp> TEST(AgradRev,asin_var) { AVAR a = 0.68; AVAR f = asin(a); EXPECT_FLOAT_EQ(asin(0.68), f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (0.68 * 0.68)), g[0]); } TEST(AgradRev,asin_1) { AVAR a = 1; AVAR f = asin(a); EXPECT_FLOAT_EQ((1.57079632679),f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (1*1)),g[0]); } TEST(AgradRev,asin_neg_1) { AVAR a = -1; AVAR f = asin(a); EXPECT_FLOAT_EQ((-1.57079632679),f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (-1*-1)),g[0]); } TEST(AgradRev,asin_out_of_bounds) { AVAR a = 1.0 + stan::math::EPSILON; EXPECT_TRUE(std::isnan(asin(a))); a = -1.0 - stan::math::EPSILON; EXPECT_TRUE(std::isnan(asin(a))); } <commit_msg>added NaN test for asin<commit_after>#include <stan/agrad/rev/functions/asin.hpp> #include <test/unit/agrad/util.hpp> #include <gtest/gtest.h> #include <stan/math/constants.hpp> #include <stan/agrad/rev/numeric_limits.hpp> TEST(AgradRev,asin_var) { AVAR a = 0.68; AVAR f = asin(a); EXPECT_FLOAT_EQ(asin(0.68), f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (0.68 * 0.68)), g[0]); } TEST(AgradRev,asin_1) { AVAR a = 1; AVAR f = asin(a); EXPECT_FLOAT_EQ((1.57079632679),f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (1*1)),g[0]); } TEST(AgradRev,asin_neg_1) { AVAR a = -1; AVAR f = asin(a); EXPECT_FLOAT_EQ((-1.57079632679),f.val()); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_FLOAT_EQ(1.0/sqrt(1.0 - (-1*-1)),g[0]); } TEST(AgradRev,asin_out_of_bounds) { AVAR a = 1.0 + stan::math::EPSILON; EXPECT_TRUE(std::isnan(asin(a))); a = -1.0 - stan::math::EPSILON; EXPECT_TRUE(std::isnan(asin(a))); } TEST(AgradRev,asin_nan) { AVAR a = std::numeric_limits<double>::quiet_NaN(); AVAR f = stan::agrad::asin(a); AVEC x = createAVEC(a); VEC g; f.grad(x,g); EXPECT_TRUE(boost::math::isnan(f.val())); ASSERT_EQ(1U,g.size()); EXPECT_TRUE(boost::math::isnan(g[0])); } <|endoftext|>
<commit_before>/* Copyright (c) 2011 Steve Revill and Shane Woolcock 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. */ #ifdef _WIN32 #include <windows.h> #include <Shellapi.h> #include <iostream> #endif #include <string.h> #include <time.h> extern gxtkAudio *bb_audio_device; extern gxtkGraphics *bb_graphics_device; float diddy_mouseWheel = 0.0f; #ifdef _glfw3_h_ void diddy_mouseScroll(GLFWwindow *window, double xoffset, double yoffset) { diddy_mouseWheel = yoffset; } #endif float diddy_mouseZ() { float ret = 0.0f; #ifdef _glfw3_h_ ret = diddy_mouseWheel; diddy_mouseWheel = 0; #else ret = glfwGetMouseWheel() - diddy_mouseWheel; diddy_mouseWheel = glfwGetMouseWheel(); #endif return ret; } class diddy { public: // Returns an empty string if dialog is cancelled static String openfilename() { #ifdef _WIN32 const char *filter = "All Files (*.*)\0*.*\0"; HWND owner = NULL; OPENFILENAME ofn; char fileName[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = owner; ofn.lpstrFilter = filter; ofn.lpstrFile = fileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = ""; String fileNameStr; if ( GetOpenFileName(&ofn) ) fileNameStr = fileName; return fileNameStr; #endif #ifdef linux return ""; #endif } static String savefilename() { #ifdef _WIN32 const char *filter = "All Files (*.*)\0*.*\0"; HWND owner = NULL; OPENFILENAME ofn; char fileName[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = owner; ofn.lpstrFilter = filter; ofn.lpstrFile = fileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = ""; String fileNameStr; if ( GetSaveFileNameA(&ofn) ) fileNameStr = fileName; return fileNameStr; #endif #ifdef linux return ""; #endif } static float mouseZ() { return diddy_mouseZ(); } static void mouseZInit() { #ifdef _glfw3_h_ glfwSetScrollCallback(BBGlfwGame::GlfwGame()->GetGLFWwindow(), diddy_mouseScroll); #endif } // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void setGraphics(int w, int h) { #ifdef _glfw3_h_ GLFWwindow *window = BBGlfwGame::GlfwGame()->GetGLFWwindow(); glfwSetWindowSize(window, w, h); GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *desktopMode = glfwGetVideoMode(monitor); glfwSetWindowPos(window, (desktopMode->width-w)/2,(desktopMode->height-h)/2 ); #else glfwSetWindowSize(w, h); GLFWvidmode desktopMode; glfwGetDesktopMode( &desktopMode ); glfwSetWindowPos( (desktopMode.Width-w)/2,(desktopMode.Height-h)/2 ); #endif } static void setMouse(int x, int y) { #ifdef _glfw3_h_ glfwSetCursorPos(BBGlfwGame::GlfwGame()->GetGLFWwindow(), x, y); #else glfwSetMousePos(x, y); #endif } static void showKeyboard() { } static void launchBrowser(String address, String windowName) { #ifdef _WIN32 LPCSTR addressStr = address.ToCString<char>(); ShellExecute(HWND_DESKTOP, "open", addressStr, NULL, NULL, SW_SHOWNORMAL); #endif } static void launchEmail(String email, String subject, String text) { #ifdef _WIN32 String tmp = "mailto:"; tmp+=email; tmp+="&subject="; tmp+=subject; tmp+="&body="; tmp+=text; LPCSTR addressStr = tmp.ToCString<char>(); ShellExecute(HWND_DESKTOP, "open", addressStr, NULL, NULL, SW_SHOWNORMAL); #endif } static void startVibrate(int millisecs) { } static void stopVibrate() { } static void startGps() { } static String getLatitude() { return ""; } static String getLongitude() { return ""; } static void showAlertDialog(String title, String message) { } static String getInputString() { return ""; } static int seekMusic(int timeMillis) { gxtkChannel *chan = &(bb_audio_device->channels[32]); if(chan && chan->state==1) { alSourcef(chan->source, AL_SEC_OFFSET, (float)(timeMillis / 1000.0)); } // TODO: check it worked return 1; } }; <commit_msg>Fixed glfw native code to compile with Mac and Linux (in theory).<commit_after>/* Copyright (c) 2011 Steve Revill and Shane Woolcock 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. */ #ifdef _WIN32 #include <windows.h> #include <Shellapi.h> #include <iostream> #include <string.h> #endif #ifdef __linux__ #include <string.h> #endif #ifdef __APPLE__ #include <math.h> #endif #include <time.h> extern gxtkAudio *bb_audio_device; extern gxtkGraphics *bb_graphics_device; float diddy_mouseWheel = 0.0f; #ifdef _glfw3_h_ void diddy_mouseScroll(GLFWwindow *window, double xoffset, double yoffset) { diddy_mouseWheel = yoffset; } #endif float diddy_mouseZ() { float ret = 0.0f; #ifdef _glfw3_h_ ret = diddy_mouseWheel; diddy_mouseWheel = 0; #else ret = glfwGetMouseWheel() - diddy_mouseWheel; diddy_mouseWheel = glfwGetMouseWheel(); #endif return ret; } class diddy { public: #ifdef _WIN32 // Returns an empty string if dialog is cancelled static String openfilename() { #ifdef _WIN32 const char *filter = "All Files (*.*)\0*.*\0"; HWND owner = NULL; OPENFILENAME ofn; char fileName[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = owner; ofn.lpstrFilter = filter; ofn.lpstrFile = fileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = ""; String fileNameStr; if ( GetOpenFileName(&ofn) ) fileNameStr = fileName; return fileNameStr; #else return ""; #endif } static String savefilename() { #ifdef _WIN32 const char *filter = "All Files (*.*)\0*.*\0"; HWND owner = NULL; OPENFILENAME ofn; char fileName[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = owner; ofn.lpstrFilter = filter; ofn.lpstrFile = fileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = ""; String fileNameStr; if ( GetSaveFileNameA(&ofn) ) fileNameStr = fileName; return fileNameStr; #else return ""; #endif } #endif static float mouseZ() { return diddy_mouseZ(); } static void mouseZInit() { #ifdef _glfw3_h_ glfwSetScrollCallback(BBGlfwGame::GlfwGame()->GetGLFWwindow(), diddy_mouseScroll); #endif } // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void setGraphics(int w, int h) { #ifdef _glfw3_h_ GLFWwindow *window = BBGlfwGame::GlfwGame()->GetGLFWwindow(); glfwSetWindowSize(window, w, h); GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *desktopMode = glfwGetVideoMode(monitor); glfwSetWindowPos(window, (desktopMode->width-w)/2,(desktopMode->height-h)/2 ); #else glfwSetWindowSize(w, h); GLFWvidmode desktopMode; glfwGetDesktopMode( &desktopMode ); glfwSetWindowPos( (desktopMode.Width-w)/2,(desktopMode.Height-h)/2 ); #endif } static void setMouse(int x, int y) { #ifdef _glfw3_h_ glfwSetCursorPos(BBGlfwGame::GlfwGame()->GetGLFWwindow(), x, y); #else glfwSetMousePos(x, y); #endif } static void showKeyboard() { } static void launchBrowser(String address, String windowName) { #ifdef _WIN32 LPCSTR addressStr = address.ToCString<char>(); ShellExecute(HWND_DESKTOP, "open", addressStr, NULL, NULL, SW_SHOWNORMAL); #endif } static void launchEmail(String email, String subject, String text) { #ifdef _WIN32 String tmp = "mailto:"; tmp+=email; tmp+="&subject="; tmp+=subject; tmp+="&body="; tmp+=text; LPCSTR addressStr = tmp.ToCString<char>(); ShellExecute(HWND_DESKTOP, "open", addressStr, NULL, NULL, SW_SHOWNORMAL); #endif } static void startVibrate(int millisecs) { } static void stopVibrate() { } static void startGps() { } static String getLatitude() { return ""; } static String getLongitude() { return ""; } static void showAlertDialog(String title, String message) { } static String getInputString() { return ""; } static int seekMusic(int timeMillis) { gxtkChannel *chan = &(bb_audio_device->channels[32]); if(chan && chan->state==1) { alSourcef(chan->source, AL_SEC_OFFSET, (float)(timeMillis / 1000.0)); } // TODO: check it worked return 1; } }; <|endoftext|>
<commit_before>#include "../ChTestConfig.h" #if defined(__APPLE__) #include <libkern/OSAtomic.h> #endif #include <iostream> using namespace std; using namespace chrono; static volatile int first = 100000; int main() { ChTimer<double> OSX, GNU; #if defined(__APPLE__) OSX.start(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 1000000; i++) { static volatile int32_t id = first; OSAtomicIncrement32Barrier(&id); } } OSX.stop(); double result_OSX = OSX(); cout << "OSAtomicIncrement32Barrier: " << result_OSX << " " << result_OSX / 100000000.0 << endl; #endif #if defined(__GNUC__) GNU.start(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 1000000; i++) { static volatile int id = first; __sync_add_and_fetch(&id, 1); } } GNU.stop(); double result_GNU = GNU(); cout << "__sync_add_and_fetch: " << result_GNU << " " << result_GNU / 100000000.0 << endl; #endif return 0; } <commit_msg>Updated benchmark to also run the GetUniqueIntID function<commit_after>#include "../ChTestConfig.h" #include "physics/ChGlobal.h" #if defined(__APPLE__) #include <libkern/OSAtomic.h> #endif #include <iostream> using namespace std; using namespace chrono; static volatile int first = 100000; int main() { ChTimer<double> OSX, GNU, CHRONO; #if defined(__APPLE__) OSX.start(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 1000000; i++) { static volatile int32_t id = first; OSAtomicIncrement32Barrier(&id); } } OSX.stop(); double result_OSX = OSX(); cout << "OSAtomicIncrement32Barrier: " << result_OSX << " " << result_OSX / 100000000.0 << endl; #endif #if defined(__GNUC__) GNU.start(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 1000000; i++) { static volatile int id = first; __sync_add_and_fetch(&id, 1); } } GNU.stop(); double result_GNU = GNU(); cout << "__sync_add_and_fetch: " << result_GNU << " " << result_GNU / 100000000.0 << endl; #endif CHRONO.start(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 1000000; i++) { GetUniqueIntID(); } } CHRONO.stop(); double result_CHRONO = CHRONO(); cout << "Chrono GetUniqueIntID: " << result_CHRONO << " " << result_CHRONO / 100000000.0 << endl; return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2013 the Urho3D project. // // 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 "Context.h" #include "Engine.h" #include "FileSystem.h" #include "Log.h" #include "Main.h" #include "ProcessUtils.h" #include "ResourceCache.h" #include "ResourceEvents.h" #include "ScriptFile.h" #include <exception> #include "DebugNew.h" using namespace Urho3D; class Application : public Object { OBJECT(Application); public: Application(Context* context); int Run(const String& scriptFileName); private: void ErrorExit(); void HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData); void HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData); void HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData); int exitCode_; }; int Run() { try { // Check for script file name const Vector<String>& arguments = GetArguments(); String scriptFileName; for (unsigned i = 0; i < arguments.Size(); ++i) { if (arguments[i][0] != '-') { scriptFileName = GetInternalPath(arguments[i]); break; } } #if defined(ANDROID) || defined(IOS) // Can not pass script name on mobile devices, so choose a hardcoded default scriptFileName = "Scripts/NinjaSnowWar.as"; #endif // Show usage if not found if (scriptFileName.Empty()) { ErrorDialog("Urho3D", "Usage: Urho3D <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x<res> Horizontal resolution\n" "-y<res> Vertical resolution\n" "-m<level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b<length> Sound buffer length in milliseconds\n" "-r<freq> Sound mixing frequency in Hz\n" "-headless Headless mode. No application window will be created\n" "-log<level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-sm2 Force SM2.0 rendering\n" #endif ); return EXIT_FAILURE; } // Create the execution context and the application object. The application object is needed to subscribe to events // which allow to live-reload the script. SharedPtr<Context> context(new Context()); SharedPtr<Application> application(new Application(context)); return application->Run(scriptFileName); } catch (std::bad_alloc&) { ErrorDialog("Urho3D", "An out-of-memory error occurred. The application will now exit."); return EXIT_FAILURE; } } OBJECTTYPESTATIC(Application); Application::Application(Context* context) : Object(context), exitCode_(EXIT_SUCCESS) { } int Application::Run(const String& scriptFileName) { SharedPtr<Engine> engine(new Engine(context_)); if (engine->Initialize("Urho3D", "Urho3D.log", GetArguments())) { // Hold a shared pointer to the script file to make sure it is not unloaded during runtime engine->InitializeScripting(); SharedPtr<ScriptFile> scriptFile(context_->GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName)); // If script loading is successful, execute engine loop if (scriptFile && scriptFile->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile, E_RELOADSTARTED, HANDLER(Application, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile, E_RELOADFINISHED, HANDLER(Application, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile, E_RELOADFAILED, HANDLER(Application, HandleScriptReloadFailed)); while (!engine->IsExiting()) engine->RunFrame(); if (scriptFile->GetFunction("void Stop()")) scriptFile->Execute("void Stop()"); return exitCode_; } } ErrorExit(); return exitCode_; } void Application::ErrorExit() { Engine* engine = context_->GetSubsystem<Engine>(); engine->Exit(); // Close the rendering window // Only for WIN32, otherwise the last message would be double posted on Mac OS X and Linux platforms #ifdef WIN32 Log* log = context_->GetSubsystem<Log>(); // May be null if ENABLE_LOGGING is not defined during built ErrorDialog("Urho3D", log ? log->GetLastMessage() : "Application has been terminated due to unexpected error."); #endif exitCode_ = EXIT_FAILURE; } void Application::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData) { ScriptFile* scriptFile = static_cast<ScriptFile*>(GetEventSender()); if (scriptFile->GetFunction("void Stop()")) scriptFile->Execute("void Stop()"); } void Application::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData) { ScriptFile* scriptFile = static_cast<ScriptFile*>(GetEventSender()); // Restart the script application after reload if (!scriptFile->Execute("void Start()")) ErrorExit(); } void Application::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData) { ErrorExit(); } DEFINE_MAIN(Run()); <commit_msg>Moved checking for script file name & printing usage inside Application::Run(). Fixed some command line options (-prepass and -deferred) not being printed.<commit_after>// // Copyright (c) 2008-2013 the Urho3D project. // // 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 "Context.h" #include "Engine.h" #include "FileSystem.h" #include "Log.h" #include "Main.h" #include "ProcessUtils.h" #include "ResourceCache.h" #include "ResourceEvents.h" #include "ScriptFile.h" #include <exception> #include "DebugNew.h" using namespace Urho3D; class Application : public Object { OBJECT(Application); public: Application(Context* context); int Run(); private: void ErrorExit(); void HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData); void HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData); void HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData); int exitCode_; }; int Run() { try { // Create the execution context and the application object. The application object is needed to subscribe to events // which allow to live-reload the script. SharedPtr<Context> context(new Context()); SharedPtr<Application> application(new Application(context)); return application->Run(); } catch (std::bad_alloc&) { ErrorDialog("Urho3D", "An out-of-memory error occurred. The application will now exit."); return EXIT_FAILURE; } } OBJECTTYPESTATIC(Application); Application::Application(Context* context) : Object(context), exitCode_(EXIT_SUCCESS) { } int Application::Run() { // Check for script file name const Vector<String>& arguments = GetArguments(); String scriptFileName; for (unsigned i = 0; i < arguments.Size(); ++i) { if (arguments[i][0] != '-') { scriptFileName = GetInternalPath(arguments[i]); break; } } #if defined(ANDROID) || defined(IOS) // Can not pass script name on mobile devices, so choose a hardcoded default scriptFileName = "Scripts/NinjaSnowWar.as"; #endif // Show usage if not found if (scriptFileName.Empty()) { ErrorDialog("Urho3D", "Usage: Urho3D <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x<res> Horizontal resolution\n" "-y<res> Vertical resolution\n" "-m<level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b<length> Sound buffer length in milliseconds\n" "-r<freq> Sound mixing frequency in Hz\n" "-headless Headless mode. No application window will be created\n" "-log<level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-sm2 Force SM2.0 rendering\n" #endif ); return EXIT_FAILURE; } SharedPtr<Engine> engine(new Engine(context_)); if (engine->Initialize("Urho3D", "Urho3D.log", arguments)) { // Hold a shared pointer to the script file to make sure it is not unloaded during runtime engine->InitializeScripting(); SharedPtr<ScriptFile> scriptFile(context_->GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName)); // If script loading is successful, execute engine loop if (scriptFile && scriptFile->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile, E_RELOADSTARTED, HANDLER(Application, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile, E_RELOADFINISHED, HANDLER(Application, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile, E_RELOADFAILED, HANDLER(Application, HandleScriptReloadFailed)); while (!engine->IsExiting()) engine->RunFrame(); if (scriptFile->GetFunction("void Stop()")) scriptFile->Execute("void Stop()"); return exitCode_; } } ErrorExit(); return exitCode_; } void Application::ErrorExit() { Engine* engine = context_->GetSubsystem<Engine>(); engine->Exit(); // Close the rendering window // Only for WIN32, otherwise the last message would be double posted on Mac OS X and Linux platforms #ifdef WIN32 Log* log = context_->GetSubsystem<Log>(); // May be null if ENABLE_LOGGING is not defined during built ErrorDialog("Urho3D", log ? log->GetLastMessage() : "Application has been terminated due to unexpected error."); #endif exitCode_ = EXIT_FAILURE; } void Application::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData) { ScriptFile* scriptFile = static_cast<ScriptFile*>(GetEventSender()); if (scriptFile->GetFunction("void Stop()")) scriptFile->Execute("void Stop()"); } void Application::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData) { ScriptFile* scriptFile = static_cast<ScriptFile*>(GetEventSender()); // Restart the script application after reload if (!scriptFile->Execute("void Start()")) ErrorExit(); } void Application::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData) { ErrorExit(); } DEFINE_MAIN(Run()); <|endoftext|>
<commit_before>#include <znc/main.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <znc/Nick.h> #include <znc/Chan.h> #include <znc/IRCSock.h> #include "twitchtmi.h" #include "jload.h" TwitchTMI::~TwitchTMI() { } bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage) { OnBoot(); if(GetNetwork()) { for(CChan *ch: GetNetwork()->GetChans()) { CString chname = ch->GetName().substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(this, chname)); ch->SetTopic(CString()); } } return true; } bool TwitchTMI::OnBoot() { initCurl(); timer = new TwitchTMIUpdateTimer(this); AddTimer(timer); return true; } void TwitchTMI::OnIRCConnected() { PutIRC("CAP REQ :twitch.tv/membership"); } CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine) { if(sLine.Left(5).Equals("WHO #")) return CModule::HALT; if(sLine.Left(5).Equals("AWAY ")) return CModule::HALT; if(sLine.Left(12).Equals("TWITCHCLIENT")) return CModule::HALT; if(sLine.Left(9).Equals("JTVCLIENT")) return CModule::HALT; if(!sLine.Left(7).Equals("TOPIC #")) return CModule::CONTINUE; CString chname = sLine.substr(6); chname.Trim(); CChan *chan = GetNetwork()->FindChan(chname); std::stringstream ss; if(chan->GetTopic().Trim_n() != "") { ss << ":jtv 332 " << GetNetwork()->GetIRCNick().GetNick() << " " << chname << " :" << chan->GetTopic(); } else { ss << ":jtv 331 " << GetNetwork()->GetIRCNick().GetNick() << " " << chname << " :No topic is set"; } PutUser(ss.str()); return CModule::HALT; } CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey) { CString chname = sChannel.substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(this, chname)); return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnPrivMsg(CNick& nick, CString& sMessage) { if(nick.GetNick().Equals("jtv", true)) return CModule::HALT; return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnChanMsg(CNick& nick, CChan& channel, CString& sMessage) { if(nick.GetNick().Equals("jtv", true)) return CModule::HALT; if(sMessage == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10) { std::stringstream ss1, ss2; CString mynick = GetNetwork()->GetIRCNick().GetNickMask(); ss1 << "PRIVMSG " << channel.GetName() << " :FrankerZ"; ss2 << ":" << mynick << " PRIVMSG " << channel.GetName() << " :FrankerZ"; PutIRC(ss1.str()); GetNetwork()->GetIRCSock()->ReadLine(ss2.str()); lastFrankerZ = std::time(nullptr); } return CModule::CONTINUE; } bool TwitchTMI::OnServerCapAvailable(const CString &sCap) { if(sCap == "twitch.tv/membership") { CUtils::PrintMessage("TwitchTMI: Requesting twitch.tv/membership cap"); return true; } CUtils::PrintMessage(CString("TwitchTMI: Not requesting ") + sCap + " cap"); return false; } TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod) :CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information") ,mod(tmod) { } void TwitchTMIUpdateTimer::RunJob() { if(!mod->GetNetwork()) return; for(CChan *chan: mod->GetNetwork()->GetChans()) { CString chname = chan->GetName().substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname)); } } void TwitchTMIJob::runThread() { std::stringstream ss; ss << "https://api.twitch.tv/kraken/channels/" << channel; CString url = ss.str(); Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json"); if(root.isNull()) { return; } Json::Value &titleVal = root["status"]; if(!titleVal.isString()) titleVal = root["title"]; if(!titleVal.isString()) return; title = titleVal.asString(); } void TwitchTMIJob::runMain() { if(title.empty()) return; CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel); if(!chan) return; if(!chan->GetTopic().Equals(title, true)) { chan->SetTopic(title); chan->SetTopicOwner("jtv"); chan->SetTopicDate((unsigned long)time(nullptr)); std::stringstream ss; ss << ":jtv TOPIC #" << channel << " :" << title; mod->PutUser(ss.str()); } } template<> void TModInfo<TwitchTMI>(CModInfo &info) { info.SetWikiPage("Twitch"); info.SetHasArgs(false); } NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module") <commit_msg>Topic automatism no longer needed<commit_after>#include <znc/main.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <znc/Nick.h> #include <znc/Chan.h> #include <znc/IRCSock.h> #include "twitchtmi.h" #include "jload.h" TwitchTMI::~TwitchTMI() { } bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage) { OnBoot(); if(GetNetwork()) { for(CChan *ch: GetNetwork()->GetChans()) { ch->SetTopic(CString()); CString chname = ch->GetName().substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(this, chname)); } } return true; } bool TwitchTMI::OnBoot() { initCurl(); timer = new TwitchTMIUpdateTimer(this); AddTimer(timer); return true; } void TwitchTMI::OnIRCConnected() { PutIRC("CAP REQ :twitch.tv/membership"); } CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine) { if(sLine.Left(5).Equals("WHO #")) return CModule::HALT; if(sLine.Left(5).Equals("AWAY ")) return CModule::HALT; if(sLine.Left(12).Equals("TWITCHCLIENT")) return CModule::HALT; if(sLine.Left(9).Equals("JTVCLIENT")) return CModule::HALT; return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey) { CString chname = sChannel.substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(this, chname)); return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnPrivMsg(CNick& nick, CString& sMessage) { if(nick.GetNick().Equals("jtv", true)) return CModule::HALT; return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnChanMsg(CNick& nick, CChan& channel, CString& sMessage) { if(nick.GetNick().Equals("jtv", true)) return CModule::HALT; if(sMessage == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10) { std::stringstream ss1, ss2; CString mynick = GetNetwork()->GetIRCNick().GetNickMask(); ss1 << "PRIVMSG " << channel.GetName() << " :FrankerZ"; ss2 << ":" << mynick << " PRIVMSG " << channel.GetName() << " :FrankerZ"; PutIRC(ss1.str()); GetNetwork()->GetIRCSock()->ReadLine(ss2.str()); lastFrankerZ = std::time(nullptr); } return CModule::CONTINUE; } bool TwitchTMI::OnServerCapAvailable(const CString &sCap) { if(sCap == "twitch.tv/membership") { CUtils::PrintMessage("TwitchTMI: Requesting twitch.tv/membership cap"); return true; } CUtils::PrintMessage(CString("TwitchTMI: Not requesting ") + sCap + " cap"); return false; } TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod) :CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information") ,mod(tmod) { } void TwitchTMIUpdateTimer::RunJob() { if(!mod->GetNetwork()) return; for(CChan *chan: mod->GetNetwork()->GetChans()) { CString chname = chan->GetName().substr(1); CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname)); } } void TwitchTMIJob::runThread() { std::stringstream ss; ss << "https://api.twitch.tv/kraken/channels/" << channel; CString url = ss.str(); Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json"); if(root.isNull()) { return; } Json::Value &titleVal = root["status"]; if(!titleVal.isString()) titleVal = root["title"]; if(!titleVal.isString()) return; title = titleVal.asString(); } void TwitchTMIJob::runMain() { if(title.empty()) return; CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel); if(!chan) return; if(!chan->GetTopic().Equals(title, true)) { chan->SetTopic(title); chan->SetTopicOwner("jtv"); chan->SetTopicDate((unsigned long)time(nullptr)); std::stringstream ss; ss << ":jtv TOPIC #" << channel << " :" << title; mod->PutUser(ss.str()); } } template<> void TModInfo<TwitchTMI>(CModInfo &info) { info.SetWikiPage("Twitch"); info.SetHasArgs(false); } NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module") <|endoftext|>
<commit_before>/*** tws_strat.cpp -- TWS strategy module * * Copyright (C) 2012 Ruediger Meier * * Author: Ruediger Meier <sweet_f_a@gmx.de> * * This file is part of twstools. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 "tws_strat.h" #include "tws_query.h" #include "tws_meta.h" #include "tws_account.h" #include "twsdo.h" #include "debug.h" #include <assert.h> buy_sell_oid::buy_sell_oid() : sell_oid(0), buy_oid(0) { } Strat::Strat( TwsDL& _twsdo) : twsdo(_twsdo) { } Strat::~Strat() { } /** * Return min tick price for a given contract. */ double Strat::min_tick(const IB::Contract& c) { assert( c.conId != 0 ); assert( twsdo.con_details.find( c.conId ) != twsdo.con_details.end() ); double min_tick = twsdo.con_details[c.conId]->minTick ; assert(min_tick > 0.0); return min_tick; } /** * Return portfolio position of a given contract. */ int Strat::prtfl_pos(const IB::Contract& c) { Prtfl::const_iterator it = twsdo.account->portfolio.find(c.conId); if( it != twsdo.account->portfolio.end() ) { return it->second.position; } return 0; } /** * Place or modify buy and sell orders for a single contract. Quote should * valid bid and ask. */ void Strat::adjust_order( const IB::Contract& c, const Quote& quote, buy_sell_oid& oids ) { PlaceOrder pO; pO.contract = c; pO.order.orderType = "LMT"; pO.order.totalQuantity = pO.contract.secType == "CASH" ? 25000 : 1; const char *symbol = pO.contract.symbol.c_str(); double quote_dist = 1 * min_tick(c); const int max_pos = 1; int cur_pos = prtfl_pos(c); double lmt_buy = quote.val[IB::BID] - quote_dist; double lmt_sell = quote.val[IB::ASK] + quote_dist; if( twsdo.p_orders.find(oids.buy_oid) == twsdo.p_orders.end() ) { if( cur_pos < max_pos ) { /* new buy order */ DEBUG_PRINTF( "strat, new buy order %s", symbol ); oids.buy_oid = twsdo.fetch_inc_order_id(); pO.orderId = oids.buy_oid; pO.order.action = "BUY"; pO.order.lmtPrice = lmt_buy; twsdo.workTodo->placeOrderTodo()->add(pO); } } else { /* modify buy order */ PacketPlaceOrder *ppo = twsdo.p_orders[oids.buy_oid]; const PlaceOrder &po = ppo->getRequest(); if( po.order.lmtPrice != lmt_buy ) { DEBUG_PRINTF( "strat, modify buy order %s", symbol ); pO.orderId = oids.buy_oid; pO.order.action = "BUY"; pO.order.lmtPrice = lmt_buy; twsdo.workTodo->placeOrderTodo()->add(pO); } } if( twsdo.p_orders.find(oids.sell_oid) == twsdo.p_orders.end() ) { if( cur_pos > -max_pos ) { /* new sell order */ DEBUG_PRINTF( "strat, new sell order %s", symbol ); oids.sell_oid = twsdo.fetch_inc_order_id(); pO.orderId = oids.sell_oid; pO.order.action = "SELL"; pO.order.lmtPrice = lmt_sell; twsdo.workTodo->placeOrderTodo()->add(pO); } } else { /* modify sell order */ PacketPlaceOrder *ppo = twsdo.p_orders[oids.sell_oid]; const PlaceOrder &po = ppo->getRequest(); if( po.order.lmtPrice != lmt_sell ) { DEBUG_PRINTF( "strat, modify sell order %s", symbol ); pO.orderId = oids.sell_oid; pO.order.action = "SELL"; pO.order.lmtPrice = lmt_sell; twsdo.workTodo->placeOrderTodo()->add(pO); } } } void Strat::adjustOrders() { DEBUG_PRINTF( "strat, adjust orders" ); const MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo(); for( int i=0; i < mtodo.mktDataRequests.size(); i++ ) { const IB::Contract &contract = mtodo.mktDataRequests[i].ibContract; const Quote &quote = twsdo.quotes->at(i); /* here we also initialize zero order ids */ buy_sell_oid &oids = map_data_order[i]; if( quote.val[IB::BID] > 0.0 && quote.val[IB::ASK] > 0.0 ) { adjust_order( contract, quote, oids ); } else { /* invalid quotes, TODO cleanup, cancel, whatever */ } } DEBUG_PRINTF( "strat, place/modify %d orders", twsdo.workTodo->placeOrderTodo()->countLeft()); assert( mtodo.mktDataRequests.size() == map_data_order.size() ); }<commit_msg>cosmetics, correct indentations<commit_after>/*** tws_strat.cpp -- TWS strategy module * * Copyright (C) 2012 Ruediger Meier * * Author: Ruediger Meier <sweet_f_a@gmx.de> * * This file is part of twstools. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 "tws_strat.h" #include "tws_query.h" #include "tws_meta.h" #include "tws_account.h" #include "twsdo.h" #include "debug.h" #include <assert.h> buy_sell_oid::buy_sell_oid() : sell_oid(0), buy_oid(0) { } Strat::Strat( TwsDL& _twsdo) : twsdo(_twsdo) { } Strat::~Strat() { } /** * Return min tick price for a given contract. */ double Strat::min_tick(const IB::Contract& c) { assert( c.conId != 0 ); assert( twsdo.con_details.find( c.conId ) != twsdo.con_details.end() ); double min_tick = twsdo.con_details[c.conId]->minTick ; assert(min_tick > 0.0); return min_tick; } /** * Return portfolio position of a given contract. */ int Strat::prtfl_pos(const IB::Contract& c) { Prtfl::const_iterator it = twsdo.account->portfolio.find(c.conId); if( it != twsdo.account->portfolio.end() ) { return it->second.position; } return 0; } /** * Place or modify buy and sell orders for a single contract. Quote should * valid bid and ask. */ void Strat::adjust_order( const IB::Contract& c, const Quote& quote, buy_sell_oid& oids ) { PlaceOrder pO; pO.contract = c; pO.order.orderType = "LMT"; pO.order.totalQuantity = pO.contract.secType == "CASH" ? 25000 : 1; const char *symbol = pO.contract.symbol.c_str(); double quote_dist = 1 * min_tick(c); const int max_pos = 1; int cur_pos = prtfl_pos(c); double lmt_buy = quote.val[IB::BID] - quote_dist; double lmt_sell = quote.val[IB::ASK] + quote_dist; if( twsdo.p_orders.find(oids.buy_oid) == twsdo.p_orders.end() ) { /* new buy order */ if( cur_pos < max_pos ) { DEBUG_PRINTF( "strat, new buy order %s", symbol ); oids.buy_oid = twsdo.fetch_inc_order_id(); pO.orderId = oids.buy_oid; pO.order.action = "BUY"; pO.order.lmtPrice = lmt_buy; twsdo.workTodo->placeOrderTodo()->add(pO); } } else { /* modify buy order */ PacketPlaceOrder *ppo = twsdo.p_orders[oids.buy_oid]; const PlaceOrder &po = ppo->getRequest(); if( po.order.lmtPrice != lmt_buy ) { DEBUG_PRINTF( "strat, modify buy order %s", symbol ); pO.orderId = oids.buy_oid; pO.order.action = "BUY"; pO.order.lmtPrice = lmt_buy; twsdo.workTodo->placeOrderTodo()->add(pO); } } if( twsdo.p_orders.find(oids.sell_oid) == twsdo.p_orders.end() ) { /* new sell order */ if( cur_pos > -max_pos ) { DEBUG_PRINTF( "strat, new sell order %s", symbol ); oids.sell_oid = twsdo.fetch_inc_order_id(); pO.orderId = oids.sell_oid; pO.order.action = "SELL"; pO.order.lmtPrice = lmt_sell; twsdo.workTodo->placeOrderTodo()->add(pO); } } else { /* modify sell order */ PacketPlaceOrder *ppo = twsdo.p_orders[oids.sell_oid]; const PlaceOrder &po = ppo->getRequest(); if( po.order.lmtPrice != lmt_sell ) { DEBUG_PRINTF( "strat, modify sell order %s", symbol ); pO.orderId = oids.sell_oid; pO.order.action = "SELL"; pO.order.lmtPrice = lmt_sell; twsdo.workTodo->placeOrderTodo()->add(pO); } } } void Strat::adjustOrders() { DEBUG_PRINTF( "strat, adjust orders" ); const MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo(); for( int i=0; i < mtodo.mktDataRequests.size(); i++ ) { const IB::Contract &contract = mtodo.mktDataRequests[i].ibContract; const Quote &quote = twsdo.quotes->at(i); /* here we also initialize zero order ids */ buy_sell_oid &oids = map_data_order[i]; if( quote.val[IB::BID] > 0.0 && quote.val[IB::ASK] > 0.0 ) { adjust_order( contract, quote, oids ); } else { /* invalid quotes, TODO cleanup, cancel, whatever */ } } DEBUG_PRINTF( "strat, place/modify %d orders", twsdo.workTodo->placeOrderTodo()->countLeft()); assert( mtodo.mktDataRequests.size() == map_data_order.size() ); }<|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2019 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/cpu/backend/x64/x64_code_cache.h" #include <cstdlib> #include <cstring> #include "xenia/base/assert.h" #include "xenia/base/clock.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/base/memory.h" #include "xenia/base/platform_win.h" #include "xenia/cpu/function.h" // Function pointer definitions typedef DWORD(NTAPI* FnRtlAddGrowableFunctionTable)( _Out_ PVOID* DynamicTable, _In_reads_(MaximumEntryCount) PRUNTIME_FUNCTION FunctionTable, _In_ DWORD EntryCount, _In_ DWORD MaximumEntryCount, _In_ ULONG_PTR RangeBase, _In_ ULONG_PTR RangeEnd); typedef VOID(NTAPI* FnRtlGrowFunctionTable)(_Inout_ PVOID DynamicTable, _In_ DWORD NewEntryCount); typedef VOID(NTAPI* FnRtlDeleteGrowableFunctionTable)(_In_ PVOID DynamicTable); namespace xe { namespace cpu { namespace backend { namespace x64 { // https://msdn.microsoft.com/en-us/library/ssa62fwe.aspx typedef enum _UNWIND_OP_CODES { UWOP_PUSH_NONVOL = 0, /* info == register number */ UWOP_ALLOC_LARGE, /* no info, alloc size in next 2 slots */ UWOP_ALLOC_SMALL, /* info == size of allocation / 8 - 1 */ UWOP_SET_FPREG, /* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 */ UWOP_SAVE_NONVOL, /* info == register number, offset in next slot */ UWOP_SAVE_NONVOL_FAR, /* info == register number, offset in next 2 slots */ UWOP_SAVE_XMM128, /* info == XMM reg number, offset in next slot */ UWOP_SAVE_XMM128_FAR, /* info == XMM reg number, offset in next 2 slots */ UWOP_PUSH_MACHFRAME /* info == 0: no error-code, 1: error-code */ } UNWIND_CODE_OPS; class UNWIND_REGISTER { public: enum _ { RAX = 0, RCX = 1, RDX = 2, RBX = 3, RSP = 4, RBP = 5, RSI = 6, RDI = 7, R8 = 8, R9 = 9, R10 = 10, R11 = 11, R12 = 12, R13 = 13, R14 = 14, R15 = 15, }; }; typedef union _UNWIND_CODE { struct { uint8_t CodeOffset; uint8_t UnwindOp : 4; uint8_t OpInfo : 4; }; USHORT FrameOffset; } UNWIND_CODE, *PUNWIND_CODE; typedef struct _UNWIND_INFO { uint8_t Version : 3; uint8_t Flags : 5; uint8_t SizeOfProlog; uint8_t CountOfCodes; uint8_t FrameRegister : 4; uint8_t FrameOffset : 4; UNWIND_CODE UnwindCode[1]; /* UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1]; * union { * OPTIONAL ULONG ExceptionHandler; * OPTIONAL ULONG FunctionEntry; * }; * OPTIONAL ULONG ExceptionData[]; */ } UNWIND_INFO, *PUNWIND_INFO; // Size of unwind info per function. // TODO(benvanik): move this to emitter. static const uint32_t kUnwindInfoSize = sizeof(UNWIND_INFO) + (sizeof(UNWIND_CODE) * (6 - 1)); class Win32X64CodeCache : public X64CodeCache { public: Win32X64CodeCache(); ~Win32X64CodeCache() override; bool Initialize() override; void* LookupUnwindInfo(uint64_t host_pc) override; private: UnwindReservation RequestUnwindReservation(uint8_t* entry_address) override; void PlaceCode(uint32_t guest_address, void* machine_code, const EmitFunctionInfo& func_info, void* code_address, UnwindReservation unwind_reservation) override; void InitializeUnwindEntry(uint8_t* unwind_entry_address, size_t unwind_table_slot, void* code_address, const EmitFunctionInfo& func_info); // Growable function table system handle. void* unwind_table_handle_ = nullptr; // Actual unwind table entries. std::vector<RUNTIME_FUNCTION> unwind_table_; // Current number of entries in the table. std::atomic<uint32_t> unwind_table_count_ = {0}; // Does this version of Windows support growable funciton tables? bool supports_growable_table_ = false; FnRtlAddGrowableFunctionTable add_growable_table_ = nullptr; FnRtlDeleteGrowableFunctionTable delete_growable_table_ = nullptr; FnRtlGrowFunctionTable grow_table_ = nullptr; }; std::unique_ptr<X64CodeCache> X64CodeCache::Create() { return std::make_unique<Win32X64CodeCache>(); } Win32X64CodeCache::Win32X64CodeCache() = default; Win32X64CodeCache::~Win32X64CodeCache() { if (supports_growable_table_) { if (unwind_table_handle_) { delete_growable_table_(unwind_table_handle_); } } else { if (generated_code_base_) { RtlDeleteFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>( reinterpret_cast<DWORD64>(generated_code_base_) | 0x3)); } } } bool Win32X64CodeCache::Initialize() { if (!X64CodeCache::Initialize()) { return false; } // Compute total number of unwind entries we should allocate. // We don't support reallocing right now, so this should be high. unwind_table_.resize(kMaximumFunctionCount); // Check if this version of Windows supports growable function tables. auto ntdll_handle = GetModuleHandleW(L"ntdll.dll"); if (!ntdll_handle) { add_growable_table_ = nullptr; delete_growable_table_ = nullptr; grow_table_ = nullptr; } else { add_growable_table_ = (FnRtlAddGrowableFunctionTable)GetProcAddress( ntdll_handle, "RtlAddGrowableFunctionTable"); delete_growable_table_ = (FnRtlDeleteGrowableFunctionTable)GetProcAddress( ntdll_handle, "RtlDeleteGrowableFunctionTable"); grow_table_ = (FnRtlGrowFunctionTable)GetProcAddress( ntdll_handle, "RtlGrowFunctionTable"); } supports_growable_table_ = add_growable_table_ && delete_growable_table_ && grow_table_; // Create table and register with the system. It's empty now, but we'll grow // it as functions are added. if (supports_growable_table_) { if (add_growable_table_(&unwind_table_handle_, unwind_table_.data(), unwind_table_count_, DWORD(unwind_table_.size()), reinterpret_cast<ULONG_PTR>(generated_code_base_), reinterpret_cast<ULONG_PTR>(generated_code_base_ + kGeneratedCodeSize))) { XELOGE("Unable to create unwind function table"); return false; } } else { // Install a callback that the debugger will use to lookup unwind info on // demand. if (!RtlInstallFunctionTableCallback( reinterpret_cast<DWORD64>(generated_code_base_) | 0x3, reinterpret_cast<DWORD64>(generated_code_base_), kGeneratedCodeSize, [](DWORD64 control_pc, PVOID context) { auto code_cache = reinterpret_cast<Win32X64CodeCache*>(context); return reinterpret_cast<PRUNTIME_FUNCTION>( code_cache->LookupUnwindInfo(control_pc)); }, this, nullptr)) { XELOGE("Unable to install function table callback"); return false; } } return true; } Win32X64CodeCache::UnwindReservation Win32X64CodeCache::RequestUnwindReservation(uint8_t* entry_address) { assert_false(unwind_table_count_ >= kMaximumFunctionCount); UnwindReservation unwind_reservation; unwind_reservation.data_size = xe::round_up(kUnwindInfoSize, 16); unwind_reservation.table_slot = unwind_table_count_++; unwind_reservation.entry_address = entry_address; return unwind_reservation; } void Win32X64CodeCache::PlaceCode(uint32_t guest_address, void* machine_code, const EmitFunctionInfo& func_info, void* code_address, UnwindReservation unwind_reservation) { // Add unwind info. InitializeUnwindEntry(unwind_reservation.entry_address, unwind_reservation.table_slot, code_address, func_info); if (supports_growable_table_) { // Notify that the unwind table has grown. // We do this outside of the lock, but with the latest total count. grow_table_(unwind_table_handle_, unwind_table_count_); } // This isn't needed on x64 (probably), but is convention. FlushInstructionCache(GetCurrentProcess(), code_address, func_info.code_size.total); } void Win32X64CodeCache::InitializeUnwindEntry( uint8_t* unwind_entry_address, size_t unwind_table_slot, void* code_address, const EmitFunctionInfo& func_info) { auto unwind_info = reinterpret_cast<UNWIND_INFO*>(unwind_entry_address); UNWIND_CODE* unwind_code = nullptr; assert_true(func_info.code_size.prolog < 256); // needs to fit into a uint8_t auto prolog_size = static_cast<uint8_t>(func_info.code_size.prolog); assert_true(func_info.prolog_stack_alloc_offset < 256); // needs to fit into a uint8_t auto prolog_stack_alloc_offset = static_cast<uint8_t>(func_info.prolog_stack_alloc_offset); if (!func_info.stack_size) { // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; } else if (func_info.stack_size <= 128) { // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->CodeOffset = prolog_stack_alloc_offset; unwind_code->UnwindOp = UWOP_ALLOC_SMALL; unwind_code->OpInfo = (func_info.stack_size / 8) - 1; } else { // TODO(benvanik): take as parameters? // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->CodeOffset = prolog_stack_alloc_offset; unwind_code->UnwindOp = UWOP_ALLOC_LARGE; unwind_code->OpInfo = 0; // One slot for size assert_true((func_info.stack_size / 8) < 65536u); unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->FrameOffset = (USHORT)(func_info.stack_size) / 8; } if (unwind_info->CountOfCodes % 1) { // Count of unwind codes must always be even. std::memset(&unwind_info->UnwindCode[unwind_info->CountOfCodes + 1], 0, sizeof(UNWIND_CODE)); } // Add entry. auto& fn_entry = unwind_table_[unwind_table_slot]; fn_entry.BeginAddress = (DWORD)(reinterpret_cast<uint8_t*>(code_address) - generated_code_base_); fn_entry.EndAddress = (DWORD)(fn_entry.BeginAddress + func_info.code_size.total); fn_entry.UnwindData = (DWORD)(unwind_entry_address - generated_code_base_); } void* Win32X64CodeCache::LookupUnwindInfo(uint64_t host_pc) { return std::bsearch( &host_pc, unwind_table_.data(), unwind_table_count_, sizeof(RUNTIME_FUNCTION), [](const void* key_ptr, const void* element_ptr) { auto key = *reinterpret_cast<const uintptr_t*>(key_ptr) - kGeneratedCodeBase; auto element = reinterpret_cast<const RUNTIME_FUNCTION*>(element_ptr); if (key < element->BeginAddress) { return -1; } else if (key > element->EndAddress) { return 1; } else { return 0; } }); } } // namespace x64 } // namespace backend } // namespace cpu } // namespace xe <commit_msg>[x64] Simplify growable function pointer definitions.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2019 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/cpu/backend/x64/x64_code_cache.h" #include <cstdlib> #include <cstring> #include "xenia/base/assert.h" #include "xenia/base/clock.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/base/memory.h" #include "xenia/base/platform_win.h" #include "xenia/cpu/function.h" // Function pointer definitions using FnRtlAddGrowableFunctionTable = decltype(&RtlAddGrowableFunctionTable); using FnRtlGrowFunctionTable = decltype(&RtlGrowFunctionTable); using FnRtlDeleteGrowableFunctionTable = decltype(&RtlDeleteGrowableFunctionTable); namespace xe { namespace cpu { namespace backend { namespace x64 { // https://msdn.microsoft.com/en-us/library/ssa62fwe.aspx typedef enum _UNWIND_OP_CODES { UWOP_PUSH_NONVOL = 0, /* info == register number */ UWOP_ALLOC_LARGE, /* no info, alloc size in next 2 slots */ UWOP_ALLOC_SMALL, /* info == size of allocation / 8 - 1 */ UWOP_SET_FPREG, /* no info, FP = RSP + UNWIND_INFO.FPRegOffset*16 */ UWOP_SAVE_NONVOL, /* info == register number, offset in next slot */ UWOP_SAVE_NONVOL_FAR, /* info == register number, offset in next 2 slots */ UWOP_SAVE_XMM128, /* info == XMM reg number, offset in next slot */ UWOP_SAVE_XMM128_FAR, /* info == XMM reg number, offset in next 2 slots */ UWOP_PUSH_MACHFRAME /* info == 0: no error-code, 1: error-code */ } UNWIND_CODE_OPS; class UNWIND_REGISTER { public: enum _ { RAX = 0, RCX = 1, RDX = 2, RBX = 3, RSP = 4, RBP = 5, RSI = 6, RDI = 7, R8 = 8, R9 = 9, R10 = 10, R11 = 11, R12 = 12, R13 = 13, R14 = 14, R15 = 15, }; }; typedef union _UNWIND_CODE { struct { uint8_t CodeOffset; uint8_t UnwindOp : 4; uint8_t OpInfo : 4; }; USHORT FrameOffset; } UNWIND_CODE, *PUNWIND_CODE; typedef struct _UNWIND_INFO { uint8_t Version : 3; uint8_t Flags : 5; uint8_t SizeOfProlog; uint8_t CountOfCodes; uint8_t FrameRegister : 4; uint8_t FrameOffset : 4; UNWIND_CODE UnwindCode[1]; /* UNWIND_CODE MoreUnwindCode[((CountOfCodes + 1) & ~1) - 1]; * union { * OPTIONAL ULONG ExceptionHandler; * OPTIONAL ULONG FunctionEntry; * }; * OPTIONAL ULONG ExceptionData[]; */ } UNWIND_INFO, *PUNWIND_INFO; // Size of unwind info per function. // TODO(benvanik): move this to emitter. static const uint32_t kUnwindInfoSize = sizeof(UNWIND_INFO) + (sizeof(UNWIND_CODE) * (6 - 1)); class Win32X64CodeCache : public X64CodeCache { public: Win32X64CodeCache(); ~Win32X64CodeCache() override; bool Initialize() override; void* LookupUnwindInfo(uint64_t host_pc) override; private: UnwindReservation RequestUnwindReservation(uint8_t* entry_address) override; void PlaceCode(uint32_t guest_address, void* machine_code, const EmitFunctionInfo& func_info, void* code_address, UnwindReservation unwind_reservation) override; void InitializeUnwindEntry(uint8_t* unwind_entry_address, size_t unwind_table_slot, void* code_address, const EmitFunctionInfo& func_info); // Growable function table system handle. void* unwind_table_handle_ = nullptr; // Actual unwind table entries. std::vector<RUNTIME_FUNCTION> unwind_table_; // Current number of entries in the table. std::atomic<uint32_t> unwind_table_count_ = {0}; // Does this version of Windows support growable funciton tables? bool supports_growable_table_ = false; FnRtlAddGrowableFunctionTable add_growable_table_ = nullptr; FnRtlDeleteGrowableFunctionTable delete_growable_table_ = nullptr; FnRtlGrowFunctionTable grow_table_ = nullptr; }; std::unique_ptr<X64CodeCache> X64CodeCache::Create() { return std::make_unique<Win32X64CodeCache>(); } Win32X64CodeCache::Win32X64CodeCache() = default; Win32X64CodeCache::~Win32X64CodeCache() { if (supports_growable_table_) { if (unwind_table_handle_) { delete_growable_table_(unwind_table_handle_); } } else { if (generated_code_base_) { RtlDeleteFunctionTable(reinterpret_cast<PRUNTIME_FUNCTION>( reinterpret_cast<DWORD64>(generated_code_base_) | 0x3)); } } } bool Win32X64CodeCache::Initialize() { if (!X64CodeCache::Initialize()) { return false; } // Compute total number of unwind entries we should allocate. // We don't support reallocing right now, so this should be high. unwind_table_.resize(kMaximumFunctionCount); // Check if this version of Windows supports growable function tables. auto ntdll_handle = GetModuleHandleW(L"ntdll.dll"); if (!ntdll_handle) { add_growable_table_ = nullptr; delete_growable_table_ = nullptr; grow_table_ = nullptr; } else { add_growable_table_ = (FnRtlAddGrowableFunctionTable)GetProcAddress( ntdll_handle, "RtlAddGrowableFunctionTable"); delete_growable_table_ = (FnRtlDeleteGrowableFunctionTable)GetProcAddress( ntdll_handle, "RtlDeleteGrowableFunctionTable"); grow_table_ = (FnRtlGrowFunctionTable)GetProcAddress( ntdll_handle, "RtlGrowFunctionTable"); } supports_growable_table_ = add_growable_table_ && delete_growable_table_ && grow_table_; // Create table and register with the system. It's empty now, but we'll grow // it as functions are added. if (supports_growable_table_) { if (add_growable_table_(&unwind_table_handle_, unwind_table_.data(), unwind_table_count_, DWORD(unwind_table_.size()), reinterpret_cast<ULONG_PTR>(generated_code_base_), reinterpret_cast<ULONG_PTR>(generated_code_base_ + kGeneratedCodeSize))) { XELOGE("Unable to create unwind function table"); return false; } } else { // Install a callback that the debugger will use to lookup unwind info on // demand. if (!RtlInstallFunctionTableCallback( reinterpret_cast<DWORD64>(generated_code_base_) | 0x3, reinterpret_cast<DWORD64>(generated_code_base_), kGeneratedCodeSize, [](DWORD64 control_pc, PVOID context) { auto code_cache = reinterpret_cast<Win32X64CodeCache*>(context); return reinterpret_cast<PRUNTIME_FUNCTION>( code_cache->LookupUnwindInfo(control_pc)); }, this, nullptr)) { XELOGE("Unable to install function table callback"); return false; } } return true; } Win32X64CodeCache::UnwindReservation Win32X64CodeCache::RequestUnwindReservation(uint8_t* entry_address) { assert_false(unwind_table_count_ >= kMaximumFunctionCount); UnwindReservation unwind_reservation; unwind_reservation.data_size = xe::round_up(kUnwindInfoSize, 16); unwind_reservation.table_slot = unwind_table_count_++; unwind_reservation.entry_address = entry_address; return unwind_reservation; } void Win32X64CodeCache::PlaceCode(uint32_t guest_address, void* machine_code, const EmitFunctionInfo& func_info, void* code_address, UnwindReservation unwind_reservation) { // Add unwind info. InitializeUnwindEntry(unwind_reservation.entry_address, unwind_reservation.table_slot, code_address, func_info); if (supports_growable_table_) { // Notify that the unwind table has grown. // We do this outside of the lock, but with the latest total count. grow_table_(unwind_table_handle_, unwind_table_count_); } // This isn't needed on x64 (probably), but is convention. FlushInstructionCache(GetCurrentProcess(), code_address, func_info.code_size.total); } void Win32X64CodeCache::InitializeUnwindEntry( uint8_t* unwind_entry_address, size_t unwind_table_slot, void* code_address, const EmitFunctionInfo& func_info) { auto unwind_info = reinterpret_cast<UNWIND_INFO*>(unwind_entry_address); UNWIND_CODE* unwind_code = nullptr; assert_true(func_info.code_size.prolog < 256); // needs to fit into a uint8_t auto prolog_size = static_cast<uint8_t>(func_info.code_size.prolog); assert_true(func_info.prolog_stack_alloc_offset < 256); // needs to fit into a uint8_t auto prolog_stack_alloc_offset = static_cast<uint8_t>(func_info.prolog_stack_alloc_offset); if (!func_info.stack_size) { // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; } else if (func_info.stack_size <= 128) { // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->CodeOffset = prolog_stack_alloc_offset; unwind_code->UnwindOp = UWOP_ALLOC_SMALL; unwind_code->OpInfo = (func_info.stack_size / 8) - 1; } else { // TODO(benvanik): take as parameters? // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info unwind_info->Version = 1; unwind_info->Flags = 0; unwind_info->SizeOfProlog = prolog_size; unwind_info->CountOfCodes = 0; unwind_info->FrameRegister = 0; unwind_info->FrameOffset = 0; // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_code unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->CodeOffset = prolog_stack_alloc_offset; unwind_code->UnwindOp = UWOP_ALLOC_LARGE; unwind_code->OpInfo = 0; // One slot for size assert_true((func_info.stack_size / 8) < 65536u); unwind_code = &unwind_info->UnwindCode[unwind_info->CountOfCodes++]; unwind_code->FrameOffset = (USHORT)(func_info.stack_size) / 8; } if (unwind_info->CountOfCodes % 1) { // Count of unwind codes must always be even. std::memset(&unwind_info->UnwindCode[unwind_info->CountOfCodes + 1], 0, sizeof(UNWIND_CODE)); } // Add entry. auto& fn_entry = unwind_table_[unwind_table_slot]; fn_entry.BeginAddress = (DWORD)(reinterpret_cast<uint8_t*>(code_address) - generated_code_base_); fn_entry.EndAddress = (DWORD)(fn_entry.BeginAddress + func_info.code_size.total); fn_entry.UnwindData = (DWORD)(unwind_entry_address - generated_code_base_); } void* Win32X64CodeCache::LookupUnwindInfo(uint64_t host_pc) { return std::bsearch( &host_pc, unwind_table_.data(), unwind_table_count_, sizeof(RUNTIME_FUNCTION), [](const void* key_ptr, const void* element_ptr) { auto key = *reinterpret_cast<const uintptr_t*>(key_ptr) - kGeneratedCodeBase; auto element = reinterpret_cast<const RUNTIME_FUNCTION*>(element_ptr); if (key < element->BeginAddress) { return -1; } else if (key > element->EndAddress) { return 1; } else { return 0; } }); } } // namespace x64 } // namespace backend } // namespace cpu } // namespace xe <|endoftext|>
<commit_before>/***************************************************************************** * Help.cpp : Help and About dialogs **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "dialogs/about.hpp" #include "dialogs/help.hpp" #include "dialogs_provider.hpp" #include "util/qvlcframe.hpp" #include "qt4.hpp" #include <QTextBrowser> #include <QTabWidget> #include <QFile> #include <QLabel> #include <QString> HelpDialog *HelpDialog::instance = NULL; HelpDialog::HelpDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Help" ) ); resize( 600, 560 ); QGridLayout *layout = new QGridLayout( this ); QTextBrowser *helpBrowser = new QTextBrowser( this ); helpBrowser->setOpenExternalLinks( true ); helpBrowser->setHtml( _("<html><h2>Welcome to VLC media player help</h2><h3>Documentation</h3><p>You can find VLC documentation on VideoLAN's <a href=\"http://wiki.videolan.org\">wiki</a> website.</p> <p>If you are a newcomer to VLC media player, please read the<br><a href=\"http://wiki.videolan.org/Documentation:VLC_for_dummies\"><em>Introduction to VLC media player</em></a>.</p><p>You will find some information on how to use the player in the <br>\"<a href=\"http://wiki.videolan.org/Documentation:Play_HowTo\"><em>How to play files with VLC media player<em></a>\" document.</p> For all the saving, converting, transcoding, encoding, muxing and streaming tasks, you should find useful information in the <a href=\"http://wiki.videolan.org/Documentation:Streaming_HowTo\">Streaming Documentation</a>.</p><p>If you are unsure about terminology, please consult the <a href=\"http://wiki.videolan.org/Knowledge_Base\">knowledge base</a>.</p> <p>To understand the main keyboard shortcuts, read the <a href=\"http://wiki.videolan.org/Hotkeys\">shortcuts</a> page.</p><h3>Help</h3><p>Before asking any question, please refer yourself to the <a href=\"http://wiki.videolan.org/Frequently_Asked_Questions\">FAQ</a>.</p><p>You might then get (and give) help on the <a href=\"http://forum.videolan.org\">Forums</a>, the <a href=\"http://www.videolan.org/vlc/lists.html\">mailing-lists</a> or our IRC channel ( <a href=\"http://krishna.videolan.org/cgi-bin/irc/irc.cgi\"><em>#videolan</em></a> on irc.freenode.net ).</p><h3>Contribute to the project</h3><p>You can help the VideoLAN project giving some of your time to help the community, to design skins, to translate the documentation, to test and to code. You can also give funds and material to help us. And of course, you can <b>promote</b> VLC media player.</p></html>") ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); layout->addWidget( helpBrowser, 0, 0, 1, 0 ); layout->addWidget( closeButton, 1, 3 ); BUTTONACT( closeButton, close() ); } HelpDialog::~HelpDialog() { } void HelpDialog::close() { this->toggleVisible(); } AboutDialog *AboutDialog::instance = NULL; AboutDialog::AboutDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "About" ) ); resize( 600, 500 ); QGridLayout *layout = new QGridLayout( this ); QTabWidget *tab = new QTabWidget( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); closeButton->setDefault( true ); QLabel *introduction = new QLabel( qtr( "Information about VLC media player." ) ); QLabel *iconVLC = new QLabel; iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) ); layout->addWidget( iconVLC, 0, 0, 1, 1 ); layout->addWidget( introduction, 0, 1, 1, 7 ); layout->addWidget( tab, 1, 0, 1, 8 ); layout->addWidget( closeButton, 2, 6, 1, 2 ); /* Main Introduction */ QWidget *infoWidget = new QWidget( this ); QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget ); QLabel *infoLabel = new QLabel( "VLC media player " PACKAGE_VERSION "\n\n" "(c) 1996-2007777777 - the VideoLAN Team\n\n" + qtr( "VLC media player is a free media player, made by the " "VideoLAN Team.\nIt is a standalone multimedia player, " "encoder and streamer, that can read from many supports " "(files, CDs, DVDs, networks, capture cards) and that works " "on many platforms.\n\n" ) + qtr( "You are using the new Qt4 Interface.\n" ) + qtr( "Compiled by " ) + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileDomain() ) + ".\n" + "Compiler: " + qfu( VLC_Compiler() ) +".\n" + qtr( "Based on SVN revision: " ) + qfu( VLC_Changeset() ) + ".\n\n" + qtr( "This program comes with NO WARRANTY, to the extent " "permitted by the law; read the distribution tab.\n\n" ) + "The VideoLAN team <videolan@videolan.org> \n" "http://www.videolan.org/\n") ; infoLabel->setWordWrap( infoLabel ); QLabel *iconVLC2 = new QLabel; iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) ); infoLayout->addWidget( iconVLC2 ); infoLayout->addWidget( infoLabel ); /* GPL License */ QTextEdit *licenseEdit = new QTextEdit( this ); licenseEdit->setText( qfu( psz_license ) ); licenseEdit->setReadOnly( true ); /* People who helped */ QWidget *thanksWidget = new QWidget( this ); QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget ); QLabel *thanksLabel = new QLabel( qtr("We would like to thanks the whole " "community, the testers, our users and the following people " "(and the missing ones...) for their collaboration to " "provide the best software." ) ); thanksLabel->setWordWrap( true ); thanksLayout->addWidget( thanksLabel ); QTextEdit *thanksEdit = new QTextEdit( this ); thanksEdit->setText( qfu( psz_thanks ) ); thanksEdit->setReadOnly( true ); thanksLayout->addWidget( thanksEdit ); /* People who wrote the software */ QTextEdit *authorsEdit = new QTextEdit( this ); authorsEdit->setText( qfu( psz_authors ) ); authorsEdit->setReadOnly( true ); /* add the tabs to the Tabwidget */ tab->addTab( infoWidget, qtr( "General Info" ) ); tab->addTab( authorsEdit, qtr( "Authors" ) ); tab->addTab( thanksWidget, qtr("Thanks") ); tab->addTab( licenseEdit, qtr("Distribution License") ); BUTTONACT( closeButton, close() ); } AboutDialog::~AboutDialog() { } void AboutDialog::close() { this->toggleVisible(); } <commit_msg>Oups<commit_after>/***************************************************************************** * Help.cpp : Help and About dialogs **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "dialogs/about.hpp" #include "dialogs/help.hpp" #include "dialogs_provider.hpp" #include "util/qvlcframe.hpp" #include "qt4.hpp" #include <QTextBrowser> #include <QTabWidget> #include <QFile> #include <QLabel> #include <QString> HelpDialog *HelpDialog::instance = NULL; HelpDialog::HelpDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Help" ) ); resize( 600, 560 ); QGridLayout *layout = new QGridLayout( this ); QTextBrowser *helpBrowser = new QTextBrowser( this ); helpBrowser->setOpenExternalLinks( true ); helpBrowser->setHtml( _("<html><h2>Welcome to VLC media player help</h2><h3>Documentation</h3><p>You can find VLC documentation on VideoLAN's <a href=\"http://wiki.videolan.org\">wiki</a> website.</p> <p>If you are a newcomer to VLC media player, please read the<br><a href=\"http://wiki.videolan.org/Documentation:VLC_for_dummies\"><em>Introduction to VLC media player</em></a>.</p><p>You will find some information on how to use the player in the <br>\"<a href=\"http://wiki.videolan.org/Documentation:Play_HowTo\"><em>How to play files with VLC media player<em></a>\" document.</p> For all the saving, converting, transcoding, encoding, muxing and streaming tasks, you should find useful information in the <a href=\"http://wiki.videolan.org/Documentation:Streaming_HowTo\">Streaming Documentation</a>.</p><p>If you are unsure about terminology, please consult the <a href=\"http://wiki.videolan.org/Knowledge_Base\">knowledge base</a>.</p> <p>To understand the main keyboard shortcuts, read the <a href=\"http://wiki.videolan.org/Hotkeys\">shortcuts</a> page.</p><h3>Help</h3><p>Before asking any question, please refer yourself to the <a href=\"http://wiki.videolan.org/Frequently_Asked_Questions\">FAQ</a>.</p><p>You might then get (and give) help on the <a href=\"http://forum.videolan.org\">Forums</a>, the <a href=\"http://www.videolan.org/vlc/lists.html\">mailing-lists</a> or our IRC channel ( <a href=\"http://krishna.videolan.org/cgi-bin/irc/irc.cgi\"><em>#videolan</em></a> on irc.freenode.net ).</p><h3>Contribute to the project</h3><p>You can help the VideoLAN project giving some of your time to help the community, to design skins, to translate the documentation, to test and to code. You can also give funds and material to help us. And of course, you can <b>promote</b> VLC media player.</p></html>") ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); layout->addWidget( helpBrowser, 0, 0, 1, 0 ); layout->addWidget( closeButton, 1, 3 ); BUTTONACT( closeButton, close() ); } HelpDialog::~HelpDialog() { } void HelpDialog::close() { this->toggleVisible(); } AboutDialog *AboutDialog::instance = NULL; AboutDialog::AboutDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "About" ) ); resize( 600, 500 ); QGridLayout *layout = new QGridLayout( this ); QTabWidget *tab = new QTabWidget( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); closeButton->setDefault( true ); QLabel *introduction = new QLabel( qtr( "Information about VLC media player." ) ); QLabel *iconVLC = new QLabel; iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) ); layout->addWidget( iconVLC, 0, 0, 1, 1 ); layout->addWidget( introduction, 0, 1, 1, 7 ); layout->addWidget( tab, 1, 0, 1, 8 ); layout->addWidget( closeButton, 2, 6, 1, 2 ); /* Main Introduction */ QWidget *infoWidget = new QWidget( this ); QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget ); QLabel *infoLabel = new QLabel( "VLC media player " PACKAGE_VERSION "\n\n" "(c) 1996-2007 - the VideoLAN Team\n\n" + qtr( "VLC media player is a free media player, made by the " "VideoLAN Team.\nIt is a standalone multimedia player, " "encoder and streamer, that can read from many supports " "(files, CDs, DVDs, networks, capture cards) and that works " "on many platforms.\n\n" ) + qtr( "You are using the new Qt4 Interface.\n" ) + qtr( "Compiled by " ) + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileDomain() ) + ".\n" + "Compiler: " + qfu( VLC_Compiler() ) +".\n" + qtr( "Based on SVN revision: " ) + qfu( VLC_Changeset() ) + ".\n\n" + qtr( "This program comes with NO WARRANTY, to the extent " "permitted by the law; read the distribution tab.\n\n" ) + "The VideoLAN team <videolan@videolan.org> \n" "http://www.videolan.org/\n") ; infoLabel->setWordWrap( infoLabel ); QLabel *iconVLC2 = new QLabel; iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) ); infoLayout->addWidget( iconVLC2 ); infoLayout->addWidget( infoLabel ); /* GPL License */ QTextEdit *licenseEdit = new QTextEdit( this ); licenseEdit->setText( qfu( psz_license ) ); licenseEdit->setReadOnly( true ); /* People who helped */ QWidget *thanksWidget = new QWidget( this ); QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget ); QLabel *thanksLabel = new QLabel( qtr("We would like to thanks the whole " "community, the testers, our users and the following people " "(and the missing ones...) for their collaboration to " "provide the best software." ) ); thanksLabel->setWordWrap( true ); thanksLayout->addWidget( thanksLabel ); QTextEdit *thanksEdit = new QTextEdit( this ); thanksEdit->setText( qfu( psz_thanks ) ); thanksEdit->setReadOnly( true ); thanksLayout->addWidget( thanksEdit ); /* People who wrote the software */ QTextEdit *authorsEdit = new QTextEdit( this ); authorsEdit->setText( qfu( psz_authors ) ); authorsEdit->setReadOnly( true ); /* add the tabs to the Tabwidget */ tab->addTab( infoWidget, qtr( "General Info" ) ); tab->addTab( authorsEdit, qtr( "Authors" ) ); tab->addTab( thanksWidget, qtr("Thanks") ); tab->addTab( licenseEdit, qtr("Distribution License") ); BUTTONACT( closeButton, close() ); } AboutDialog::~AboutDialog() { } void AboutDialog::close() { this->toggleVisible(); } <|endoftext|>
<commit_before>//Main driver program to run Velocity. #include <conio.h> //Provides console input/output functions. #include <stdio.h> //Provides streams to operate with keyboard. #include "vars.h" //Contains global variables and structure definitions for the player and enemies. #include "gfx.h" //Contains function definitions to generate the game environment. #include "scores.h" //Contains function definitions for appending to/diplaying a highscores database. void main() { clrscr(); //Initializing graphics. setviewport(0, 0, 200, getmaxy(), 0); int gd= DETECT, gm; initgraph(&gd, &gm, "C:\\turboc3\\bgi"); //Initializing player variables. int pos= CENTER; player.width= 20; player.height= 40; player.score= 0; //Initializing enemy variables. enemy.height= 0; enemy.height2= 200; enemy.pos= LEFT; enemy.pos2= CENTER; enemy.pos3= RIGHT; char input= menu(); //Displays the menu with instructions to play the game or quit the program (if return value of menu() is 'q'). int start= clock(); //Assigns the current processor time to the integer start. Used in the score() function. //Start of main game loop. while(input!= 'q') { score(start); if(kbhit()) { input= getch(); switch(input) { //'a' to move vehicle to left. case 'a': { pos--; if(pos< -1) pos= -1; cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(10); break; } //'d' to move vehicle to right. case 'd': { pos++; if(pos> 1) pos= 1; cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(10); break; } } } else { cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(speed); //Determines the game speed after every refresh. } if( checkCrash(player.pos, 400-player.height, enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2) == 1) { //This section is only invoked if the player crashes. cleardevice(); settextstyle(0, 0, 6); outtextxy(100, getmaxy()/2-100, "GAME OVER!"); settextstyle(9, 0, 4); outtextxy(150, getmaxy()/2, "Your Score"); outtextxy(475, getmaxy()/2, scr); getch(); clrscr(); cleardevice(); cout<<"Enter your name..."<<endl; cin>>player.name; //This section adds player's data to the highscores file and subsequently displays them. clrscr(); cleardevice(); insert(player); displayScores(); getch(); cleardevice(); //This section resets the score and brings the player back to the main menu. delay(1000); input= menu(); start= clock(); speed= 30; } } closegraph(); } <commit_msg>Update main.cpp<commit_after>//Main driver program to run Velocity. #include <conio.h> //Provides console input/output functions. #include <stdio.h> //Provides streams to operate with keyboard. #include "vars.h" //Contains global variables and structure definitions for the player and enemies. #include "gfx.h" //Contains function definitions to generate the game environment. #include "scores.h" //Contains function definitions for appending to/diplaying a highscores database. void main() { clrscr(); //Initializing graphics. setviewport(0, 0, 200, getmaxy(), 0); int gd= DETECT, gm; initgraph(&gd, &gm, "C:\\turboc3\\bgi"); //Initializing player variables. int pos= CENTER; player.width= 20; player.height= 40; player.score= 0; //Initializing enemy variables. enemy.height= 0; enemy.height2= 200; enemy.pos= LEFT; enemy.pos2= CENTER; enemy.pos3= RIGHT; char input= menu(); //Displays the menu with instructions to play the game or quit the program (if return value of menu() is 'q'). int start= clock(); //Assigns the current processor time to the integer start. Used in the score() function in scores.h. //Start of main game loop. while(input!= 'q') { score(start); if(kbhit()) { input= getch(); switch(input) { //'a' to move vehicle to left. case 'a': { pos--; if(pos< -1) pos= -1; cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(10); break; } //'d' to move vehicle to right. case 'd': { pos++; if(pos> 1) pos= 1; cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(10); break; } } } else { cleardevice(); pGen(pos); eGen(enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2); lineGen(pos); delay(speed); //Determines the game speed after every refresh. } if( checkCrash(player.pos, 400-player.height, enemy.pos, enemy.pos2, enemy.pos3, enemy.height, enemy.height2) == 1) { //This section is only invoked if the player crashes. cleardevice(); settextstyle(0, 0, 6); outtextxy(100, getmaxy()/2-100, "GAME OVER!"); settextstyle(9, 0, 4); outtextxy(150, getmaxy()/2, "Your Score"); outtextxy(475, getmaxy()/2, scr); getch(); clrscr(); cleardevice(); cout<<"Enter your name..."<<endl; cin>>player.name; //This section adds player's data to the highscores file and subsequently displays them. clrscr(); cleardevice(); insert(player); displayScores(); getch(); cleardevice(); //This section resets the score and brings the player back to the main menu. delay(1000); input= menu(); start= clock(); speed= 30; } } closegraph(); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "credd.h" #include "condor_config.h" #include "condor_daemon_core.h" #include "condor_debug.h" #include "store_cred.h" #include "internet.h" #include "get_daemon_name.h" #include "subsystem_info.h" #include "credmon_interface.h" //------------------------------------------------------------- CredDaemon *credd; CredDaemon::CredDaemon() : m_name(NULL), m_update_collector_tid(-1) { reconfig(); // Command handler for the user condor_store_cred tool daemonCore->Register_Command( STORE_CRED, "STORE_CRED", (CommandHandler)&store_cred_handler, "store_cred_handler", NULL, WRITE, D_FULLDEBUG ); // Command handler for daemons to get the password daemonCore->Register_Command( CREDD_GET_PASSWD, "CREDD_GET_PASSWD", (CommandHandler)&get_cred_handler, "get_cred_handler", NULL, DAEMON, D_FULLDEBUG ); // NOP command for testing authentication daemonCore->Register_Command( CREDD_NOP, "CREDD_NOP", (CommandHandlercpp)&CredDaemon::nop_handler, "nop_handler", this, DAEMON, D_FULLDEBUG ); // NOP command for testing authentication daemonCore->Register_Command( CREDD_REFRESH_ALL, "CREDD_REFRESH_ALL", (CommandHandlercpp)&CredDaemon::refresh_all_handler, "refresh_all_handler", this, DAEMON, D_FULLDEBUG ); // set timer to periodically advertise ourself to the collector daemonCore->Register_Timer(0, m_update_collector_interval, (TimerHandlercpp)&CredDaemon::update_collector, "update_collector", this); // only sweep if we have a cred dir char* p = param("SEC_CREDENTIAL_DIRECTORY"); if(p) { // didn't need the value, just to see if it's defined. free(p); dprintf(D_ALWAYS, "ZKM: setting sweep_timer_handler\n"); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 30); m_cred_sweep_tid = daemonCore->Register_Timer( sec_cred_sweep_interval, sec_cred_sweep_interval, (TimerHandlercpp)&CredDaemon::sweep_timer_handler, "sweep_timer_handler", this ); } } CredDaemon::~CredDaemon() { // tell our collector we're going away invalidate_ad(); if (m_name != NULL) { free(m_name); } } void CredDaemon::reconfig() { // get our daemon name; if CREDD_HOST is defined, we use it // as our name. this is because clients that have CREDD_HOST // defined will query the Collector for a CredD ad that has // a name matching its setting for CREDD_HOST. but CREDD_HOST // will not necessarily match what default_daemon_name() // returns - for example, if CREDD_HOST is set to a DNS alias // if (m_name != NULL) { free(m_name); } m_name = param("CREDD_HOST"); if (m_name == NULL) { char* tmp = default_daemon_name(); ASSERT(tmp != NULL); m_name = strdup(tmp); ASSERT(m_name != NULL); delete[] tmp; } if(m_name == NULL) { EXCEPT("default_daemon_name() returned NULL"); } // how often do we update the collector? m_update_collector_interval = param_integer ("CREDD_UPDATE_INTERVAL", 5 * MINUTE); // fill in our classad initialize_classad(); // reset the timer (if it exists) to update the collector if (m_update_collector_tid != -1) { daemonCore->Reset_Timer(m_update_collector_tid, 0, m_update_collector_interval); } } void CredDaemon::sweep_timer_handler( void ) { dprintf(D_ALWAYS, "ZKM: sweep_timer_handler()\n"); credmon_sweep_creds(); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 30); daemonCore->Reset_Timer (m_cred_sweep_tid, sec_cred_sweep_interval, sec_cred_sweep_interval); } void CredDaemon::initialize_classad() { m_classad.Clear(); SetMyTypeName(m_classad, CREDD_ADTYPE); SetTargetTypeName(m_classad, ""); MyString line; line.formatstr("%s = \"%s\"", ATTR_NAME, m_name ); m_classad.Insert(line.Value()); line.formatstr ("%s = \"%s\"", ATTR_CREDD_IP_ADDR, daemonCore->InfoCommandSinfulString() ); m_classad.Insert(line.Value()); // Publish all DaemonCore-specific attributes, which also handles // SUBSYS_ATTRS for us. daemonCore->publish(&m_classad); } void CredDaemon::update_collector() { daemonCore->sendUpdates(UPDATE_AD_GENERIC, &m_classad, NULL, true); } void CredDaemon::invalidate_ad() { ClassAd query_ad; SetMyTypeName(query_ad, QUERY_ADTYPE); SetTargetTypeName(query_ad, CREDD_ADTYPE); MyString line; line.formatstr("%s = TARGET.%s == \"%s\"", ATTR_REQUIREMENTS, ATTR_NAME, m_name); query_ad.Insert(line.Value()); query_ad.Assign(ATTR_NAME,m_name); daemonCore->sendUpdates(INVALIDATE_ADS_GENERIC, &query_ad, NULL, true); } void CredDaemon::nop_handler(int, Stream*) { return; } void CredDaemon::refresh_all_handler( int, Stream* s) { ReliSock* r = (ReliSock*)s; r->decode(); ClassAd ad; getClassAd(r, ad); r->end_of_message(); // don't actually care (at the moment) what's in the ad, it's for // forward/backward compatibility. // refresh ALL credentials credmon_signal_and_poll( NULL ); r->encode(); ad.Assign("result", "success"); dprintf(D_ALWAYS, "ZKM: sending ad:\n"); dPrintAd(D_ALWAYS, ad); putClassAd(r, ad); r->end_of_message(); dprintf(D_ALWAYS, "ZKM: done!\n"); } //------------------------------------------------------------- void main_init(int /*argc*/, char */*argv*/[]) { dprintf(D_ALWAYS, "main_init() called\n"); credd = new CredDaemon; } //------------------------------------------------------------- void main_config() { dprintf(D_ALWAYS, "main_config() called\n"); credd->reconfig(); } //------------------------------------------------------------- void main_shutdown_fast() { dprintf(D_ALWAYS, "main_shutdown_fast() called\n"); delete credd; DC_Exit(0); } //------------------------------------------------------------- void main_shutdown_graceful() { dprintf(D_ALWAYS, "main_shutdown_graceful() called\n"); delete credd; DC_Exit(0); } //------------------------------------------------------------- int main( int argc, char **argv ) { set_mySubSystem( "CREDD", SUBSYSTEM_TYPE_DAEMON ); dc_main_init = main_init; dc_main_config = main_config; dc_main_shutdown_fast = main_shutdown_fast; dc_main_shutdown_graceful = main_shutdown_graceful; return dc_main( argc, argv ); } <commit_msg>Check return value of credmon_signal_and_poll and propagate to classad. #5338<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "credd.h" #include "condor_config.h" #include "condor_daemon_core.h" #include "condor_debug.h" #include "store_cred.h" #include "internet.h" #include "get_daemon_name.h" #include "subsystem_info.h" #include "credmon_interface.h" //------------------------------------------------------------- CredDaemon *credd; CredDaemon::CredDaemon() : m_name(NULL), m_update_collector_tid(-1) { reconfig(); // Command handler for the user condor_store_cred tool daemonCore->Register_Command( STORE_CRED, "STORE_CRED", (CommandHandler)&store_cred_handler, "store_cred_handler", NULL, WRITE, D_FULLDEBUG ); // Command handler for daemons to get the password daemonCore->Register_Command( CREDD_GET_PASSWD, "CREDD_GET_PASSWD", (CommandHandler)&get_cred_handler, "get_cred_handler", NULL, DAEMON, D_FULLDEBUG ); // NOP command for testing authentication daemonCore->Register_Command( CREDD_NOP, "CREDD_NOP", (CommandHandlercpp)&CredDaemon::nop_handler, "nop_handler", this, DAEMON, D_FULLDEBUG ); // NOP command for testing authentication daemonCore->Register_Command( CREDD_REFRESH_ALL, "CREDD_REFRESH_ALL", (CommandHandlercpp)&CredDaemon::refresh_all_handler, "refresh_all_handler", this, DAEMON, D_FULLDEBUG ); // set timer to periodically advertise ourself to the collector daemonCore->Register_Timer(0, m_update_collector_interval, (TimerHandlercpp)&CredDaemon::update_collector, "update_collector", this); // only sweep if we have a cred dir char* p = param("SEC_CREDENTIAL_DIRECTORY"); if(p) { // didn't need the value, just to see if it's defined. free(p); dprintf(D_ALWAYS, "ZKM: setting sweep_timer_handler\n"); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 30); m_cred_sweep_tid = daemonCore->Register_Timer( sec_cred_sweep_interval, sec_cred_sweep_interval, (TimerHandlercpp)&CredDaemon::sweep_timer_handler, "sweep_timer_handler", this ); } } CredDaemon::~CredDaemon() { // tell our collector we're going away invalidate_ad(); if (m_name != NULL) { free(m_name); } } void CredDaemon::reconfig() { // get our daemon name; if CREDD_HOST is defined, we use it // as our name. this is because clients that have CREDD_HOST // defined will query the Collector for a CredD ad that has // a name matching its setting for CREDD_HOST. but CREDD_HOST // will not necessarily match what default_daemon_name() // returns - for example, if CREDD_HOST is set to a DNS alias // if (m_name != NULL) { free(m_name); } m_name = param("CREDD_HOST"); if (m_name == NULL) { char* tmp = default_daemon_name(); ASSERT(tmp != NULL); m_name = strdup(tmp); ASSERT(m_name != NULL); delete[] tmp; } if(m_name == NULL) { EXCEPT("default_daemon_name() returned NULL"); } // how often do we update the collector? m_update_collector_interval = param_integer ("CREDD_UPDATE_INTERVAL", 5 * MINUTE); // fill in our classad initialize_classad(); // reset the timer (if it exists) to update the collector if (m_update_collector_tid != -1) { daemonCore->Reset_Timer(m_update_collector_tid, 0, m_update_collector_interval); } } void CredDaemon::sweep_timer_handler( void ) { dprintf(D_ALWAYS, "ZKM: sweep_timer_handler()\n"); credmon_sweep_creds(); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 30); daemonCore->Reset_Timer (m_cred_sweep_tid, sec_cred_sweep_interval, sec_cred_sweep_interval); } void CredDaemon::initialize_classad() { m_classad.Clear(); SetMyTypeName(m_classad, CREDD_ADTYPE); SetTargetTypeName(m_classad, ""); MyString line; line.formatstr("%s = \"%s\"", ATTR_NAME, m_name ); m_classad.Insert(line.Value()); line.formatstr ("%s = \"%s\"", ATTR_CREDD_IP_ADDR, daemonCore->InfoCommandSinfulString() ); m_classad.Insert(line.Value()); // Publish all DaemonCore-specific attributes, which also handles // SUBSYS_ATTRS for us. daemonCore->publish(&m_classad); } void CredDaemon::update_collector() { daemonCore->sendUpdates(UPDATE_AD_GENERIC, &m_classad, NULL, true); } void CredDaemon::invalidate_ad() { ClassAd query_ad; SetMyTypeName(query_ad, QUERY_ADTYPE); SetTargetTypeName(query_ad, CREDD_ADTYPE); MyString line; line.formatstr("%s = TARGET.%s == \"%s\"", ATTR_REQUIREMENTS, ATTR_NAME, m_name); query_ad.Insert(line.Value()); query_ad.Assign(ATTR_NAME,m_name); daemonCore->sendUpdates(INVALIDATE_ADS_GENERIC, &query_ad, NULL, true); } void CredDaemon::nop_handler(int, Stream*) { return; } void CredDaemon::refresh_all_handler( int, Stream* s) { ReliSock* r = (ReliSock*)s; r->decode(); ClassAd ad; getClassAd(r, ad); r->end_of_message(); // don't actually care (at the moment) what's in the ad, it's for // forward/backward compatibility. // refresh ALL credentials if(credmon_signal_and_poll( NULL )) { ad.Assign("result", "success"); } else { ad.Assign("result", "failure"); } r->encode(); dprintf(D_ALWAYS, "ZKM: sending ad:\n"); dPrintAd(D_ALWAYS, ad); putClassAd(r, ad); r->end_of_message(); dprintf(D_ALWAYS, "ZKM: done!\n"); } //------------------------------------------------------------- void main_init(int /*argc*/, char */*argv*/[]) { dprintf(D_ALWAYS, "main_init() called\n"); credd = new CredDaemon; } //------------------------------------------------------------- void main_config() { dprintf(D_ALWAYS, "main_config() called\n"); credd->reconfig(); } //------------------------------------------------------------- void main_shutdown_fast() { dprintf(D_ALWAYS, "main_shutdown_fast() called\n"); delete credd; DC_Exit(0); } //------------------------------------------------------------- void main_shutdown_graceful() { dprintf(D_ALWAYS, "main_shutdown_graceful() called\n"); delete credd; DC_Exit(0); } //------------------------------------------------------------- int main( int argc, char **argv ) { set_mySubSystem( "CREDD", SUBSYSTEM_TYPE_DAEMON ); dc_main_init = main_init; dc_main_config = main_config; dc_main_shutdown_fast = main_shutdown_fast; dc_main_shutdown_graceful = main_shutdown_graceful; return dc_main( argc, argv ); } <|endoftext|>
<commit_before>#include "include/parser.hh" #include <iostream> // class unittest // { // public: // unittest(); // ~unittest(); // }; #include <fstream> template <class T, class U> std::ostream& operator << ( std::ostream& o, const std::map<T, U> &m) { for (auto &e : m) { o << e.first << ":\n" << e.second << std::endl; } return o; } int main(int argc, char const *argv[]) { optionparser::parser p; p.add_option("--help", "-h", optionparser::store_true); p.add_option("--file", "-f", optionparser::store_value); p.add_option("--save", "-s", optionparser::store_value); p.eat_arguments(argc, argv); double lrn = p.get_value<double>("save"); std::cout << "retrieved value for save is " << lrn << std::endl; return 0; }<commit_msg>generic value pulling<commit_after>#include "include/parser.hh" #include <iostream> // class unittest // { // public: // unittest(); // ~unittest(); // }; #include <fstream> template <class T, class U> std::ostream& operator << ( std::ostream& o, const std::map<T, U> &m) { for (auto &e : m) { o << e.first << ":\n" << e.second << std::endl; } return o; } int main(int argc, char const *argv[]) { optionparser::parser p; p.add_option("--help", "-h", optionparser::store_true); p.add_option("--file", "-f", optionparser::store_value); p.add_option("--save", "-s", optionparser::store_value); p.eat_arguments(argc, argv); if(p.get_value("help")) { std::cout << "help passed!" << std::endl; } double lrn = p.get_value<double>("save"); std::cout << "retrieved value for 2 * save is " << 2*lrn << std::endl; return 0; }<|endoftext|>
<commit_before>#include "stdsneezy.h" #include "database.h" #include <vector> #include <string> #include "cgicc/Cgicc.h" #include "cgicc/HTTPHTMLHeader.h" #include "cgicc/HTMLClasses.h" using namespace cgicc; void print_form() { cout << "<form method=post action=\"/low/objlog.cgi\">" << endl; cout << "Filter on Object Name: <input type=text name=name><br>" << endl; cout << "Filter on Object VNum: <input type=text name=vnum><br>" << endl; cout << "<input type=hidden name=start value=1" << ">"; cout << "<input type=submit><br>" << endl; cout << "Notes:<br>" << endl; cout << "1. Leaving both fields blank will list all entries in the log.<br>" << endl; cout << "2. The object name field should use the % wildcard character. Example: %shield%<br>" << endl; cout << "3. If both fields are filled in, the script ignores the VNum field.<br>" << endl; } int main(int argc, char **argv) { Cgicc cgi; TDatabase db(DB_SNEEZYPROD); // TDatabase db(DB_SNEEZYBETA); toggleInfo.loadToggles(); form_iterator name = cgi.getElement("name"); form_iterator vnum = cgi.getElement("vnum"); form_iterator start = cgi.getElement("start"); if (start == cgi.getElements().end()) { cout << HTTPHTMLHeader() << endl; cout << html() << head(title("Object Load Logs")) << endl; cout << body() << endl; print_form(); cout << body() << endl; } else { cout << HTTPHTMLHeader() << endl; cout << html() << head(title("Object Load Logs")) << endl; cout << body() << endl; print_form(); cout << "<table border=1>" << endl; cout << " <tr>" << endl; cout << " <th align center>VNum</th>" << endl; cout << " <th align center>Object Name</th>" << endl; cout << " <th align center>Loadtime</th>" << endl; cout << " <th align center>Count</th>" << endl; cout << " </tr>" << endl; if ((**vnum).empty() && (**name).empty()) { db.query("select l.vnum, o.name, l.loadtime, l.objcount from objlog l, obj o where l.vnum = o.vnum order by l.loadtime"); } else if ((**vnum).empty()) { db.query("select l.vnum, o.name, l.loadtime, l.objcount from objlog l, obj o where l.vnum = o.vnum and o.name like '%s' order by l.loadtime", (**name).c_str()); } else if ((**name).empty()) { db.query("select l.vnum, o.name, l.loadtime, l.objcount from objlog l, obj o where l.vnum = o.vnum and l.vnum=%i order by l.loadtime", convertTo<int>(**vnum)); } while(db.fetchRow()){ cout << " <tr valign=top>" << endl; cout << " <td align=right>" << stripColorCodes(db["vnum"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["name"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["loadtime"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["objcount"]) << "</td>" << endl; cout << " </tr>" << endl; } cout << "</table>" << endl; cout << body() << endl; } cout << html() << endl; } <commit_msg>Changed the queries to reduct the precision of the timestamp field.<commit_after>#include "stdsneezy.h" #include "database.h" #include <vector> #include <string> #include "cgicc/Cgicc.h" #include "cgicc/HTTPHTMLHeader.h" #include "cgicc/HTMLClasses.h" using namespace cgicc; void print_form() { cout << "<form method=post action=\"/low/objlog.cgi\">" << endl; cout << "Filter on Object Name: <input type=text name=name><br>" << endl; cout << "Filter on Object VNum: <input type=text name=vnum><br>" << endl; cout << "<input type=hidden name=start value=1" << ">"; cout << "<input type=submit><br>" << endl; cout << "Notes:<br>" << endl; cout << "1. Leaving both fields blank will list all entries in the log.<br>" << endl; cout << "2. The object name field should use the % wildcard character. Example: %shield%<br>" << endl; cout << "3. If both fields are filled in, the script ignores the VNum field.<br>" << endl; } int main(int argc, char **argv) { Cgicc cgi; TDatabase db(DB_SNEEZYPROD); // TDatabase db(DB_SNEEZYBETA); toggleInfo.loadToggles(); form_iterator name = cgi.getElement("name"); form_iterator vnum = cgi.getElement("vnum"); form_iterator start = cgi.getElement("start"); if (start == cgi.getElements().end()) { cout << HTTPHTMLHeader() << endl; cout << html() << head(title("Object Load Logs")) << endl; cout << body() << endl; print_form(); cout << body() << endl; } else { cout << HTTPHTMLHeader() << endl; cout << html() << head(title("Object Load Logs")) << endl; cout << body() << endl; print_form(); cout << "<table border=1>" << endl; cout << " <tr>" << endl; cout << " <th align center>VNum</th>" << endl; cout << " <th align center>Object Name</th>" << endl; cout << " <th align center>Loadtime</th>" << endl; cout << " <th align center>Count</th>" << endl; cout << " </tr>" << endl; if ((**vnum).empty() && (**name).empty()) { db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum order by l.loadtime"); } else if ((**vnum).empty()) { db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum and o.name like '%s' order by l.loadtime", (**name).c_str()); } else if ((**name).empty()) { db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum and l.vnum=%i order by l.loadtime", convertTo<int>(**vnum)); } while(db.fetchRow()){ cout << " <tr valign=top>" << endl; cout << " <td align=right>" << stripColorCodes(db["vnum"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["name"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["loadtime"]) << "</td>" << endl; cout << " <td align=right>" << stripColorCodes(db["objcount"]) << "</td>" << endl; cout << " </tr>" << endl; } cout << "</table>" << endl; cout << body() << endl; } cout << html() << endl; } <|endoftext|>
<commit_before>/** * Copyright (C) 2015 Bitcoin Spinoff Toolkit developers * * 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 <iostream> #include <bitcoin/bitcoin.hpp> #include "bitcoin/bst/generate.h" using namespace std; void test_signing_check() { string testEncodedAddress = "15BWWGJRtB8Z9NXmMAp94whujUK6SrmRwT"; string messageToSign = "hey there"; string signatureString = "HxXI251uSorWtrqkZejCljYlU+6s861evqN6u3IyYJVSaqYooYzvuSCf6TA0B+wJDOkqljz0fQgkvKjJHiBJgRg="; string result = bst::getVerificationMessage(testEncodedAddress, messageToSign, signatureString); cout << result << endl; } void test_recover_signature() { string testEncodedAddress = "15BWWGJRtB8Z9NXmMAp94whujUK6SrmRwT"; string messageToSign = "hey there"; string signatureString = "HxXI251uSorWtrqkZejCljYlU+6s861evqN6u3IyYJVSaqYooYzvuSCf6TA0B+wJDOkqljz0fQgkvKjJHiBJgRg="; cout << testEncodedAddress << endl; vector<uint8_t> paymentVector = vector<uint8_t>(20); bool result = bst::recover_address(messageToSign, signatureString, paymentVector); bc::short_hash sh; copy(paymentVector.begin(), paymentVector.end(), sh.begin()); bc::payment_address address(0, sh); cout << result << " " << address.encoded() << endl; } void test_string_encode_decode() { string vectorString = "01AF0F10"; vector<uint8_t> testVec; bst::decodeVector(vectorString, testVec); stringstream ss; bst::prettyPrintVector(testVec, ss); string s = ss.str(); cout << vectorString << endl << s << endl; } void test_string_encode_decode2() { string vectorString = "992fa68a35e9706f5ce12036803df00ff3003dc6"; vector<uint8_t> testVec; bst::decodeVector(vectorString, testVec); stringstream ss; bst::prettyPrintVector(testVec, ss); string s = ss.str(); cout << vectorString << endl << s << endl; } void test_address_encoding() { string short_hash = "992fa68a35e9706f5ce12036803df00ff3003dc6"; vector<uint8_t> hashVec; bst::decodeVector(short_hash, hashVec); bc::short_hash sh; copy(hashVec.begin(), hashVec.end(), sh.begin()); bc::payment_address address(111, sh); cout << address.encoded(); } void test_store_p2pkhs() { string transaction1 = "76A9142345FBB2B00E115C98C1D6E975C99B5431DE9CDE88AC"; string transaction2 = "76A914992FA68A35E9706F5CE12036803DF00FF3003DC688AC"; vector<uint8_t> vector1; vector<uint8_t> vector2; bst::decodeVector(transaction1, vector1); bst::decodeVector(transaction2, vector2); bst::snapshot_preparer preparer; bst::prepareForUTXOs(preparer); bst::writeUTXO(preparer, vector1, 24900000000); bst::writeUTXO(preparer, vector2, 99998237); vector<uint8_t> block_hash = vector<uint8_t>(32); bst::writeSnapshot(preparer, block_hash); bst::printSnapshot(); } void test_store_and_claim() { string transaction1 = "76A9142345FBB2B00E115C98C1D6E975C99B5431DE9CDE88AC"; string transaction2 = "76A914992FA68A35E9706F5CE12036803DF00FF3003DC688AC"; string transaction3 = "2102f91ca5628d8a77fbf8e12fd098fdd871bdcb61c84cc3abf111a747b26ff6a2cbac"; vector<uint8_t> vector1; vector<uint8_t> vector2; vector<uint8_t> vector3; bst::decodeVector(transaction1, vector1); bst::decodeVector(transaction2, vector2); bst::decodeVector(transaction3, vector3); bst::snapshot_preparer preparer; bst::prepareForUTXOs(preparer); bst::writeUTXO(preparer, vector1, 24900000000); bst::writeUTXO(preparer, vector2, 99998237); bst::writeUTXO(preparer, vector3, 5000000643); vector<uint8_t> block_hash = vector<uint8_t>(32); bst::writeSnapshot(preparer, block_hash); string claim = "I claim funds."; string signature = "Hxc0sSkslD2mFE3HtHzIDRqSutQBiAQ+TxrsgVPeL3jWbXtcusuD77MTX7Tc/hJsQtVrbZsf9xpSDs+6Khx7nNk="; string signature2 = "H3ys4y9vnG2cvneZMo33Vvv1kQTKr2iCcBZZe78OFl8VaPbXYNwLVTtTh5K7Qu4MpdOQiVo+6SHq6pPSzdBm7PQ="; string signature3 = "IIuXyLFeU+HVJnv9TPAGXnCnc0bCOi+enwjIWxsO5FmaMdVNBcRrkYGB07Qbdkghd+0XhnaUL3O+X+h4dzb0Kio="; bst::snapshot_reader reader; bst::openSnapshot(reader); uint64_t amount = bst::getP2PKHAmount(reader, claim, signature); cout << "found amount " << amount << endl; amount = bst::getP2PKHAmount(reader, claim, signature2); cout << "found amount " << amount << endl; amount = bst::getP2PKHAmount(reader, claim, signature3); cout << "found amount " << amount << endl; } int main() { test_store_and_claim(); return 0; }<commit_msg>adding in multisig test<commit_after>/** * Copyright (C) 2015 Bitcoin Spinoff Toolkit developers * * 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 <iostream> #include <bitcoin/bitcoin.hpp> #include "bitcoin/bst/generate.h" using namespace std; void test_signing_check() { string testEncodedAddress = "15BWWGJRtB8Z9NXmMAp94whujUK6SrmRwT"; string messageToSign = "hey there"; string signatureString = "HxXI251uSorWtrqkZejCljYlU+6s861evqN6u3IyYJVSaqYooYzvuSCf6TA0B+wJDOkqljz0fQgkvKjJHiBJgRg="; string result = bst::getVerificationMessage(testEncodedAddress, messageToSign, signatureString); cout << result << endl; } void test_recover_signature() { string testEncodedAddress = "15BWWGJRtB8Z9NXmMAp94whujUK6SrmRwT"; string messageToSign = "hey there"; string signatureString = "HxXI251uSorWtrqkZejCljYlU+6s861evqN6u3IyYJVSaqYooYzvuSCf6TA0B+wJDOkqljz0fQgkvKjJHiBJgRg="; cout << testEncodedAddress << endl; vector<uint8_t> paymentVector = vector<uint8_t>(20); bool result = bst::recover_address(messageToSign, signatureString, paymentVector); bc::short_hash sh; copy(paymentVector.begin(), paymentVector.end(), sh.begin()); bc::payment_address address(0, sh); cout << result << " " << address.encoded() << endl; } void test_string_encode_decode() { string vectorString = "01AF0F10"; vector<uint8_t> testVec; bst::decodeVector(vectorString, testVec); stringstream ss; bst::prettyPrintVector(testVec, ss); string s = ss.str(); cout << vectorString << endl << s << endl; } void test_string_encode_decode2() { string vectorString = "992fa68a35e9706f5ce12036803df00ff3003dc6"; vector<uint8_t> testVec; bst::decodeVector(vectorString, testVec); stringstream ss; bst::prettyPrintVector(testVec, ss); string s = ss.str(); cout << vectorString << endl << s << endl; } void test_address_encoding() { string short_hash = "992fa68a35e9706f5ce12036803df00ff3003dc6"; vector<uint8_t> hashVec; bst::decodeVector(short_hash, hashVec); bc::short_hash sh; copy(hashVec.begin(), hashVec.end(), sh.begin()); bc::payment_address address(111, sh); cout << address.encoded(); } void test_store_p2pkhs() { string transaction1 = "76A9142345FBB2B00E115C98C1D6E975C99B5431DE9CDE88AC"; string transaction2 = "76A914992FA68A35E9706F5CE12036803DF00FF3003DC688AC"; vector<uint8_t> vector1; vector<uint8_t> vector2; bst::decodeVector(transaction1, vector1); bst::decodeVector(transaction2, vector2); bst::snapshot_preparer preparer; bst::prepareForUTXOs(preparer); bst::writeUTXO(preparer, vector1, 24900000000); bst::writeUTXO(preparer, vector2, 99998237); vector<uint8_t> block_hash = vector<uint8_t>(32); bst::writeSnapshot(preparer, block_hash); bst::printSnapshot(); } void test_store_and_claim() { string transaction1 = "76A9142345FBB2B00E115C98C1D6E975C99B5431DE9CDE88AC"; string transaction2 = "76A914992FA68A35E9706F5CE12036803DF00FF3003DC688AC"; string transaction3 = "2102f91ca5628d8a77fbf8e12fd098fdd871bdcb61c84cc3abf111a747b26ff6a2cbac"; vector<uint8_t> vector1; vector<uint8_t> vector2; vector<uint8_t> vector3; bst::decodeVector(transaction1, vector1); bst::decodeVector(transaction2, vector2); bst::decodeVector(transaction3, vector3); bst::snapshot_preparer preparer; bst::prepareForUTXOs(preparer); bst::writeUTXO(preparer, vector1, 24900000000); bst::writeUTXO(preparer, vector2, 99998237); bst::writeUTXO(preparer, vector3, 5000000643); vector<uint8_t> block_hash = vector<uint8_t>(32); bst::writeSnapshot(preparer, block_hash); string claim = "I claim funds."; string signature = "Hxc0sSkslD2mFE3HtHzIDRqSutQBiAQ+TxrsgVPeL3jWbXtcusuD77MTX7Tc/hJsQtVrbZsf9xpSDs+6Khx7nNk="; string signature2 = "H3ys4y9vnG2cvneZMo33Vvv1kQTKr2iCcBZZe78OFl8VaPbXYNwLVTtTh5K7Qu4MpdOQiVo+6SHq6pPSzdBm7PQ="; string signature3 = "IIuXyLFeU+HVJnv9TPAGXnCnc0bCOi+enwjIWxsO5FmaMdVNBcRrkYGB07Qbdkghd+0XhnaUL3O+X+h4dzb0Kio="; bst::snapshot_reader reader; bst::openSnapshot(reader); uint64_t amount = bst::getP2PKHAmount(reader, claim, signature); cout << "found amount " << amount << endl; amount = bst::getP2PKHAmount(reader, claim, signature2); cout << "found amount " << amount << endl; amount = bst::getP2PKHAmount(reader, claim, signature3); cout << "found amount " << amount << endl; } void test_validate_multisig() { string transaction_string = "0100000001a9dd2ae0a5d513a336a2c61db3472e260443eb79ffbd07e154829574c1fa2f3901000000fc00" "473044022062b5798436e9524c267f5c03c0601743db0cd3e57722c87a48a51d3af4089ccc02200f00f9e244e1fc6fa8141a4e90fa" "43b0423d5eda7a1d6d9eb6f6a375337ceda30147304402204ae544e90a9cdf70db7a571cc44a7dcdc0c9f5cbffea6172d7d8ef625d" "ea0758022074c3fa6437c60a762dd49075d80855eec78ea27fafff5e78fb70e07985c9f833014c69522102f91ca5628d8a77fbf8e1" "2fd098fdd871bdcb61c84cc3abf111a747b26ff6a2cb2103b708d33d5452ce8232fe096220ad2aaea4aa68ce0f0869e6321e93c88c" "f5ce082103917f030d239db795047bb5eb66713838221134e103eee2da5619c0cd938e6f6953aeffffffff0170c9fa020000000019" "76a914f2f5bbdea2763591bb5c7552df7d6fe46204bc7588ac00000000"; bc::data_chunk transaction_chunk; bc::decode_base16(transaction_chunk, transaction_string); bc::transaction_type transaction; bc::satoshi_load(transaction_chunk.begin(), transaction_chunk.end(), transaction); string output_string = "a91489a16fbc4929fc7c83ada40641411c09fe4b76d887"; bc::data_chunk output_chunk; bc::decode_base16(output_chunk, output_string); bc::script_type output_script = bc::parse_script(output_chunk); bc::script_type input_script = transaction.inputs[0].script; bool result = output_script.run(input_script, transaction, 0); cout << bc::pretty(transaction) << endl; cout << bc::pretty(output_script) << endl; cout << "result " << result << endl; } int main() { test_validate_multisig(); return 0; }<|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef CONTAINERS_COUNTED_HPP_ #define CONTAINERS_COUNTED_HPP_ #include <stddef.h> #include <stdint.h> #include <utility> #include <memory> #include "containers/scoped.hpp" #include "errors.hpp" #include "threading.hpp" // Yes, this is a clone of boost::intrusive_ptr. This will probably // not be the case in the future. // Now it supports .unique(), and in order to use it, your type needs // to provide an counted_use_count implementation. template <class T> class counted_t { public: template <class U> friend class counted_t; counted_t() : p_(NULL) { } explicit counted_t(T *p) : p_(p) { if (p_ != nullptr) { counted_add_ref(p_); } } explicit counted_t(scoped_ptr_t<T> &&p) : p_(p.release()) { if (p_ != nullptr) { counted_add_ref(p_); } } counted_t(const counted_t &copyee) : p_(copyee.p_) { if (p_ != nullptr) { counted_add_ref(p_); } } counted_t(counted_t &&movee) noexcept : p_(std::move(movee.p_)) { movee.p_ = nullptr; } template <class U> counted_t(counted_t<U> &&movee) noexcept : p_(std::move(movee.p_)) { movee.p_ = nullptr; } // Avoid a spurious warning when building on Saucy. See issue #1674 #if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 408) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif ~counted_t() { if (p_) { counted_release(p_); } } #if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 408) #pragma GCC diagnostic pop #endif void swap(counted_t &other) noexcept { T *tmp = p_; p_ = other.p_; other.p_ = tmp; } counted_t &operator=(counted_t &&other) noexcept { counted_t tmp(std::move(other)); swap(tmp); return *this; } template <class U> counted_t &operator=(counted_t<U> &&other) noexcept { counted_t tmp(std::move(other)); swap(tmp); return *this; } counted_t &operator=(const counted_t &other) { counted_t tmp(other); swap(tmp); return *this; } void reset() { counted_t tmp; swap(tmp); } void reset(T *other) { counted_t tmp(other); swap(tmp); } T *operator->() const { return p_; } T &operator*() const { return *p_; } T *get() const { return p_; } bool has() const { return p_ != NULL; } bool unique() const { return counted_use_count(p_) == 1; } explicit operator bool() const { return p_ != NULL; } private: T *p_; }; struct deallocator_base_t { public: virtual ~deallocator_base_t() {} virtual void deallocate() = 0; }; template <class Alloc> struct deallocator_alloc_t : public deallocator_base_t { typedef std::allocator_traits<Alloc> traits; typename traits::pointer object; Alloc allocator; deallocator_alloc_t(Alloc allocator_, typename traits::pointer object_) : deallocator_base_t(), allocator(allocator_), object(object_) {} virtual void deallocate() { traits::deallocate(allocator, object, 1); } }; template <class T, class... Args> counted_t<T> make_counted(Args &&... args) { return counted_t<T>(new T(std::forward<Args>(args)...)); } template <class T, class Alloc, class... Args> counted_t<T> make_counted(std::allocator_arg_t, const Alloc &a, Args &&... args) { typedef std::allocator_traits<Alloc> traits; T* result = traits::allocate(a, 1); try { traits::construct(a, result, std::forward<Args>(args)...); counted_set_deleter(result, std::unique_ptr<deallocator_alloc_t<Alloc> > (new deallocator_alloc_t<Alloc>(a, result))); return counted_t<T>(result); } catch (...) { traits::deallocate(result, 1); throw; } } template <class> class single_threaded_countable_t; template <class T> inline void counted_add_ref(const single_threaded_countable_t<T> *p); template <class T> inline void counted_release(const single_threaded_countable_t<T> *p); template <class T> inline void counted_set_deleter(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); template <class T> inline intptr_t counted_use_count(const single_threaded_countable_t<T> *p); template <class T> class single_threaded_countable_t : private home_thread_mixin_debug_only_t { public: single_threaded_countable_t() : refcount_(0), deleter_() { } protected: counted_t<T> counted_from_this() { assert_thread(); rassert(refcount_ > 0); return counted_t<T>(static_cast<T *>(this)); } counted_t<const T> counted_from_this() const { assert_thread(); rassert(refcount_ > 0); return counted_t<const T>(static_cast<const T *>(this)); } ~single_threaded_countable_t() { assert_thread(); rassert(refcount_ == 0); } private: friend void counted_add_ref<T>(const single_threaded_countable_t<T> *p); friend void counted_release<T>(const single_threaded_countable_t<T> *p); friend void counted_set_deleter<T>(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); friend intptr_t counted_use_count<T>(const single_threaded_countable_t<T> *p); mutable intptr_t refcount_; std::unique_ptr<deallocator_base_t> deleter_; DISABLE_COPYING(single_threaded_countable_t); }; template <class T> inline void counted_add_ref(const single_threaded_countable_t<T> *p) { p->assert_thread(); p->refcount_ += 1; rassert(p->refcount_ > 0); } template <class T> inline void counted_release(const single_threaded_countable_t<T> *p) { p->assert_thread(); rassert(p->refcount_ > 0); --p->refcount_; if (p->refcount_ == 0) { T *realptr = static_cast<T *>(const_cast<single_threaded_countable_t<T> *>(p)); if (p->deleter_) { p->deleter_->deallocate(); } else { delete realptr; } } } template <class T> inline void counted_set_deleter(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d) { p->deleter_ = std::move(d); } template <class T> inline intptr_t counted_use_count(const single_threaded_countable_t<T> *p) { p->assert_thread(); return p->refcount_; } template <class> class slow_atomic_countable_t; template <class T> inline void counted_add_ref(const slow_atomic_countable_t<T> *p); template <class T> inline void counted_release(const slow_atomic_countable_t<T> *p); template <class T> inline void counted_set_deleter(const slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); template <class T> inline intptr_t counted_use_count(const slow_atomic_countable_t<T> *p); template <class T> class slow_atomic_countable_t { public: slow_atomic_countable_t() : refcount_(0) { } protected: ~slow_atomic_countable_t() { rassert(refcount_ == 0); } counted_t<T> counted_from_this() { rassert(counted_use_count(this) > 0); return counted_t<T>(static_cast<T *>(this)); } counted_t<const T> counted_from_this() const { rassert(counted_use_count(this) > 0); return counted_t<const T>(static_cast<const T *>(this)); } private: friend void counted_add_ref<T>(const slow_atomic_countable_t<T> *p); friend void counted_release<T>(const slow_atomic_countable_t<T> *p); friend void counted_set_deleter<T>(const slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); friend intptr_t counted_use_count<T>(const slow_atomic_countable_t<T> *p); mutable intptr_t refcount_; std::unique_ptr<deallocator_base_t> deleter_; DISABLE_COPYING(slow_atomic_countable_t); }; template <class T> inline void counted_add_ref(const slow_atomic_countable_t<T> *p) { DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1); rassert(res > 0); } template <class T> inline void counted_release(const slow_atomic_countable_t<T> *p) { intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1); rassert(res >= 0); if (res == 0) { T *realptr = static_cast<T *>(const_cast<slow_atomic_countable_t<T> *>(p)); if (p->deleter_) { p->deleter_->deallocate(); } else { delete realptr; } } } template <class T> inline void counted_set_deleter(slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d) { p->deleter = std::move(d); } template <class T> inline intptr_t counted_use_count(const slow_atomic_countable_t<T> *p) { // Finally a practical use for volatile. intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_); rassert(tmp > 0); return tmp; } // A noncopyable reference to a reference-counted object. template <class T> class movable_t { public: explicit movable_t(const counted_t<T> &copyee) : ptr_(copyee) { } movable_t(movable_t &&movee) noexcept : ptr_(std::move(movee.ptr_)) { } movable_t &operator=(movable_t &&movee) noexcept { ptr_ = std::move(movee.ptr_); return *this; } void reset() { ptr_.reset(); } T *get() const { return ptr_.get(); } T *operator->() const { return ptr_.get(); } T &operator*() const { return *ptr_; } bool has() const { return ptr_.has(); } private: counted_t<T> ptr_; DISABLE_COPYING(movable_t); }; // Extends an arbitrary object with a slow_atomic_countable_t template<class T> class countable_wrapper_t : public T, public slow_atomic_countable_t<countable_wrapper_t<T> > { public: template <class... Args> explicit countable_wrapper_t(Args &&... args) : T(std::forward<Args>(args)...) { } }; #endif // CONTAINERS_COUNTED_HPP_ <commit_msg>Use make<> rather than dealing with try/catch everywhere.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef CONTAINERS_COUNTED_HPP_ #define CONTAINERS_COUNTED_HPP_ #include <stddef.h> #include <stdint.h> #include <utility> #include <memory> #include "allocation/utils.hpp" #include "containers/scoped.hpp" #include "errors.hpp" #include "threading.hpp" // Yes, this is a clone of boost::intrusive_ptr. This will probably // not be the case in the future. // Now it supports .unique(), and in order to use it, your type needs // to provide an counted_use_count implementation. template <class T> class counted_t { public: template <class U> friend class counted_t; counted_t() : p_(NULL) { } explicit counted_t(T *p) : p_(p) { if (p_ != nullptr) { counted_add_ref(p_); } } explicit counted_t(scoped_ptr_t<T> &&p) : p_(p.release()) { if (p_ != nullptr) { counted_add_ref(p_); } } counted_t(const counted_t &copyee) : p_(copyee.p_) { if (p_ != nullptr) { counted_add_ref(p_); } } counted_t(counted_t &&movee) noexcept : p_(std::move(movee.p_)) { movee.p_ = nullptr; } template <class U> counted_t(counted_t<U> &&movee) noexcept : p_(std::move(movee.p_)) { movee.p_ = nullptr; } // Avoid a spurious warning when building on Saucy. See issue #1674 #if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 408) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif ~counted_t() { if (p_) { counted_release(p_); } } #if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 408) #pragma GCC diagnostic pop #endif void swap(counted_t &other) noexcept { T *tmp = p_; p_ = other.p_; other.p_ = tmp; } counted_t &operator=(counted_t &&other) noexcept { counted_t tmp(std::move(other)); swap(tmp); return *this; } template <class U> counted_t &operator=(counted_t<U> &&other) noexcept { counted_t tmp(std::move(other)); swap(tmp); return *this; } counted_t &operator=(const counted_t &other) { counted_t tmp(other); swap(tmp); return *this; } void reset() { counted_t tmp; swap(tmp); } void reset(T *other) { counted_t tmp(other); swap(tmp); } T *operator->() const { return p_; } T &operator*() const { return *p_; } T *get() const { return p_; } bool has() const { return p_ != NULL; } bool unique() const { return counted_use_count(p_) == 1; } explicit operator bool() const { return p_ != NULL; } private: T *p_; }; struct deallocator_base_t { public: virtual ~deallocator_base_t() {} virtual void deallocate() = 0; }; template <class Alloc> struct deallocator_alloc_t : public deallocator_base_t { typedef std::allocator_traits<Alloc> traits; typename traits::pointer object; Alloc allocator; deallocator_alloc_t(Alloc allocator_, typename traits::pointer object_) : deallocator_base_t(), allocator(allocator_), object(object_) {} virtual void deallocate() { traits::deallocate(allocator, object, 1); } }; template <class T, class... Args> counted_t<T> make_counted(Args &&... args) { return counted_t<T>(new T(std::forward<Args>(args)...)); } template <class T, class Alloc, class... Args> counted_t<T> make_counted(std::allocator_arg_t, const Alloc &a, Args &&... args) { T* result = make<T>(std::allocator_arg, a, std::forward<Args>(args)...); counted_set_deleter(result, std::unique_ptr<deallocator_alloc_t<Alloc> > (new deallocator_alloc_t<Alloc>(a, result))); return counted_t<T>(result); } template <class> class single_threaded_countable_t; template <class T> inline void counted_add_ref(const single_threaded_countable_t<T> *p); template <class T> inline void counted_release(const single_threaded_countable_t<T> *p); template <class T> inline void counted_set_deleter(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); template <class T> inline intptr_t counted_use_count(const single_threaded_countable_t<T> *p); template <class T> class single_threaded_countable_t : private home_thread_mixin_debug_only_t { public: single_threaded_countable_t() : refcount_(0), deleter_() { } protected: counted_t<T> counted_from_this() { assert_thread(); rassert(refcount_ > 0); return counted_t<T>(static_cast<T *>(this)); } counted_t<const T> counted_from_this() const { assert_thread(); rassert(refcount_ > 0); return counted_t<const T>(static_cast<const T *>(this)); } ~single_threaded_countable_t() { assert_thread(); rassert(refcount_ == 0); } private: friend void counted_add_ref<T>(const single_threaded_countable_t<T> *p); friend void counted_release<T>(const single_threaded_countable_t<T> *p); friend void counted_set_deleter<T>(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); friend intptr_t counted_use_count<T>(const single_threaded_countable_t<T> *p); mutable intptr_t refcount_; std::unique_ptr<deallocator_base_t> deleter_; DISABLE_COPYING(single_threaded_countable_t); }; template <class T> inline void counted_add_ref(const single_threaded_countable_t<T> *p) { p->assert_thread(); p->refcount_ += 1; rassert(p->refcount_ > 0); } template <class T> inline void counted_release(const single_threaded_countable_t<T> *p) { p->assert_thread(); rassert(p->refcount_ > 0); --p->refcount_; if (p->refcount_ == 0) { T *realptr = static_cast<T *>(const_cast<single_threaded_countable_t<T> *>(p)); if (p->deleter_) { p->deleter_->deallocate(); } else { delete realptr; } } } template <class T> inline void counted_set_deleter(single_threaded_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d) { p->deleter_ = std::move(d); } template <class T> inline intptr_t counted_use_count(const single_threaded_countable_t<T> *p) { p->assert_thread(); return p->refcount_; } template <class> class slow_atomic_countable_t; template <class T> inline void counted_add_ref(const slow_atomic_countable_t<T> *p); template <class T> inline void counted_release(const slow_atomic_countable_t<T> *p); template <class T> inline void counted_set_deleter(const slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); template <class T> inline intptr_t counted_use_count(const slow_atomic_countable_t<T> *p); template <class T> class slow_atomic_countable_t { public: slow_atomic_countable_t() : refcount_(0) { } protected: ~slow_atomic_countable_t() { rassert(refcount_ == 0); } counted_t<T> counted_from_this() { rassert(counted_use_count(this) > 0); return counted_t<T>(static_cast<T *>(this)); } counted_t<const T> counted_from_this() const { rassert(counted_use_count(this) > 0); return counted_t<const T>(static_cast<const T *>(this)); } private: friend void counted_add_ref<T>(const slow_atomic_countable_t<T> *p); friend void counted_release<T>(const slow_atomic_countable_t<T> *p); friend void counted_set_deleter<T>(const slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d); friend intptr_t counted_use_count<T>(const slow_atomic_countable_t<T> *p); mutable intptr_t refcount_; std::unique_ptr<deallocator_base_t> deleter_; DISABLE_COPYING(slow_atomic_countable_t); }; template <class T> inline void counted_add_ref(const slow_atomic_countable_t<T> *p) { DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1); rassert(res > 0); } template <class T> inline void counted_release(const slow_atomic_countable_t<T> *p) { intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1); rassert(res >= 0); if (res == 0) { T *realptr = static_cast<T *>(const_cast<slow_atomic_countable_t<T> *>(p)); if (p->deleter_) { p->deleter_->deallocate(); } else { delete realptr; } } } template <class T> inline void counted_set_deleter(slow_atomic_countable_t<T> *p, std::unique_ptr<deallocator_base_t> &&d) { p->deleter = std::move(d); } template <class T> inline intptr_t counted_use_count(const slow_atomic_countable_t<T> *p) { // Finally a practical use for volatile. intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_); rassert(tmp > 0); return tmp; } // A noncopyable reference to a reference-counted object. template <class T> class movable_t { public: explicit movable_t(const counted_t<T> &copyee) : ptr_(copyee) { } movable_t(movable_t &&movee) noexcept : ptr_(std::move(movee.ptr_)) { } movable_t &operator=(movable_t &&movee) noexcept { ptr_ = std::move(movee.ptr_); return *this; } void reset() { ptr_.reset(); } T *get() const { return ptr_.get(); } T *operator->() const { return ptr_.get(); } T &operator*() const { return *ptr_; } bool has() const { return ptr_.has(); } private: counted_t<T> ptr_; DISABLE_COPYING(movable_t); }; // Extends an arbitrary object with a slow_atomic_countable_t template<class T> class countable_wrapper_t : public T, public slow_atomic_countable_t<countable_wrapper_t<T> > { public: template <class... Args> explicit countable_wrapper_t(Args &&... args) : T(std::forward<Args>(args)...) { } }; #endif // CONTAINERS_COUNTED_HPP_ <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapCache.h" #include "SkBitmapProvider.h" #include "SkImage.h" #include "SkResourceCache.h" #include "SkMipMap.h" #include "SkPixelRef.h" #include "SkRect.h" /** * Use this for bitmapcache and mipmapcache entries. */ uint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) { uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p'); return (sharedID << 32) | bitmapGenID; } void SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) { SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID)); } /////////////////////////////////////////////////////////////////////////////////////////////////// SkBitmapCacheDesc SkBitmapCacheDesc::Make(uint32_t imageID, const SkIRect& subset) { SkASSERT(imageID); SkASSERT(subset.width() > 0 && subset.height() > 0); return { imageID, subset }; } SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) { SkIRect bounds = SkIRect::MakeWH(image->width(), image->height()); return Make(image->uniqueID(), bounds); } namespace { static unsigned gBitmapKeyNamespaceLabel; struct BitmapKey : public SkResourceCache::Key { public: BitmapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) { this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID), sizeof(fDesc)); } const SkBitmapCacheDesc fDesc; }; } ////////////////////// #include "SkDiscardableMemory.h" #include "SkNextID.h" void SkBitmapCache_setImmutableWithID(SkPixelRef* pr, uint32_t id) { pr->setImmutableWithID(id); } class SkBitmapCache::Rec : public SkResourceCache::Rec { public: Rec(const SkBitmapCacheDesc& desc, const SkImageInfo& info, size_t rowBytes, std::unique_ptr<SkDiscardableMemory> dm, void* block) : fKey(desc) , fDM(std::move(dm)) , fMalloc(block) , fInfo(info) , fRowBytes(rowBytes) , fExternalCounter(kBeforeFirstInstall_ExternalCounter) { SkASSERT(!(fDM && fMalloc)); // can't have both // We need an ID to return with the bitmap/pixelref. We can't necessarily use the key/desc // ID - lazy images cache the same ID with multiple keys (in different color types). fPrUniqueID = SkNextID::ImageID(); } ~Rec() override { SkASSERT(0 == fExternalCounter || kBeforeFirstInstall_ExternalCounter == fExternalCounter); if (fDM && kBeforeFirstInstall_ExternalCounter == fExternalCounter) { // we never installed, so we need to unlock before we destroy the DM SkASSERT(fDM->data()); fDM->unlock(); } sk_free(fMalloc); // may be null } const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + fInfo.computeByteSize(fRowBytes); } bool canBePurged() override { SkAutoMutexAcquire ama(fMutex); return fExternalCounter == 0; } void postAddInstall(void* payload) override { SkAssertResult(this->install(static_cast<SkBitmap*>(payload))); } const char* getCategory() const override { return "bitmap"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return fDM.get(); } static void ReleaseProc(void* addr, void* ctx) { Rec* rec = static_cast<Rec*>(ctx); SkAutoMutexAcquire ama(rec->fMutex); SkASSERT(rec->fExternalCounter > 0); rec->fExternalCounter -= 1; if (rec->fDM) { SkASSERT(rec->fMalloc == nullptr); if (rec->fExternalCounter == 0) { rec->fDM->unlock(); } } else { SkASSERT(rec->fMalloc != nullptr); } } bool install(SkBitmap* bitmap) { SkAutoMutexAcquire ama(fMutex); // are we still valid if (!fDM && !fMalloc) { return false; } /* constructor fExternalCount < 0 fDM->data() after install fExternalCount > 0 fDM->data() after Release fExternalCount == 0 !fDM->data() */ if (fDM) { if (kBeforeFirstInstall_ExternalCounter == fExternalCounter) { SkASSERT(fDM->data()); } else if (fExternalCounter > 0) { SkASSERT(fDM->data()); } else { SkASSERT(fExternalCounter == 0); if (!fDM->lock()) { fDM.reset(nullptr); return false; } } SkASSERT(fDM->data()); } bitmap->installPixels(fInfo, fDM ? fDM->data() : fMalloc, fRowBytes, ReleaseProc, this); SkBitmapCache_setImmutableWithID(bitmap->pixelRef(), fPrUniqueID); if (kBeforeFirstInstall_ExternalCounter == fExternalCounter) { fExternalCounter = 1; } else { fExternalCounter += 1; } SkASSERT(fExternalCounter > 0); return true; } static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) { Rec* rec = (Rec*)&baseRec; SkBitmap* result = (SkBitmap*)contextBitmap; return rec->install(result); } private: BitmapKey fKey; SkMutex fMutex; // either fDM or fMalloc can be non-null, but not both std::unique_ptr<SkDiscardableMemory> fDM; void* fMalloc; SkImageInfo fInfo; size_t fRowBytes; uint32_t fPrUniqueID; // This field counts the number of external pixelrefs we have created. They notify us when // they are destroyed so we can decrement this. // // > 0 we have outstanding pixelrefs // == 0 we have no outstanding pixelrefs, and can be safely purged // < 0 we have been created, but not yet "installed" the first time. // int fExternalCounter; enum { kBeforeFirstInstall_ExternalCounter = -1 }; }; void SkBitmapCache::PrivateDeleteRec(Rec* rec) { delete rec; } SkBitmapCache::RecPtr SkBitmapCache::Alloc(const SkBitmapCacheDesc& desc, const SkImageInfo& info, SkPixmap* pmap) { // Ensure that the info matches the subset (i.e. the subset is the entire image) SkASSERT(info.width() == desc.fSubset.width()); SkASSERT(info.height() == desc.fSubset.height()); const size_t rb = info.minRowBytes(); size_t size = info.computeByteSize(rb); if (SkImageInfo::ByteSizeOverflowed(size)) { return nullptr; } std::unique_ptr<SkDiscardableMemory> dm; void* block = nullptr; auto factory = SkResourceCache::GetDiscardableFactory(); if (factory) { dm.reset(factory(size)); } else { block = sk_malloc_canfail(size); } if (!dm && !block) { return nullptr; } *pmap = SkPixmap(info, dm ? dm->data() : block, rb); return RecPtr(new Rec(desc, info, rb, std::move(dm), block)); } void SkBitmapCache::Add(RecPtr rec, SkBitmap* bitmap) { SkResourceCache::Add(rec.release(), bitmap); } bool SkBitmapCache::Find(const SkBitmapCacheDesc& desc, SkBitmap* result) { desc.validate(); return SkResourceCache::Find(BitmapKey(desc), SkBitmapCache::Rec::Finder, result); } ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// #define CHECK_LOCAL(localCache, localName, globalName, ...) \ ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__)) namespace { static unsigned gMipMapKeyNamespaceLabel; struct MipMapKey : public SkResourceCache::Key { public: MipMapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) { this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID), sizeof(fDesc)); } const SkBitmapCacheDesc fDesc; }; struct MipMapRec : public SkResourceCache::Rec { MipMapRec(const SkBitmapCacheDesc& desc, const SkMipMap* result) : fKey(desc) , fMipMap(result) { fMipMap->attachToCacheAndRef(); } ~MipMapRec() override { fMipMap->detachFromCacheAndUnref(); } const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); } const char* getCategory() const override { return "mipmap"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return fMipMap->diagnostic_only_getDiscardable(); } static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) { const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec); const SkMipMap* mm = SkRef(rec.fMipMap); // the call to ref() above triggers a "lock" in the case of discardable memory, // which means we can now check for null (in case the lock failed). if (nullptr == mm->data()) { mm->unref(); // balance our call to ref() return false; } // the call must call unref() when they are done. *(const SkMipMap**)contextMip = mm; return true; } private: MipMapKey fKey; const SkMipMap* fMipMap; }; } const SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc, SkResourceCache* localCache) { MipMapKey key(desc); const SkMipMap* result; if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) { result = nullptr; } return result; } static SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) { return localCache ? localCache->GetDiscardableFactory() : SkResourceCache::GetDiscardableFactory(); } const SkMipMap* SkMipMapCache::AddAndRef(const SkBitmapProvider& provider, SkResourceCache* localCache) { SkBitmap src; if (!provider.asBitmap(&src)) { return nullptr; } SkMipMap* mipmap = SkMipMap::Build(src, get_fact(localCache)); if (mipmap) { MipMapRec* rec = new MipMapRec(provider.makeCacheDesc(), mipmap); CHECK_LOCAL(localCache, add, Add, rec); provider.notifyAddedToCache(); } return mipmap; } <commit_msg>simplify fExternalCounter bookkeeping<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapCache.h" #include "SkBitmapProvider.h" #include "SkImage.h" #include "SkResourceCache.h" #include "SkMipMap.h" #include "SkPixelRef.h" #include "SkRect.h" /** * Use this for bitmapcache and mipmapcache entries. */ uint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) { uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p'); return (sharedID << 32) | bitmapGenID; } void SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) { SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID)); } /////////////////////////////////////////////////////////////////////////////////////////////////// SkBitmapCacheDesc SkBitmapCacheDesc::Make(uint32_t imageID, const SkIRect& subset) { SkASSERT(imageID); SkASSERT(subset.width() > 0 && subset.height() > 0); return { imageID, subset }; } SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) { SkIRect bounds = SkIRect::MakeWH(image->width(), image->height()); return Make(image->uniqueID(), bounds); } namespace { static unsigned gBitmapKeyNamespaceLabel; struct BitmapKey : public SkResourceCache::Key { public: BitmapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) { this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID), sizeof(fDesc)); } const SkBitmapCacheDesc fDesc; }; } ////////////////////// #include "SkDiscardableMemory.h" #include "SkNextID.h" void SkBitmapCache_setImmutableWithID(SkPixelRef* pr, uint32_t id) { pr->setImmutableWithID(id); } class SkBitmapCache::Rec : public SkResourceCache::Rec { public: Rec(const SkBitmapCacheDesc& desc, const SkImageInfo& info, size_t rowBytes, std::unique_ptr<SkDiscardableMemory> dm, void* block) : fKey(desc) , fDM(std::move(dm)) , fMalloc(block) , fInfo(info) , fRowBytes(rowBytes) { SkASSERT(!(fDM && fMalloc)); // can't have both // We need an ID to return with the bitmap/pixelref. We can't necessarily use the key/desc // ID - lazy images cache the same ID with multiple keys (in different color types). fPrUniqueID = SkNextID::ImageID(); } ~Rec() override { SkASSERT(0 == fExternalCounter); if (fDM && fDiscardableIsLocked) { SkASSERT(fDM->data()); fDM->unlock(); } sk_free(fMalloc); // may be null } const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + fInfo.computeByteSize(fRowBytes); } bool canBePurged() override { SkAutoMutexAcquire ama(fMutex); return fExternalCounter == 0; } void postAddInstall(void* payload) override { SkAssertResult(this->install(static_cast<SkBitmap*>(payload))); } const char* getCategory() const override { return "bitmap"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return fDM.get(); } static void ReleaseProc(void* addr, void* ctx) { Rec* rec = static_cast<Rec*>(ctx); SkAutoMutexAcquire ama(rec->fMutex); SkASSERT(rec->fExternalCounter > 0); rec->fExternalCounter -= 1; if (rec->fDM) { SkASSERT(rec->fMalloc == nullptr); if (rec->fExternalCounter == 0) { rec->fDM->unlock(); rec->fDiscardableIsLocked = false; } } else { SkASSERT(rec->fMalloc != nullptr); } } bool install(SkBitmap* bitmap) { SkAutoMutexAcquire ama(fMutex); if (!fDM && !fMalloc) { return false; } if (fDM) { if (!fDiscardableIsLocked) { SkASSERT(fExternalCounter == 0); if (!fDM->lock()) { fDM.reset(nullptr); return false; } fDiscardableIsLocked = true; } SkASSERT(fDM->data()); } bitmap->installPixels(fInfo, fDM ? fDM->data() : fMalloc, fRowBytes, ReleaseProc, this); SkBitmapCache_setImmutableWithID(bitmap->pixelRef(), fPrUniqueID); fExternalCounter++; return true; } static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) { Rec* rec = (Rec*)&baseRec; SkBitmap* result = (SkBitmap*)contextBitmap; return rec->install(result); } private: BitmapKey fKey; SkMutex fMutex; // either fDM or fMalloc can be non-null, but not both std::unique_ptr<SkDiscardableMemory> fDM; void* fMalloc; SkImageInfo fInfo; size_t fRowBytes; uint32_t fPrUniqueID; // This field counts the number of external pixelrefs we have created. // They notify us when they are destroyed so we can decrement this. int fExternalCounter = 0; bool fDiscardableIsLocked = true; }; void SkBitmapCache::PrivateDeleteRec(Rec* rec) { delete rec; } SkBitmapCache::RecPtr SkBitmapCache::Alloc(const SkBitmapCacheDesc& desc, const SkImageInfo& info, SkPixmap* pmap) { // Ensure that the info matches the subset (i.e. the subset is the entire image) SkASSERT(info.width() == desc.fSubset.width()); SkASSERT(info.height() == desc.fSubset.height()); const size_t rb = info.minRowBytes(); size_t size = info.computeByteSize(rb); if (SkImageInfo::ByteSizeOverflowed(size)) { return nullptr; } std::unique_ptr<SkDiscardableMemory> dm; void* block = nullptr; auto factory = SkResourceCache::GetDiscardableFactory(); if (factory) { dm.reset(factory(size)); } else { block = sk_malloc_canfail(size); } if (!dm && !block) { return nullptr; } *pmap = SkPixmap(info, dm ? dm->data() : block, rb); return RecPtr(new Rec(desc, info, rb, std::move(dm), block)); } void SkBitmapCache::Add(RecPtr rec, SkBitmap* bitmap) { SkResourceCache::Add(rec.release(), bitmap); } bool SkBitmapCache::Find(const SkBitmapCacheDesc& desc, SkBitmap* result) { desc.validate(); return SkResourceCache::Find(BitmapKey(desc), SkBitmapCache::Rec::Finder, result); } ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// #define CHECK_LOCAL(localCache, localName, globalName, ...) \ ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__)) namespace { static unsigned gMipMapKeyNamespaceLabel; struct MipMapKey : public SkResourceCache::Key { public: MipMapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) { this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID), sizeof(fDesc)); } const SkBitmapCacheDesc fDesc; }; struct MipMapRec : public SkResourceCache::Rec { MipMapRec(const SkBitmapCacheDesc& desc, const SkMipMap* result) : fKey(desc) , fMipMap(result) { fMipMap->attachToCacheAndRef(); } ~MipMapRec() override { fMipMap->detachFromCacheAndUnref(); } const Key& getKey() const override { return fKey; } size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); } const char* getCategory() const override { return "mipmap"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return fMipMap->diagnostic_only_getDiscardable(); } static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) { const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec); const SkMipMap* mm = SkRef(rec.fMipMap); // the call to ref() above triggers a "lock" in the case of discardable memory, // which means we can now check for null (in case the lock failed). if (nullptr == mm->data()) { mm->unref(); // balance our call to ref() return false; } // the call must call unref() when they are done. *(const SkMipMap**)contextMip = mm; return true; } private: MipMapKey fKey; const SkMipMap* fMipMap; }; } const SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc, SkResourceCache* localCache) { MipMapKey key(desc); const SkMipMap* result; if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) { result = nullptr; } return result; } static SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) { return localCache ? localCache->GetDiscardableFactory() : SkResourceCache::GetDiscardableFactory(); } const SkMipMap* SkMipMapCache::AddAndRef(const SkBitmapProvider& provider, SkResourceCache* localCache) { SkBitmap src; if (!provider.asBitmap(&src)) { return nullptr; } SkMipMap* mipmap = SkMipMap::Build(src, get_fact(localCache)); if (mipmap) { MipMapRec* rec = new MipMapRec(provider.makeCacheDesc(), mipmap); CHECK_LOCAL(localCache, add, Add, rec); provider.notifyAddedToCache(); } return mipmap; } <|endoftext|>