text
stringlengths
54
60.6k
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "authdb.hh" #include <thread> using namespace soci; void SociAuthDB::declareConfig(GenericStruct *mc) { // ODBC-specific configuration keys ConfigItemDescriptor items[]={ { String, "soci-password-request", "Soci SQL request to execute to obtain the password.\n" "Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, and\n -':authid' : the authorization username.\n" "The use of the :id parameter is mandatory.", "select password from accounts where id = :id and domain = :domain and authid=:authid" }, { Integer, "soci-poolsize", "Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will allow each thread to get a connection.\n" "The threads are blocked until a connection is released back to the pool, so increasing the pool size will allow more connections to occur simultaneously.\n" "On the other hand, you should not keep too many open connections to your DB at the same time.", "100" }, { String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n" "Depending on your Soci package and the modules you installed, this could be 'mysql', 'oracle', 'postgresql' or something else.", "mysql" }, { String, "soci-connection-string", "The configuration parameters of the Soci backend.\n" "The basic format is \"key=value key2=value2\". For a mysql backend, this is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n" "Please refer to the Soci documentation of your backend, for intance: http://soci.sourceforge.net/doc/3.2/backends/mysql.html", "db=mydb user=myuser password='mypass' host=myhost.com" }, config_item_end }; mc->addChildrenValues(items); } SociAuthDB::SociAuthDB() : pool(NULL) { GenericStruct *cr=GenericManager::get()->getRoot(); GenericStruct *ma=cr->get<GenericStruct>("module::Authentication"); poolSize = ma->get< ConfigInt >("soci-poolsize")->read();; connection_string = ma->get<ConfigString>("soci-connection-string")->read(); backend = ma->get<ConfigString>("soci-backend")->read(); get_password_request = ma->get<ConfigString>("soci-password-request")->read(); pool = new connection_pool(poolSize); LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(), (int)poolSize); for( auto i = 0; i<poolSize; i++ ){ pool->at(i).open(backend, connection_string); } } SociAuthDB::~SociAuthDB() { delete pool; } void SociAuthDB::getPasswordWithPool(su_root_t* root, const std::string &id, const std::string &domain, const std::string &authid, AuthDbListener *listener){ // will grab a connection from the pool. This is thread safe session sql(*pool); std::string pass; try { sql << get_password_request, into(pass), use(id,"id"), use(domain, "domain"), use(authid, "authid"); SLOGD << "[SOCI] Got pass for " << id << endl; cachePassword( createPasswordKey(id, domain, authid), domain, pass, mCacheExpire); notifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass); } catch (mysql_soci_error const & e) { SLOGE << "[SOCI] MySQL error: " << e.err_num_ << " " << e.what() << endl; notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass); } catch (exception const & e) { SLOGE << "[SOCI] Some other error: " << e.what() << endl; notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass); } } #pragma mark - Inherited virtuals void SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string& id, const std::string& domain, const std::string& authid, AuthDbListener *listener) { // create a thread to grab a pool connection and use it to retrieve the auth information auto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener); thread t = std::thread(func); t.detach(); return; }<commit_msg>Use size_t instead of auto<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "authdb.hh" #include <thread> using namespace soci; void SociAuthDB::declareConfig(GenericStruct *mc) { // ODBC-specific configuration keys ConfigItemDescriptor items[]={ { String, "soci-password-request", "Soci SQL request to execute to obtain the password.\n" "Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, and\n -':authid' : the authorization username.\n" "The use of the :id parameter is mandatory.", "select password from accounts where id = :id and domain = :domain and authid=:authid" }, { Integer, "soci-poolsize", "Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will allow each thread to get a connection.\n" "The threads are blocked until a connection is released back to the pool, so increasing the pool size will allow more connections to occur simultaneously.\n" "On the other hand, you should not keep too many open connections to your DB at the same time.", "100" }, { String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n" "Depending on your Soci package and the modules you installed, this could be 'mysql', 'oracle', 'postgresql' or something else.", "mysql" }, { String, "soci-connection-string", "The configuration parameters of the Soci backend.\n" "The basic format is \"key=value key2=value2\". For a mysql backend, this is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n" "Please refer to the Soci documentation of your backend, for intance: http://soci.sourceforge.net/doc/3.2/backends/mysql.html", "db=mydb user=myuser password='mypass' host=myhost.com" }, config_item_end }; mc->addChildrenValues(items); } SociAuthDB::SociAuthDB() : pool(NULL) { GenericStruct *cr=GenericManager::get()->getRoot(); GenericStruct *ma=cr->get<GenericStruct>("module::Authentication"); poolSize = ma->get< ConfigInt >("soci-poolsize")->read();; connection_string = ma->get<ConfigString>("soci-connection-string")->read(); backend = ma->get<ConfigString>("soci-backend")->read(); get_password_request = ma->get<ConfigString>("soci-password-request")->read(); pool = new connection_pool(poolSize); LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(), (int)poolSize); for( size_t i = 0; i<poolSize; i++ ){ pool->at(i).open(backend, connection_string); } } SociAuthDB::~SociAuthDB() { delete pool; } void SociAuthDB::getPasswordWithPool(su_root_t* root, const std::string &id, const std::string &domain, const std::string &authid, AuthDbListener *listener){ // will grab a connection from the pool. This is thread safe session sql(*pool); std::string pass; try { sql << get_password_request, into(pass), use(id,"id"), use(domain, "domain"), use(authid, "authid"); SLOGD << "[SOCI] Got pass for " << id << endl; cachePassword( createPasswordKey(id, domain, authid), domain, pass, mCacheExpire); notifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass); } catch (mysql_soci_error const & e) { SLOGE << "[SOCI] MySQL error: " << e.err_num_ << " " << e.what() << endl; notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass); } catch (exception const & e) { SLOGE << "[SOCI] Some other error: " << e.what() << endl; notifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass); } } #pragma mark - Inherited virtuals void SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string& id, const std::string& domain, const std::string& authid, AuthDbListener *listener) { // create a thread to grab a pool connection and use it to retrieve the auth information auto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener); thread t = std::thread(func); t.detach(); return; }<|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Raphael Hiesgen <raphael.hiesgen (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. * ******************************************************************************/ #include <fstream> #include "caf/detail/type_list.hpp" #include "caf/raise_error.hpp" #include "caf/opencl/device.hpp" #include "caf/opencl/manager.hpp" #include "caf/opencl/platform.hpp" #include "caf/opencl/opencl_err.hpp" using namespace std; namespace caf { namespace opencl { optional<device_ptr> manager::find_device(size_t dev_id) const { if (platforms_.empty()) return none; size_t to = 0; for (auto& pl : platforms_) { auto from = to; to += pl->devices().size(); if (dev_id >= from && dev_id < to) return pl->devices()[dev_id - from]; } return none; } void manager::init(actor_system_config&) { // get number of available platforms auto num_platforms = v1get<cl_uint>(CAF_CLF(clGetPlatformIDs)); // get platform ids std::vector<cl_platform_id> platform_ids(num_platforms); v2callcl(CAF_CLF(clGetPlatformIDs), num_platforms, platform_ids.data()); if (platform_ids.empty()) CAF_RAISE_ERROR("no OpenCL platform found"); // initialize platforms (device discovery) unsigned current_device_id = 0; for (auto& pl_id : platform_ids) { platforms_.push_back(platform::create(pl_id, current_device_id)); current_device_id += static_cast<unsigned>(platforms_.back()->devices().size()); } } void manager::start() { // nop } void manager::stop() { // nop } actor_system::module::id_t manager::id() const { return actor_system::module::opencl_manager; } void* manager::subtype_ptr() { return this; } actor_system::module* manager::make(actor_system& sys, caf::detail::type_list<>) { return new manager{sys}; } program_ptr manager::create_program_from_file(const char* path, const char* options, uint32_t device_id) { std::ifstream read_source{std::string(path), std::ios::in}; string kernel_source; if (read_source) { read_source.seekg(0, std::ios::end); kernel_source.resize(static_cast<size_t>(read_source.tellg())); read_source.seekg(0, std::ios::beg); read_source.read(&kernel_source[0], static_cast<streamsize>(kernel_source.size())); read_source.close(); } else { CAF_RAISE_ERROR("create_program_from_file: path not found"); } return create_program(kernel_source.c_str(), options, device_id); } program_ptr manager::create_program(const char* kernel_source, const char* options, uint32_t device_id) { auto dev = find_device(device_id); if (!dev) { CAF_RAISE_ERROR("create_program: no device found"); } return create_program(kernel_source, options, *dev); } program_ptr manager::create_program_from_file(const char* path, const char* options, const device_ptr dev) { std::ifstream read_source{std::string(path), std::ios::in}; string kernel_source; if (read_source) { read_source.seekg(0, std::ios::end); kernel_source.resize(static_cast<size_t>(read_source.tellg())); read_source.seekg(0, std::ios::beg); read_source.read(&kernel_source[0], static_cast<streamsize>(kernel_source.size())); read_source.close(); } else { CAF_RAISE_ERROR("create_program_from_file: path not found"); } return create_program(kernel_source.c_str(), options, dev); } program_ptr manager::create_program(const char* kernel_source, const char* options, const device_ptr dev) { // create program object from kernel source size_t kernel_source_length = strlen(kernel_source); detail::raw_program_ptr pptr; pptr.reset(v2get(CAF_CLF(clCreateProgramWithSource), dev->context_.get(), 1u, &kernel_source, &kernel_source_length), false); // build programm from program object auto dev_tmp = dev->device_id_.get(); auto err = clBuildProgram(pptr.get(), 1, &dev_tmp, options, nullptr, nullptr); if (err != CL_SUCCESS) { ostringstream oss; oss << "clBuildProgram: " << opencl_error(err); if (err == CL_BUILD_PROGRAM_FAILURE) { size_t buildlog_buffer_size = 0; // get the log length clGetProgramBuildInfo(pptr.get(), dev_tmp, CL_PROGRAM_BUILD_LOG, 0, nullptr, &buildlog_buffer_size); vector<char> buffer(buildlog_buffer_size); // fill the buffer with buildlog informations clGetProgramBuildInfo(pptr.get(), dev_tmp, CL_PROGRAM_BUILD_LOG, sizeof(char) * buildlog_buffer_size, buffer.data(), nullptr); ostringstream ss; ss << "############## Build log ##############" << endl << string(buffer.data()) << endl << "#######################################"; // seems that just apple implemented the // pfn_notify callback, but we can get // the build log #ifndef CAF_MACOS CAF_LOG_ERROR(CAF_ARG(ss.str())); #endif oss << endl << ss.str(); } CAF_RAISE_ERROR("clBuildProgram failed"); } cl_uint number_of_kernels = 0; clCreateKernelsInProgram(pptr.get(), 0u, nullptr, &number_of_kernels); map<string, detail::raw_kernel_ptr> available_kernels; if (number_of_kernels > 0) { vector<cl_kernel> kernels(number_of_kernels); err = clCreateKernelsInProgram(pptr.get(), number_of_kernels, kernels.data(), nullptr); if (err != CL_SUCCESS) CAF_RAISE_ERROR("clCreateKernelsInProgram failed"); for (cl_uint i = 0; i < number_of_kernels; ++i) { size_t len; clGetKernelInfo(kernels[i], CL_KERNEL_FUNCTION_NAME, 0, nullptr, &len); vector<char> name(len); err = clGetKernelInfo(kernels[i], CL_KERNEL_FUNCTION_NAME, len, reinterpret_cast<void*>(name.data()), nullptr); if (err != CL_SUCCESS) CAF_RAISE_ERROR("clGetKernelInfo failed"); detail::raw_kernel_ptr kernel; kernel.reset(move(kernels[i])); available_kernels.emplace(string(name.data()), move(kernel)); } } else { CAF_LOG_WARNING("Could not built all kernels in program. Since this happens" " on some platforms, we'll ignore this and try to build" " each kernel individually by name."); } return make_counted<program>(dev->context_, dev->queue_, pptr, move(available_kernels)); } manager::manager(actor_system& sys) : system_(sys) { // nop } manager::~manager() { // nop } } // namespace opencl } // namespace caf <commit_msg>Remove unused variable<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Raphael Hiesgen <raphael.hiesgen (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. * ******************************************************************************/ #include <fstream> #include "caf/detail/type_list.hpp" #include "caf/raise_error.hpp" #include "caf/opencl/device.hpp" #include "caf/opencl/manager.hpp" #include "caf/opencl/platform.hpp" #include "caf/opencl/opencl_err.hpp" using namespace std; namespace caf { namespace opencl { optional<device_ptr> manager::find_device(size_t dev_id) const { if (platforms_.empty()) return none; size_t to = 0; for (auto& pl : platforms_) { auto from = to; to += pl->devices().size(); if (dev_id >= from && dev_id < to) return pl->devices()[dev_id - from]; } return none; } void manager::init(actor_system_config&) { // get number of available platforms auto num_platforms = v1get<cl_uint>(CAF_CLF(clGetPlatformIDs)); // get platform ids std::vector<cl_platform_id> platform_ids(num_platforms); v2callcl(CAF_CLF(clGetPlatformIDs), num_platforms, platform_ids.data()); if (platform_ids.empty()) CAF_RAISE_ERROR("no OpenCL platform found"); // initialize platforms (device discovery) unsigned current_device_id = 0; for (auto& pl_id : platform_ids) { platforms_.push_back(platform::create(pl_id, current_device_id)); current_device_id += static_cast<unsigned>(platforms_.back()->devices().size()); } } void manager::start() { // nop } void manager::stop() { // nop } actor_system::module::id_t manager::id() const { return actor_system::module::opencl_manager; } void* manager::subtype_ptr() { return this; } actor_system::module* manager::make(actor_system& sys, caf::detail::type_list<>) { return new manager{sys}; } program_ptr manager::create_program_from_file(const char* path, const char* options, uint32_t device_id) { std::ifstream read_source{std::string(path), std::ios::in}; string kernel_source; if (read_source) { read_source.seekg(0, std::ios::end); kernel_source.resize(static_cast<size_t>(read_source.tellg())); read_source.seekg(0, std::ios::beg); read_source.read(&kernel_source[0], static_cast<streamsize>(kernel_source.size())); read_source.close(); } else { CAF_RAISE_ERROR("create_program_from_file: path not found"); } return create_program(kernel_source.c_str(), options, device_id); } program_ptr manager::create_program(const char* kernel_source, const char* options, uint32_t device_id) { auto dev = find_device(device_id); if (!dev) { CAF_RAISE_ERROR("create_program: no device found"); } return create_program(kernel_source, options, *dev); } program_ptr manager::create_program_from_file(const char* path, const char* options, const device_ptr dev) { std::ifstream read_source{std::string(path), std::ios::in}; string kernel_source; if (read_source) { read_source.seekg(0, std::ios::end); kernel_source.resize(static_cast<size_t>(read_source.tellg())); read_source.seekg(0, std::ios::beg); read_source.read(&kernel_source[0], static_cast<streamsize>(kernel_source.size())); read_source.close(); } else { CAF_RAISE_ERROR("create_program_from_file: path not found"); } return create_program(kernel_source.c_str(), options, dev); } program_ptr manager::create_program(const char* kernel_source, const char* options, const device_ptr dev) { // create program object from kernel source size_t kernel_source_length = strlen(kernel_source); detail::raw_program_ptr pptr; pptr.reset(v2get(CAF_CLF(clCreateProgramWithSource), dev->context_.get(), 1u, &kernel_source, &kernel_source_length), false); // build programm from program object auto dev_tmp = dev->device_id_.get(); auto err = clBuildProgram(pptr.get(), 1, &dev_tmp, options, nullptr, nullptr); if (err != CL_SUCCESS) { if (err == CL_BUILD_PROGRAM_FAILURE) { size_t buildlog_buffer_size = 0; // get the log length clGetProgramBuildInfo(pptr.get(), dev_tmp, CL_PROGRAM_BUILD_LOG, 0, nullptr, &buildlog_buffer_size); vector<char> buffer(buildlog_buffer_size); // fill the buffer with buildlog informations clGetProgramBuildInfo(pptr.get(), dev_tmp, CL_PROGRAM_BUILD_LOG, sizeof(char) * buildlog_buffer_size, buffer.data(), nullptr); ostringstream ss; ss << "############## Build log ##############" << endl << string(buffer.data()) << endl << "#######################################"; // seems that just apple implemented the // pfn_notify callback, but we can get // the build log #ifndef CAF_MACOS CAF_LOG_ERROR(CAF_ARG(ss.str())); #endif } CAF_RAISE_ERROR("clBuildProgram failed"); } cl_uint number_of_kernels = 0; clCreateKernelsInProgram(pptr.get(), 0u, nullptr, &number_of_kernels); map<string, detail::raw_kernel_ptr> available_kernels; if (number_of_kernels > 0) { vector<cl_kernel> kernels(number_of_kernels); err = clCreateKernelsInProgram(pptr.get(), number_of_kernels, kernels.data(), nullptr); if (err != CL_SUCCESS) CAF_RAISE_ERROR("clCreateKernelsInProgram failed"); for (cl_uint i = 0; i < number_of_kernels; ++i) { size_t len; clGetKernelInfo(kernels[i], CL_KERNEL_FUNCTION_NAME, 0, nullptr, &len); vector<char> name(len); err = clGetKernelInfo(kernels[i], CL_KERNEL_FUNCTION_NAME, len, reinterpret_cast<void*>(name.data()), nullptr); if (err != CL_SUCCESS) CAF_RAISE_ERROR("clGetKernelInfo failed"); detail::raw_kernel_ptr kernel; kernel.reset(move(kernels[i])); available_kernels.emplace(string(name.data()), move(kernel)); } } else { CAF_LOG_WARNING("Could not built all kernels in program. Since this happens" " on some platforms, we'll ignore this and try to build" " each kernel individually by name."); } return make_counted<program>(dev->context_, dev->queue_, pptr, move(available_kernels)); } manager::manager(actor_system& sys) : system_(sys) { // nop } manager::~manager() { // nop } } // namespace opencl } // namespace caf <|endoftext|>
<commit_before>#ifndef UTIL_BOX_H__ #define UTIL_BOX_H__ #include <sstream> #include <iostream> #include <type_traits> #include "point.hpp" namespace util { // forward declaration template <typename T, int N> class box; template <typename Derived, typename T, int N> class box_base { public: /** * Default constructor. */ box_base() {} template <typename S> box_base(const point<S,N>& min, const point<S,N>& max) : _min(min), _max(max) {} template <typename D,typename S> box_base(const box_base<D,S,N>& other) : _min(other.min()), _max(other.max()) {} template <typename S> operator box<S,N>() const { return box<S,N>(_min, _max); } const point<T,N>& min() const { return _min; } point<T,N>& min() { return _min; } const point<T,N>& max() const { return _max; } point<T,N>& max() { return _max; } bool valid() { return isZero(); } template <typename D, typename S> bool intersects(const box_base<D,S,N>& other) const { // empty boxes do not intersect if (isZero() || other.isZero()) return false; // two non-intersecting boxes are separated by a plane parallel to // either dimension for (int i = 0; i < N; i++) if (max()[i] <= other.min()[i] || min()[i] >= other.max()[i]) return false; return true; } template <typename D, typename S> Derived intersection(const box_base<D,S,N>& other) const { Derived result; if (!intersects(other)) return result; for (int i = 0; i < N; i++) { result.min()[i] = std::max(min()[i], other.min()[i]); result.max()[i] = std::min(max()[i], other.max()[i]); } return result; } template <typename S, int M> bool contains(const point<S,M>& point) const { for (int i = 0; i < std::min(N, M); i++) if (max()[i] <= point[i] || min()[i] > point[i]) return false; return true; } /** * Extend this box, such that it fits the given point. */ template <typename S> void fit(const point<S,N>& point) { if (isZero()) { for (int i = 0; i < N; i++) { min()[i] = point[i]; max()[i] = point[i]; } return; } for (int i = 0; i < N; i++) { min()[i] = std::min(point[i], min()[i]); max()[i] = std::max(point[i], max()[i]); } } /** * Extend the x and y dimensions of the box, such that it fits the given * box. */ template <typename D, typename S, int M> void fit(const box_base<D,S,M>& other) { if (isZero()) { for (int i = 0; i < std::min(N, M); i++) { min()[i] = other.min()[i]; max()[i] = other.max()[i]; } return; } for (int i = 0; i < std::min(N, M); i++) { min()[i] = std::min(other.min()[i], min()[i]); max()[i] = std::max(other.max()[i], max()[i]); } } /** * Extend this box, such that it fits the given box. */ template <typename D, typename S, int M> Derived& operator+=(const box_base<D,S,M>& other) { this->fit(other); return static_cast<Derived&>(*this); } /** * Add two boxes, i.e., create one that fits both. */ template <typename D, typename S, int M> Derived operator+(const box_base<D,S,M>& other) const { Derived b(*this); return (b += other); } bool isZero() const { for (int i = 0; i < N; i++) if (min()[i] != 0 || min()[i] != 0) return false; return true; } template <typename S, int M> Derived& operator+=(const point<S,M>& p) { for (int i = 0; i < std::min(N, M); i++) { min()[i] += p[i]; max()[i] += p[i]; } return static_cast<Derived&>(*this); } template <typename S, int M> Derived& operator-=(const point<S,M>& p) { for (int i = 0; i < std::min(N, M); i++) { min()[i] -= p[i]; max()[i] -= p[i]; } return static_cast<Derived&>(*this); } template <typename S> Derived& operator*=(const S& s) { min() *= s; max() *= s; return static_cast<Derived&>(*this); } template <typename S> Derived& operator/=(const S& s) { min() /= s; max() /= s; return static_cast<Derived&>(*this); } template <typename D, typename S> bool operator==(const box_base<D,S,N>& other) const { return (min() == other.min() && max() == other.max()); } template <typename D, typename S> bool operator!=(const box_base<D,S,N>& other) const { return !(*this == other); } private: point<T,N> _min; point<T,N> _max; }; template <typename T, int N> class box : public box_base<box<T,N>, T, N> { typedef box_base<box<T,N>, T, N> base_type; public: template <typename S> box(const point<S,N>& min, const point<S,N>& max) : base_type( min, max) {} }; template <typename T> class box<T,2> : public box_base<box<T,2>, T, 2> { typedef box_base<box<T,2>, T, 2> base_type; public: box() : base_type() {} box(T minX, T minY, T maxX, T maxY) : base_type( point<T,2>(minX, minY), point<T,2>(maxX, maxY)) {} template <typename S> box(const point<S,2>& min, const point<S,2>& max) : base_type( min, max) {} using base_type::min; using base_type::max; T width() const { return max().x() - min().x(); } T height() const { return max().y() - min().y(); } T area() const { return width()*height(); } using base_type::contains; template <typename S> bool contains(S x, S y) const { return contains(point<S,2>(x, y)); } }; template <typename T> class box<T, 3> : public box_base<box<T, 3>, T, 3> { typedef box_base<box<T,3>, T, 3> base_type; public: box() : base_type() {} box(T minX, T minY, T minZ, T maxX, T maxY, T maxZ) : base_type( point<T,3>(minX, minY, minZ), point<T,3>(maxX, maxY, maxZ)) {} template <typename S> box(const point<S,3>& min, const point<S,3>& max) : base_type( min, max) {} using base_type::min; using base_type::max; T width() const { return max().x() - min().x(); } T height() const { return max().y() - min().y(); } T depth() const { return max().z() - min().z(); } T volume() const { return width()*height()*depth(); } using base_type::contains; template <typename S> bool contains(S x, S y, S z) const { return contains(point<S,3>(x, y, z)); } }; } // namespace util template <typename T, int N, typename PointType> util::box<T,N> operator+(const util::box<T,N>& p, const PointType& o) { util::box<T,N> result(p); return result += o; } template <typename T, int N, typename PointType> util::box<T,N> operator-(const util::box<T,N>& p, const PointType& o) { util::box<T,N> result(p); return result -= o; } template <typename T, int N, typename S> util::box<T,N> operator*(const util::box<T,N>& p, const S& s) { util::box<T,N> result(p); return result *= s; } template <typename S, typename T, int N> util::box<S,N> operator*(const S& s, const util::box<T,N>& p) { util::box<S,N> result(p); return result *= s; } template <typename T, int N, typename S> util::box<T,N> operator/(const util::box<T,N>& p, const S& s) { util::box<T,N> result(p); return result /= s; } template <typename T, int N> std::ostream& operator<<(std::ostream& os, const util::box<T,N>& box) { os << "[" << box.min() << ", " << box.max() << "]"; return os; } #endif // UTIL_BOX_H__ <commit_msg>added center() to box<commit_after>#ifndef UTIL_BOX_H__ #define UTIL_BOX_H__ #include <sstream> #include <iostream> #include <type_traits> #include "point.hpp" namespace util { // forward declaration template <typename T, int N> class box; template <typename Derived, typename T, int N> class box_base { public: /** * Default constructor. */ box_base() {} template <typename S> box_base(const point<S,N>& min, const point<S,N>& max) : _min(min), _max(max) {} template <typename D,typename S> box_base(const box_base<D,S,N>& other) : _min(other.min()), _max(other.max()) {} template <typename S> operator box<S,N>() const { return box<S,N>(_min, _max); } const point<T,N>& min() const { return _min; } point<T,N>& min() { return _min; } const point<T,N>& max() const { return _max; } point<T,N>& max() { return _max; } bool valid() { return isZero(); } point<T,N> center() const { return (_min + _max)/2.0; } template <typename D, typename S> bool intersects(const box_base<D,S,N>& other) const { // empty boxes do not intersect if (isZero() || other.isZero()) return false; // two non-intersecting boxes are separated by a plane parallel to // either dimension for (int i = 0; i < N; i++) if (max()[i] <= other.min()[i] || min()[i] >= other.max()[i]) return false; return true; } template <typename D, typename S> Derived intersection(const box_base<D,S,N>& other) const { Derived result; if (!intersects(other)) return result; for (int i = 0; i < N; i++) { result.min()[i] = std::max(min()[i], other.min()[i]); result.max()[i] = std::min(max()[i], other.max()[i]); } return result; } template <typename S, int M> bool contains(const point<S,M>& point) const { for (int i = 0; i < std::min(N, M); i++) if (max()[i] <= point[i] || min()[i] > point[i]) return false; return true; } /** * Extend this box, such that it fits the given point. */ template <typename S> void fit(const point<S,N>& point) { if (isZero()) { for (int i = 0; i < N; i++) { min()[i] = point[i]; max()[i] = point[i]; } return; } for (int i = 0; i < N; i++) { min()[i] = std::min(point[i], min()[i]); max()[i] = std::max(point[i], max()[i]); } } /** * Extend the x and y dimensions of the box, such that it fits the given * box. */ template <typename D, typename S, int M> void fit(const box_base<D,S,M>& other) { if (isZero()) { for (int i = 0; i < std::min(N, M); i++) { min()[i] = other.min()[i]; max()[i] = other.max()[i]; } return; } for (int i = 0; i < std::min(N, M); i++) { min()[i] = std::min(other.min()[i], min()[i]); max()[i] = std::max(other.max()[i], max()[i]); } } /** * Extend this box, such that it fits the given box. */ template <typename D, typename S, int M> Derived& operator+=(const box_base<D,S,M>& other) { this->fit(other); return static_cast<Derived&>(*this); } /** * Add two boxes, i.e., create one that fits both. */ template <typename D, typename S, int M> Derived operator+(const box_base<D,S,M>& other) const { Derived b(*this); return (b += other); } bool isZero() const { for (int i = 0; i < N; i++) if (min()[i] != 0 || min()[i] != 0) return false; return true; } template <typename S, int M> Derived& operator+=(const point<S,M>& p) { for (int i = 0; i < std::min(N, M); i++) { min()[i] += p[i]; max()[i] += p[i]; } return static_cast<Derived&>(*this); } template <typename S, int M> Derived& operator-=(const point<S,M>& p) { for (int i = 0; i < std::min(N, M); i++) { min()[i] -= p[i]; max()[i] -= p[i]; } return static_cast<Derived&>(*this); } template <typename S> Derived& operator*=(const S& s) { min() *= s; max() *= s; return static_cast<Derived&>(*this); } template <typename S> Derived& operator/=(const S& s) { min() /= s; max() /= s; return static_cast<Derived&>(*this); } template <typename D, typename S> bool operator==(const box_base<D,S,N>& other) const { return (min() == other.min() && max() == other.max()); } template <typename D, typename S> bool operator!=(const box_base<D,S,N>& other) const { return !(*this == other); } private: point<T,N> _min; point<T,N> _max; }; template <typename T, int N> class box : public box_base<box<T,N>, T, N> { typedef box_base<box<T,N>, T, N> base_type; public: template <typename S> box(const point<S,N>& min, const point<S,N>& max) : base_type( min, max) {} }; template <typename T> class box<T,2> : public box_base<box<T,2>, T, 2> { typedef box_base<box<T,2>, T, 2> base_type; public: box() : base_type() {} box(T minX, T minY, T maxX, T maxY) : base_type( point<T,2>(minX, minY), point<T,2>(maxX, maxY)) {} template <typename S> box(const point<S,2>& min, const point<S,2>& max) : base_type( min, max) {} using base_type::min; using base_type::max; T width() const { return max().x() - min().x(); } T height() const { return max().y() - min().y(); } T area() const { return width()*height(); } using base_type::contains; template <typename S> bool contains(S x, S y) const { return contains(point<S,2>(x, y)); } }; template <typename T> class box<T, 3> : public box_base<box<T, 3>, T, 3> { typedef box_base<box<T,3>, T, 3> base_type; public: box() : base_type() {} box(T minX, T minY, T minZ, T maxX, T maxY, T maxZ) : base_type( point<T,3>(minX, minY, minZ), point<T,3>(maxX, maxY, maxZ)) {} template <typename S> box(const point<S,3>& min, const point<S,3>& max) : base_type( min, max) {} using base_type::min; using base_type::max; T width() const { return max().x() - min().x(); } T height() const { return max().y() - min().y(); } T depth() const { return max().z() - min().z(); } T volume() const { return width()*height()*depth(); } using base_type::contains; template <typename S> bool contains(S x, S y, S z) const { return contains(point<S,3>(x, y, z)); } }; } // namespace util template <typename T, int N, typename PointType> util::box<T,N> operator+(const util::box<T,N>& p, const PointType& o) { util::box<T,N> result(p); return result += o; } template <typename T, int N, typename PointType> util::box<T,N> operator-(const util::box<T,N>& p, const PointType& o) { util::box<T,N> result(p); return result -= o; } template <typename T, int N, typename S> util::box<T,N> operator*(const util::box<T,N>& p, const S& s) { util::box<T,N> result(p); return result *= s; } template <typename S, typename T, int N> util::box<S,N> operator*(const S& s, const util::box<T,N>& p) { util::box<S,N> result(p); return result *= s; } template <typename T, int N, typename S> util::box<T,N> operator/(const util::box<T,N>& p, const S& s) { util::box<T,N> result(p); return result /= s; } template <typename T, int N> std::ostream& operator<<(std::ostream& os, const util::box<T,N>& box) { os << "[" << box.min() << ", " << box.max() << "]"; return os; } #endif // UTIL_BOX_H__ <|endoftext|>
<commit_before>#include "Arduino.h" #include "DFR_Key.h" static int DEFAULT_KEY_PIN = 0; static int DEFAULT_THRESHOLD = 5; /* To use any alternate set of values you will need to enable it by a define. The define should NOT be done in code or it will impact all users. Visual Studio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the project, or add '-DDF_ROBOT_V1' under advanced options. Users of the standard Arduino IDE should create the file 'platform.local.txt' under <arduino_install>/hardware.arduino/avr and add the following line but be aware that when you upgrade your IDE this file may need to be re-created: compiler.cpp.extra_flags=-DDF_ROBOT_V1 If further values are added in the future then of course adjust the name of the define that you specify accordingly. */ #ifdef DF_ROBOT_V1 static int RIGHTKEY_ARV = 0; //that's read "analogue read value" static int UPKEY_ARV = 98; static int DOWNKEY_ARV = 254; static int LEFTKEY_ARV = 407; static int SELKEY_ARV = 638; static int NOKEY_ARV = 1023; #else static int RIGHTKEY_ARV = 0; static int UPKEY_ARV = 144; static int DOWNKEY_ARV = 329; static int LEFTKEY_ARV = 505; static int SELKEY_ARV = 742; static int NOKEY_ARV = 1023; #endif DFR_Key::DFR_Key() { _refreshRate = 10; _keyPin = DEFAULT_KEY_PIN; _threshold = DEFAULT_THRESHOLD; _keyIn = NO_KEY; _curInput = NO_KEY; _curKey = NO_KEY; _prevInput = NO_KEY; _prevKey = NO_KEY; _oldTime = 0; } int DFR_Key::getKey() { if (millis() > _oldTime + _refreshRate) { _prevInput = _curInput; _curInput = analogRead(_keyPin); if (_curInput == _prevInput) { _change = false; _curKey = _prevKey; } else { _change = true; _prevKey = _curKey; if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY; else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY; else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY; else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY; else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY; else _curKey = NO_KEY; } if (_change) return _curKey; else return SAMPLE_WAIT; _oldTime = millis(); } } void DFR_Key::setRate(int rate) { _refreshRate = rate; }<commit_msg>All: Increase the key thresholds to accomodate my aging keypad shield.<commit_after>#include "Arduino.h" #include "DFR_Key.h" static int DEFAULT_KEY_PIN = 0; static int DEFAULT_THRESHOLD = 20; /* To use any alternate set of values you will need to enable it by a define. The define should NOT be done in code or it will impact all users. Visual Studio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the project, or add '-DDF_ROBOT_V1' under advanced options. Users of the standard Arduino IDE should create the file 'platform.local.txt' under <arduino_install>/hardware.arduino/avr and add the following line but be aware that when you upgrade your IDE this file may need to be re-created: compiler.cpp.extra_flags=-DDF_ROBOT_V1 If further values are added in the future then of course adjust the name of the define that you specify accordingly. */ #ifdef DF_ROBOT_V1 static int RIGHTKEY_ARV = 0; //that's read "analogue read value" static int UPKEY_ARV = 98; static int DOWNKEY_ARV = 254; static int LEFTKEY_ARV = 407; static int SELKEY_ARV = 638; static int NOKEY_ARV = 1023; #else static int RIGHTKEY_ARV = 0; static int UPKEY_ARV = 144; static int DOWNKEY_ARV = 329; static int LEFTKEY_ARV = 505; static int SELKEY_ARV = 742; static int NOKEY_ARV = 1023; #endif DFR_Key::DFR_Key() { _refreshRate = 10; _keyPin = DEFAULT_KEY_PIN; _threshold = DEFAULT_THRESHOLD; _keyIn = NO_KEY; _curInput = NO_KEY; _curKey = NO_KEY; _prevInput = NO_KEY; _prevKey = NO_KEY; _oldTime = 0; } int DFR_Key::getKey() { if (millis() > _oldTime + _refreshRate) { _prevInput = _curInput; _curInput = analogRead(_keyPin); if (_curInput == _prevInput) { _change = false; _curKey = _prevKey; } else { _change = true; _prevKey = _curKey; if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY; else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY; else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY; else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY; else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY; else _curKey = NO_KEY; } if (_change) return _curKey; else return SAMPLE_WAIT; _oldTime = millis(); } } void DFR_Key::setRate(int rate) { _refreshRate = rate; }<|endoftext|>
<commit_before>#include "mnetracer.h" using namespace UTILSLIB; static const char* defaultTracerFileName("default_MNETracer_file.json"); bool MNETracer::ms_bIsEnabled(false); std::ofstream MNETracer::ms_OutputFileStream; bool MNETracer::ms_bIsFirstEvent(true); long long MNETracer::ms_iZeroTime(0); //============================================================================================================= MNETracer::MNETracer(const std::string &file, const std::string &function, int lineNumber) : m_bIsInitialized(false) , m_bPrintToTerminal(false) , m_sFileName(file) , m_sFunctionName(function) , m_iLineNumber(lineNumber) , m_iThreadId("0") , m_iBeginTime(0) , m_iEndTime(0) , m_dDurationMilis(0.) { if (ms_bIsEnabled) { initialize(); writeBeginEvent(); } } //============================================================================================================= MNETracer::~MNETracer() { if (ms_bIsEnabled && m_bIsInitialized) { registerFinalTime(); writeEndEvent(); if (m_bPrintToTerminal) { calculateDuration(); printDurationMiliSec(); } } } //============================================================================================================= void MNETracer::enable(const std::string &jsonFileName) { ms_OutputFileStream.open(jsonFileName); writeHeader(); setZeroTime(); if (ms_OutputFileStream.is_open()) { ms_bIsEnabled = true; } } //============================================================================================================= void MNETracer::enable() { enable(defaultTracerFileName); } //============================================================================================================= void MNETracer::disable() { if (ms_bIsEnabled) { writeFooter(); ms_OutputFileStream.flush(); ms_OutputFileStream.close(); ms_bIsEnabled = false; } } //============================================================================================================= void MNETracer::start(const std::string &jsonFileName) { enable(jsonFileName); } //============================================================================================================= void MNETracer::start() { enable(); } //============================================================================================================= void MNETracer::stop() { disable(); } //============================================================================================================= void MNETracer::traceQuantity(const std::string &name, long val) { long long timeNow = getTimeNow() - ms_iZeroTime; std::string s; s.append("{\"name\":\"").append(name).append("\",\"ph\":\"C\",\"ts\":"); s.append(std::to_string(timeNow)).append(",\"pid\":1,\"tid\":1"); s.append(",\"args\":{\"").append(name).append("\":").append(std::to_string(val)).append("}}\n"); writeToFile(s); } //============================================================================================================= void MNETracer::initialize() { registerConstructionTime(); registerThreadId(); formatFileName(); // formatFunctionName(); m_bIsInitialized = true; } //============================================================================================================= void MNETracer::setZeroTime() { ms_iZeroTime = getTimeNow(); } //============================================================================================================= void MNETracer::registerConstructionTime() { m_iBeginTime = getTimeNow() - ms_iZeroTime; } //============================================================================================================= void MNETracer::registerFinalTime() { m_iEndTime = getTimeNow() - ms_iZeroTime; } //============================================================================================================= long long MNETracer::getTimeNow() { auto timeNow = std::chrono::high_resolution_clock::now(); return std::chrono::time_point_cast<std::chrono::microseconds>(timeNow).time_since_epoch().count(); } //============================================================================================================= void MNETracer::registerThreadId() { auto longId = std::hash<std::thread::id>{}(std::this_thread::get_id()); m_iThreadId = std::to_string(longId).substr(0, 5); } //============================================================================================================= void MNETracer::formatFunctionName() { const char* pattern(" __cdecl"); constexpr int patternLenght(8); size_t pos = m_sFunctionName.find(pattern); if (pos != std::string::npos) { m_sFunctionName.replace(pos, patternLenght, ""); } } //============================================================================================================= void MNETracer::formatFileName() { const char* patternIn("\\"); const char* patternOut("\\\\"); constexpr int patternOutLength(4); size_t start_pos = 0; while ((start_pos = m_sFileName.find(patternIn, start_pos)) != std::string::npos) { m_sFileName.replace(start_pos, 1, patternOut); start_pos += patternOutLength; } } //============================================================================================================= void MNETracer::calculateDuration() { m_dDurationMilis = (m_iEndTime - m_iBeginTime) * 0.001; } //============================================================================================================= void MNETracer::printDurationMiliSec() { std::cout << "Scope: " << m_sFileName << " - " << m_sFunctionName << " DurationMs: " << m_dDurationMilis << "ms.\n"; } //============================================================================================================= void MNETracer::writeHeader() { writeToFile("{\"displayTimeUnit\": \"ms\",\"traceEvents\":[\n"); } //============================================================================================================= void MNETracer::writeFooter() { writeToFile("]}"); } //============================================================================================================= void MNETracer::writeToFile(const std::string &str) { ms_outFileMutex.lock(); if(ms_OutputFileStream.is_open()) { ms_OutputFileStream << str; } ms_outFileMutex.unlock(); } //============================================================================================================= void MNETracer::writeBeginEvent() { std::string s; if (!ms_bIsFirstEvent) s.append(","); s.append("{\"name\":\"").append(m_sFunctionName).append("\",\"cat\":\"bst\","); s.append("\"ph\":\"B\",\"ts\":").append(std::to_string(m_iBeginTime)).append(",\"pid\":1,\"tid\":"); s.append(m_iThreadId).append(",\"args\":{\"file path\":\"").append(m_sFileName).append("\",\"line number\":"); s.append(std::to_string(m_iLineNumber)).append("}}\n"); writeToFile(s); ms_bIsFirstEvent = false; } //============================================================================================================= void MNETracer::writeEndEvent() { std::string s; s.append(",{\"name\":\"").append(m_sFunctionName).append("\",\"cat\":\"bst\","); s.append("\"ph\":\"E\",\"ts\":").append(std::to_string(m_iEndTime)).append(",\"pid\":1,\"tid\":"); s.append(m_iThreadId).append(",\"args\":{\"file path\":\"").append(m_sFileName).append("\",\"line number\":"); s.append(std::to_string(m_iLineNumber)).append("}}\n"); writeToFile(s); } //============================================================================================================= bool MNETracer::printToTerminalIsSet() { return m_bPrintToTerminal; } //============================================================================================================= void MNETracer::setPrintToTerminal(bool s) { m_bPrintToTerminal = s; } <commit_msg>actually define the mutex<commit_after>#include "mnetracer.h" using namespace UTILSLIB; static const char* defaultTracerFileName("default_MNETracer_file.json"); bool MNETracer::ms_bIsEnabled(false); std::ofstream MNETracer::ms_OutputFileStream; bool MNETracer::ms_bIsFirstEvent(true); std::mutex MNETracer::ms_outFileMutex; long long MNETracer::ms_iZeroTime(0); //============================================================================================================= MNETracer::MNETracer(const std::string &file, const std::string &function, int lineNumber) : m_bIsInitialized(false) , m_bPrintToTerminal(false) , m_sFileName(file) , m_sFunctionName(function) , m_iLineNumber(lineNumber) , m_iThreadId("0") , m_iBeginTime(0) , m_iEndTime(0) , m_dDurationMilis(0.) { if (ms_bIsEnabled) { initialize(); writeBeginEvent(); } } //============================================================================================================= MNETracer::~MNETracer() { if (ms_bIsEnabled && m_bIsInitialized) { registerFinalTime(); writeEndEvent(); if (m_bPrintToTerminal) { calculateDuration(); printDurationMiliSec(); } } } //============================================================================================================= void MNETracer::enable(const std::string &jsonFileName) { ms_OutputFileStream.open(jsonFileName); writeHeader(); setZeroTime(); if (ms_OutputFileStream.is_open()) { ms_bIsEnabled = true; } } //============================================================================================================= void MNETracer::enable() { enable(defaultTracerFileName); } //============================================================================================================= void MNETracer::disable() { if (ms_bIsEnabled) { writeFooter(); ms_OutputFileStream.flush(); ms_OutputFileStream.close(); ms_bIsEnabled = false; } } //============================================================================================================= void MNETracer::start(const std::string &jsonFileName) { enable(jsonFileName); } //============================================================================================================= void MNETracer::start() { enable(); } //============================================================================================================= void MNETracer::stop() { disable(); } //============================================================================================================= void MNETracer::traceQuantity(const std::string &name, long val) { long long timeNow = getTimeNow() - ms_iZeroTime; std::string s; s.append("{\"name\":\"").append(name).append("\",\"ph\":\"C\",\"ts\":"); s.append(std::to_string(timeNow)).append(",\"pid\":1,\"tid\":1"); s.append(",\"args\":{\"").append(name).append("\":").append(std::to_string(val)).append("}}\n"); writeToFile(s); } //============================================================================================================= void MNETracer::initialize() { registerConstructionTime(); registerThreadId(); formatFileName(); // formatFunctionName(); m_bIsInitialized = true; } //============================================================================================================= void MNETracer::setZeroTime() { ms_iZeroTime = getTimeNow(); } //============================================================================================================= void MNETracer::registerConstructionTime() { m_iBeginTime = getTimeNow() - ms_iZeroTime; } //============================================================================================================= void MNETracer::registerFinalTime() { m_iEndTime = getTimeNow() - ms_iZeroTime; } //============================================================================================================= long long MNETracer::getTimeNow() { auto timeNow = std::chrono::high_resolution_clock::now(); return std::chrono::time_point_cast<std::chrono::microseconds>(timeNow).time_since_epoch().count(); } //============================================================================================================= void MNETracer::registerThreadId() { auto longId = std::hash<std::thread::id>{}(std::this_thread::get_id()); m_iThreadId = std::to_string(longId).substr(0, 5); } //============================================================================================================= void MNETracer::formatFunctionName() { const char* pattern(" __cdecl"); constexpr int patternLenght(8); size_t pos = m_sFunctionName.find(pattern); if (pos != std::string::npos) { m_sFunctionName.replace(pos, patternLenght, ""); } } //============================================================================================================= void MNETracer::formatFileName() { const char* patternIn("\\"); const char* patternOut("\\\\"); constexpr int patternOutLength(4); size_t start_pos = 0; while ((start_pos = m_sFileName.find(patternIn, start_pos)) != std::string::npos) { m_sFileName.replace(start_pos, 1, patternOut); start_pos += patternOutLength; } } //============================================================================================================= void MNETracer::calculateDuration() { m_dDurationMilis = (m_iEndTime - m_iBeginTime) * 0.001; } //============================================================================================================= void MNETracer::printDurationMiliSec() { std::cout << "Scope: " << m_sFileName << " - " << m_sFunctionName << " DurationMs: " << m_dDurationMilis << "ms.\n"; } //============================================================================================================= void MNETracer::writeHeader() { writeToFile("{\"displayTimeUnit\": \"ms\",\"traceEvents\":[\n"); } //============================================================================================================= void MNETracer::writeFooter() { writeToFile("]}"); } //============================================================================================================= void MNETracer::writeToFile(const std::string &str) { ms_outFileMutex.lock(); if(ms_OutputFileStream.is_open()) { ms_OutputFileStream << str; } ms_outFileMutex.unlock(); } //============================================================================================================= void MNETracer::writeBeginEvent() { std::string s; if (!ms_bIsFirstEvent) s.append(","); s.append("{\"name\":\"").append(m_sFunctionName).append("\",\"cat\":\"bst\","); s.append("\"ph\":\"B\",\"ts\":").append(std::to_string(m_iBeginTime)).append(",\"pid\":1,\"tid\":"); s.append(m_iThreadId).append(",\"args\":{\"file path\":\"").append(m_sFileName).append("\",\"line number\":"); s.append(std::to_string(m_iLineNumber)).append("}}\n"); writeToFile(s); ms_bIsFirstEvent = false; } //============================================================================================================= void MNETracer::writeEndEvent() { std::string s; s.append(",{\"name\":\"").append(m_sFunctionName).append("\",\"cat\":\"bst\","); s.append("\"ph\":\"E\",\"ts\":").append(std::to_string(m_iEndTime)).append(",\"pid\":1,\"tid\":"); s.append(m_iThreadId).append(",\"args\":{\"file path\":\"").append(m_sFileName).append("\",\"line number\":"); s.append(std::to_string(m_iLineNumber)).append("}}\n"); writeToFile(s); } //============================================================================================================= bool MNETracer::printToTerminalIsSet() { return m_bPrintToTerminal; } //============================================================================================================= void MNETracer::setPrintToTerminal(bool s) { m_bPrintToTerminal = s; } <|endoftext|>
<commit_before>/* * TTUnitTest * Copyright © 2011, Timothy Place and Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include <limits> #include "TTUnitTest.h" static const TTFloat32 kTTTestFloat32Epsilon = 0.00001f; static const TTFloat64 kTTTestFloat64Epsilon = 0.000000001; static const TTFloat32 kTTTestFloat32Infinity = std::numeric_limits<float>::infinity(); static const TTFloat64 kTTTestFloat64Infinity = std::numeric_limits<double>::infinity(); TTBoolean TTTestFloatEquivalence(TTFloat32 aFloat, TTFloat32 bFloat, TTBoolean expectedResult, TTFloat32 epsilon) { if (epsilon <= 0.) { TTLogMessage(" TTTestFloatEquivalence: epsilon must be a positive number\n"); return false; } TTBoolean result; if ((aFloat == kTTTestFloat32Infinity)||(bFloat == kTTTestFloat32Infinity)) { if (aFloat==bFloat) result = true; else result = false; } else { TTFloat32 aAbs = fabs(aFloat); TTFloat32 bAbs = fabs(bFloat); TTFloat32 absoluteOrRelative = (1.0f > aAbs ? 1.0f : aAbs); absoluteOrRelative = (absoluteOrRelative > bAbs ? absoluteOrRelative : bAbs); if (fabs(aFloat - bFloat) <= epsilon * absoluteOrRelative) result = true; else result = false; } // Was this the expected result? if (result == expectedResult) return true; else { TTLogMessage("\n"); TTLogMessage(" TTTestFloatEquivalence: Unexpected result\n"); TTLogMessage("\n"); TTLogMessage(" aFloat = %.8e\n", aFloat); TTLogMessage(" bFloat = %.8e\n", bFloat); TTLogMessage(" result = %s\n", (result)?"true":"false"); TTLogMessage("\n"); return false; } } TTBoolean TTTestFloatEquivalence(TTFloat64 aFloat, TTFloat64 bFloat, TTBoolean expectedResult, TTFloat64 epsilon) { if (epsilon <= 0.) { TTLogMessage(" TTTestFloatEquivalence: epsilon must be a positive number\n"); return false; } TTBoolean result; if ((aFloat == kTTTestFloat64Infinity)||(bFloat == kTTTestFloat64Infinity)) { if (aFloat==bFloat) result = true; else result = false; } else { TTFloat64 aAbs = fabs(aFloat); TTFloat64 bAbs = fabs(bFloat); TTFloat64 absoluteOrRelative = (1.0f > aAbs ? 1.0f : aAbs); absoluteOrRelative = (absoluteOrRelative > bAbs ? absoluteOrRelative : bAbs); if (fabs(aFloat - bFloat) <= epsilon * absoluteOrRelative) result = true; else result = false; } // Was this the expected result? if (result == expectedResult) return true; else { TTLogMessage("\n"); TTLogMessage(" TTTestFloatEquivalence: Unexpected result\n"); TTLogMessage("\n"); TTLogMessage(" aFloat = %.15e\n", aFloat); TTLogMessage(" bFloat = %.15e\n", bFloat); TTLogMessage(" result = %s\n", (result)?"true":"false"); TTLogMessage("\n"); return false; } } TTBoolean TTTestFloat32ArrayEquivalence(TTValue &aFloat, TTValue &bFloat, TTBoolean expectedResult, TTFloat32 epsilon) { TTInt32 i; TTBoolean result; // Compare vector size if (aFloat.getSize()!=bFloat.getSize()) result = false; else { // Compare member by member result = true; for (i=0; i<aFloat.getSize(); i++) result = result && TTTestFloatEquivalence(TTFloat32(aFloat.getFloat32(i)), TTFloat32(bFloat.getFloat32(i)), expectedResult, epsilon); } return result; } TTBoolean TTTestFloat64ArrayEquivalence(TTValue &aFloat, TTValue &bFloat, TTBoolean expectedResult, TTFloat64 epsilon) { TTInt32 i; TTBoolean result; // Compare vector size if (aFloat.getSize()!=bFloat.getSize()) result = false; else { // Compare member by member result = true; for (i=0; i<aFloat.getSize(); i++) result = result && TTTestFloatEquivalence(aFloat.getFloat64(i), bFloat.getFloat64(i), expectedResult, epsilon); } return result; } void TTTestLog(const char *fmtstring, ...) { char str[4096]; char fullstr[4096]; va_list ap; va_start(ap, fmtstring); vsnprintf(str, 4000, fmtstring, ap); va_end(ap); str[4095] = 0; strncpy(fullstr, " ", 4095); strncat(fullstr, str, 4095); strncat(fullstr, "\n", 4095); TTLogMessage(fullstr); } void TTTestAssertion(const char* aTestName, TTBoolean aTestResult, int& testAssertionCount, int& errorCount) { testAssertionCount++; if (aTestResult) TTLogMessage(" PASS -- "); else { TTLogMessage(" FAIL -- "); errorCount++; } TTLogMessage(aTestName); TTLogMessage("\n"); if (!aTestResult) TTLogMessage("\n"); } TTErr TTTestFinish(int testAssertionCount, int errorCount, TTValue& returnedTestInfo) { TTDictionaryPtr d = new TTDictionary; d->setSchema(TT("TestInfo")); d->append(TT("testAssertionCount"), testAssertionCount); d->append(TT("errorCount"), errorCount); returnedTestInfo = d; TTTestLog("\n"); TTTestLog("Number of assertions: %ld", testAssertionCount); TTTestLog("Number of failed assertions: %ld", errorCount); TTTestLog("\n"); if (errorCount) return kTTErrGeneric; else return kTTErrNone; } <commit_msg>TTUnitTest: adding #ifdefs around log posts when the float-comparison fails. I think any posting should be done by the code that calls these functions rather than these functions themselves. But maybe others disagree? It was cluttering my console window when debugging, so I just went ahead and did it, but we can discuss and revert if needed...<commit_after>/* * TTUnitTest * Copyright © 2011, Timothy Place and Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include <limits> #include "TTUnitTest.h" static const TTFloat32 kTTTestFloat32Epsilon = 0.00001f; static const TTFloat64 kTTTestFloat64Epsilon = 0.000000001; static const TTFloat32 kTTTestFloat32Infinity = std::numeric_limits<float>::infinity(); static const TTFloat64 kTTTestFloat64Infinity = std::numeric_limits<double>::infinity(); TTBoolean TTTestFloatEquivalence(TTFloat32 aFloat, TTFloat32 bFloat, TTBoolean expectedResult, TTFloat32 epsilon) { if (epsilon <= 0.) { TTLogMessage(" TTTestFloatEquivalence: epsilon must be a positive number\n"); return false; } TTBoolean result; if ((aFloat == kTTTestFloat32Infinity)||(bFloat == kTTTestFloat32Infinity)) { if (aFloat==bFloat) result = true; else result = false; } else { TTFloat32 aAbs = fabs(aFloat); TTFloat32 bAbs = fabs(bFloat); TTFloat32 absoluteOrRelative = (1.0f > aAbs ? 1.0f : aAbs); absoluteOrRelative = (absoluteOrRelative > bAbs ? absoluteOrRelative : bAbs); if (fabs(aFloat - bFloat) <= epsilon * absoluteOrRelative) result = true; else result = false; } // Was this the expected result? if (result == expectedResult) return true; else { #ifdef NOISY_FAILURE TTLogMessage("\n"); TTLogMessage(" TTTestFloatEquivalence: Unexpected result\n"); TTLogMessage("\n"); TTLogMessage(" aFloat = %.8e\n", aFloat); TTLogMessage(" bFloat = %.8e\n", bFloat); TTLogMessage(" result = %s\n", (result)?"true":"false"); TTLogMessage("\n"); #endif return false; } } TTBoolean TTTestFloatEquivalence(TTFloat64 aFloat, TTFloat64 bFloat, TTBoolean expectedResult, TTFloat64 epsilon) { if (epsilon <= 0.) { TTLogMessage(" TTTestFloatEquivalence: epsilon must be a positive number\n"); return false; } TTBoolean result; if ((aFloat == kTTTestFloat64Infinity)||(bFloat == kTTTestFloat64Infinity)) { if (aFloat==bFloat) result = true; else result = false; } else { TTFloat64 aAbs = fabs(aFloat); TTFloat64 bAbs = fabs(bFloat); TTFloat64 absoluteOrRelative = (1.0f > aAbs ? 1.0f : aAbs); absoluteOrRelative = (absoluteOrRelative > bAbs ? absoluteOrRelative : bAbs); if (fabs(aFloat - bFloat) <= epsilon * absoluteOrRelative) result = true; else result = false; } // Was this the expected result? if (result == expectedResult) return true; else { #ifdef NOISY_FAILURE TTLogMessage("\n"); TTLogMessage(" TTTestFloatEquivalence: Unexpected result\n"); TTLogMessage("\n"); TTLogMessage(" aFloat = %.15e\n", aFloat); TTLogMessage(" bFloat = %.15e\n", bFloat); TTLogMessage(" result = %s\n", (result)?"true":"false"); TTLogMessage("\n"); #endif return false; } } TTBoolean TTTestFloat32ArrayEquivalence(TTValue &aFloat, TTValue &bFloat, TTBoolean expectedResult, TTFloat32 epsilon) { TTInt32 i; TTBoolean result; // Compare vector size if (aFloat.getSize()!=bFloat.getSize()) result = false; else { // Compare member by member result = true; for (i=0; i<aFloat.getSize(); i++) result = result && TTTestFloatEquivalence(TTFloat32(aFloat.getFloat32(i)), TTFloat32(bFloat.getFloat32(i)), expectedResult, epsilon); } return result; } TTBoolean TTTestFloat64ArrayEquivalence(TTValue &aFloat, TTValue &bFloat, TTBoolean expectedResult, TTFloat64 epsilon) { TTInt32 i; TTBoolean result; // Compare vector size if (aFloat.getSize()!=bFloat.getSize()) result = false; else { // Compare member by member result = true; for (i=0; i<aFloat.getSize(); i++) result = result && TTTestFloatEquivalence(aFloat.getFloat64(i), bFloat.getFloat64(i), expectedResult, epsilon); } return result; } void TTTestLog(const char *fmtstring, ...) { char str[4096]; char fullstr[4096]; va_list ap; va_start(ap, fmtstring); vsnprintf(str, 4000, fmtstring, ap); va_end(ap); str[4095] = 0; strncpy(fullstr, " ", 4095); strncat(fullstr, str, 4095); strncat(fullstr, "\n", 4095); TTLogMessage(fullstr); } void TTTestAssertion(const char* aTestName, TTBoolean aTestResult, int& testAssertionCount, int& errorCount) { testAssertionCount++; if (aTestResult) TTLogMessage(" PASS -- "); else { TTLogMessage(" FAIL -- "); errorCount++; } TTLogMessage(aTestName); TTLogMessage("\n"); if (!aTestResult) TTLogMessage("\n"); } TTErr TTTestFinish(int testAssertionCount, int errorCount, TTValue& returnedTestInfo) { TTDictionaryPtr d = new TTDictionary; d->setSchema(TT("TestInfo")); d->append(TT("testAssertionCount"), testAssertionCount); d->append(TT("errorCount"), errorCount); returnedTestInfo = d; TTTestLog("\n"); TTTestLog("Number of assertions: %ld", testAssertionCount); TTTestLog("Number of failed assertions: %ld", errorCount); TTTestLog("\n"); if (errorCount) return kTTErrGeneric; else return kTTErrNone; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Determine coverage of font given its raw "cmap" OpenType table #define LOG_TAG "Minikin" #include <cutils/log.h> #include <vector> using std::vector; #include <minikin/SparseBitSet.h> #include <minikin/CmapCoverage.h> namespace android { // These could perhaps be optimized to use __builtin_bswap16 and friends. static uint32_t readU16(const uint8_t* data, size_t offset) { return data[offset] << 8 | data[offset + 1]; } static uint32_t readU32(const uint8_t* data, size_t offset) { return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; } static void addRange(vector<uint32_t> &coverage, uint32_t start, uint32_t end) { #ifdef VERBOSE_DEBUG ALOGD("adding range %d-%d\n", start, end); #endif if (coverage.empty() || coverage.back() < start) { coverage.push_back(start); coverage.push_back(end); } else { coverage.back() = end; } } // Get the coverage information out of a Format 12 subtable, storing it in the coverage vector static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { int end = readU16(data, kEndCountOffset + 2 * i); int start = readU16(data, kHeaderSize + 2 * (segCount + i)); int rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { int delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (int j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (int j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { // invalid rangeOffset is considered a "warning" by OpenType Sanitizer continue; } int glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; } // Get the coverage information out of a Format 12 subtable, storing it in the coverage vector static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const int kMicrosoftPlatformId = 3; const int kUnicodeBmpEncodingId = 1; const int kUnicodeUcs4EncodingId = 10; if (kHeaderSize > cmap_size) { return false; } int numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } int bestTable = -1; for (int i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef VERBOSE_DEBUG ALOGD("best table = %d\n", bestTable); #endif if (bestTable < 0) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset + 2 > cmap_size) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef VERBOSE_DEBUG for (size_t i = 0; i < coverageVec.size(); i += 2) { ALOGD("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } ALOGD("success = %d", success); #endif return success; } } // namespace android <commit_msg>Avoid integer overflows in parsing fonts am: 6299a6ba13<commit_after>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Determine coverage of font given its raw "cmap" OpenType table #define LOG_TAG "Minikin" #include <cutils/log.h> #include <vector> using std::vector; #include <minikin/SparseBitSet.h> #include <minikin/CmapCoverage.h> namespace android { // These could perhaps be optimized to use __builtin_bswap16 and friends. static uint32_t readU16(const uint8_t* data, size_t offset) { return ((uint32_t)data[offset]) << 8 | ((uint32_t)data[offset + 1]); } static uint32_t readU32(const uint8_t* data, size_t offset) { return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 | ((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]); } static void addRange(vector<uint32_t> &coverage, uint32_t start, uint32_t end) { #ifdef VERBOSE_DEBUG ALOGD("adding range %d-%d\n", start, end); #endif if (coverage.empty() || coverage.back() < start) { coverage.push_back(start); coverage.push_back(end); } else { coverage.back() = end; } } // Get the coverage information out of a Format 12 subtable, storing it in the coverage vector static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { int end = readU16(data, kEndCountOffset + 2 * i); int start = readU16(data, kHeaderSize + 2 * (segCount + i)); int rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { int delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (int j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (int j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { // invalid rangeOffset is considered a "warning" by OpenType Sanitizer continue; } int glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; } // Get the coverage information out of a Format 12 subtable, storing it in the coverage vector static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow // For all values < kMaxNGroups, kFirstGroupOffset + nGroups * kGroupSize fits in 32 bits. if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const int kMicrosoftPlatformId = 3; const int kUnicodeBmpEncodingId = 1; const int kUnicodeUcs4EncodingId = 10; if (kHeaderSize > cmap_size) { return false; } int numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } int bestTable = -1; for (int i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef VERBOSE_DEBUG ALOGD("best table = %d\n", bestTable); #endif if (bestTable < 0) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset + 2 > cmap_size) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef VERBOSE_DEBUG for (size_t i = 0; i < coverageVec.size(); i += 2) { ALOGD("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } ALOGD("success = %d", success); #endif return success; } } // namespace android <|endoftext|>
<commit_before><commit_msg>WaE: MSVC2008 C2220 unsafe mix of types in operation<commit_after><|endoftext|>
<commit_before>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bit_by_bit.hpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #pragma once #include "constants.hpp" #include "type_utils.hpp" #include "container_utils.hpp" #include "reusable_array.hpp" #include "thread_utils.hpp" #include "math_utils.hpp" #include "stop_watch.hpp" <commit_msg>include logger.hpp in bit_by_bit.hpp<commit_after>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bit_by_bit.hpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #pragma once #include "constants.hpp" #include "type_utils.hpp" #include "container_utils.hpp" #include "reusable_array.hpp" #include "thread_utils.hpp" #include "math_utils.hpp" #include "stop_watch.hpp" #include "logger.hpp"<|endoftext|>
<commit_before>/****************************************************************************** * (C) Copyright 2020 AMIQ Consulting * * 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. * * MODULE: BLOG * PROJECT: Non-blocking socket communication in SV using DPI-C * Description: This is a code snippet from the Blog article mentioned on PROJECT * Link: *******************************************************************************/ #include <arpa/inet.h> #include <errno.h> #include <poll.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <netinet/tcp.h> #include <thread> #include <cstring> #include <string> //#include <svdpi.h> #define BUFFER_SIZE 512 extern "C" void recv_callback(char * msg); extern "C" void consume_time(); static int run_finished = 0; //Client Arguments struct ConnConfiguration { int port; // the port number char *hostname; // the name of server's host }; enum class ConnectionState { UNCONFIGURED, CONFIGURED, CONNECTED }; struct Connection { // Use this to get the actual connection static Connection &instance() { static Connection conn; return conn; } ~Connection() { if (sock_fd != -1) { close(sock_fd); } } std::string state_to_string() const { switch (state) { case ConnectionState::UNCONFIGURED: return "Unconfigured"; case ConnectionState::CONFIGURED: return "Configured"; case ConnectionState::CONNECTED: return "Connected"; default: break; } return "Error"; } ConnectionState get_state() const { return state; } void set_state(const ConnectionState new_state) { // blabla checks if (state == ConnectionState::CONNECTED && new_state == ConnectionState::CONFIGURED) { // Cleanup close(sock_fd); sock_fd = -1; } state = new_state; } void set_sockfd(const int sockfd) { sock_fd = sockfd; // Assign pollfd events recv_event.fd = sockfd; recv_event.events = POLLIN; send_event.fd = sockfd; send_event.events = POLLOUT; } // How many miliseconds to wait for socket events when reading/writing to it void set_timeout(const int miliseconds) { timeout = miliseconds; } /** * Throws: * -1 on error * 1 if sending would block (unlikely) * * Returns number of bytes sent to remote */ int do_send(const char *data, int len) { int status = can_use_connection(); if (!status) { return status; } int event_ready = poll(&send_event, 1, timeout); if (event_ready == -1) { throw -1; } int can_send = send_event.revents & POLLOUT; if (!can_send) { throw 1; } int sent = send(sock_fd, data, len, 0); return sent; } /** * Throws: * -1 on error * 1 if recv would block * * Returns number of bytes received from remote */ int do_recv(char *data, int len) { int status = can_use_connection(); if (!status) { return status; } int event_ready = poll(&recv_event, 1, timeout); if (event_ready == -1) { throw -1; } int can_read = recv_event.revents & POLLIN; if (!can_read) { throw 1; } int received = recv(sock_fd, data, len, 0); return received; } void do_recv_forever() { int r; char data[BUFFER_SIZE+1]; // receive transactions forever while (!run_finished) { try{ r = do_recv(data, BUFFER_SIZE); if (r > 0) { data[r] = 0; recv_callback(data); } } catch (int e) { // Call to consume_time gives the SV simulator some indication that // it can schedule another SV thread for execution. If this exported SV // task is never executed, the simulator will continue to poll on the // socket for receive, without giving any chance to the send thread to execute. // This function is called only when there is nothing to read // (1) - means timeout on poll if(e == 1){ consume_time(); } else if(e == -1){ printf("\n Error while polling socket! errno = %s \n", std::strerror(errno)); } } } } private: int sock_fd; ConnectionState state; pollfd recv_event; pollfd send_event; int timeout; Connection() { state = ConnectionState::UNCONFIGURED; sock_fd = -1; timeout = 0; } Connection(const Connection &) = delete; Connection &operator=(const Connection &) = delete; int can_use_connection() const { if (state != ConnectionState::CONNECTED) { //printf("Client is not connected to remote!\n"); //printf("Client is in state '%s'", state_to_string().c_str()); return false; } return true; } }; // Use this to configure the remote host (the Python server) // Returns 0 if the connection succedeed, 1 otherwise extern "C" int configure(const char *hostname, int port) { Connection &conn = Connection::instance(); conn.set_state(ConnectionState::CONFIGURED); // Create socket int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (sockfd == -1) { perror("Failed to create socket"); exit(1); } // Assign PORT struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); // See if we got an ip or a hostname (like localhost) struct hostent *server = gethostbyname(hostname); if (server == NULL) { servaddr.sin_addr.s_addr = inet_addr(hostname); } else { memcpy((char *) &(servaddr.sin_addr.s_addr), server->h_addr, server->h_length); } // Try to connect int status = 0; do { status = connect(sockfd, (sockaddr *) &servaddr, sizeof(servaddr)); } while (status != 0 && status != EINPROGRESS); if (status != 0) { perror("Connect failed"); exit(1); } printf("Connected to %s:%u\n", hostname, port); conn.set_state(ConnectionState::CONNECTED); conn.set_sockfd(sockfd); return conn.get_state() != ConnectionState::CONNECTED; } extern "C" void set_timeout(const int miliseconds) { Connection &conn = Connection::instance(); conn.set_timeout(miliseconds); } extern "C" int send_data(const char *data, int len) { Connection &conn = Connection::instance(); int result; try{ result = conn.do_send(data, len); } catch (int i){ if(i == -1){ consume_time(); } else if(i == 1){ printf("\n Error while polling socket! errno = %s \n", std::strerror(errno)); } return -1; } return result; } extern "C" int recv_thread() { Connection &conn = Connection::instance(); conn.do_recv_forever(); // During the test, the task is enabled, therefore must return 0 // At the end of the test, the task is disabled, therefore must return 1 return run_finished; } extern "C" void set_run_finish() { printf("\n-------------------Called set_run_finish-------------------------\n"); run_finished = 1; } <commit_msg>Update client.cc<commit_after>/****************************************************************************** * (C) Copyright 2020 AMIQ Consulting * * 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. * * MODULE: BLOG * PROJECT: Non-blocking socket communication in SV using DPI-C * Description: This is a code snippet from the Blog article mentioned on PROJECT * Link: *******************************************************************************/ #include <arpa/inet.h> #include <errno.h> #include <poll.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <netinet/tcp.h> #include <thread> #include <cstring> #include <string> //#include <svdpi.h> #define BUFFER_SIZE 512 extern "C" void recv_callback(char * msg); extern "C" void consume_time(); static int run_finished = 0; //Client Arguments struct ConnConfiguration { int port; // the port number char *hostname; // the name of server's host }; enum class ConnectionState { UNCONFIGURED, CONFIGURED, CONNECTED }; struct Connection { // Use this to get the actual connection static Connection &instance() { static Connection conn; return conn; } ~Connection() { if (sock_fd != -1) { close(sock_fd); } } std::string state_to_string() const { switch (state) { case ConnectionState::UNCONFIGURED: return "Unconfigured"; case ConnectionState::CONFIGURED: return "Configured"; case ConnectionState::CONNECTED: return "Connected"; default: break; } return "Error"; } ConnectionState get_state() const { return state; } void set_state(const ConnectionState new_state) { // blabla checks if (state == ConnectionState::CONNECTED && new_state == ConnectionState::CONFIGURED) { // Cleanup close(sock_fd); sock_fd = -1; } state = new_state; } void set_sockfd(const int sockfd) { sock_fd = sockfd; // Assign pollfd events recv_event.fd = sockfd; recv_event.events = POLLIN; send_event.fd = sockfd; send_event.events = POLLOUT; } // How many miliseconds to wait for socket events when reading/writing to it void set_timeout(const int miliseconds) { timeout = miliseconds; } /** * Throws: * -1 on error * 1 if sending would block (unlikely) * * Returns number of bytes sent to remote */ int do_send(const char *data, int len) { int status = can_use_connection(); if (!status) { return status; } int event_ready = poll(&send_event, 1, timeout); if (event_ready == -1) { throw -1; } int can_send = send_event.revents & POLLOUT; if (!can_send) { throw 1; } int sent = send(sock_fd, data, len, 0); return sent; } /** * Throws: * -1 on error * 1 if recv would block * * Returns number of bytes received from remote */ int do_recv(char *data, int len) { int status = can_use_connection(); if (!status) { return status; } int event_ready = poll(&recv_event, 1, timeout); if (event_ready == -1) { throw -1; } int can_read = recv_event.revents & POLLIN; if (!can_read) { throw 1; } int received = recv(sock_fd, data, len, 0); return received; } void do_recv_forever() { int r; char data[BUFFER_SIZE+1]; // receive transactions forever while (!run_finished) { try{ r = do_recv(data, BUFFER_SIZE); if (r > 0) { data[r] = 0; recv_callback(data); } } catch (int e) { // Call to consume_time gives the SV simulator some indication that // it can schedule another SV thread for execution. If this exported SV // task is never executed, the simulator will continue to poll on the // socket for receive, without giving any chance to the send thread to execute. // This function is called only when there is nothing to read // (1) - means timeout on poll if(e == 1){ consume_time(); } else if(e == -1){ printf("\n Error while polling socket! errno = %s \n", std::strerror(errno)); } } } } private: int sock_fd; ConnectionState state; pollfd recv_event; pollfd send_event; int timeout; Connection() { state = ConnectionState::UNCONFIGURED; sock_fd = -1; timeout = 0; } Connection(const Connection &) = delete; Connection &operator=(const Connection &) = delete; int can_use_connection() const { if (state != ConnectionState::CONNECTED) { //printf("Client is not connected to remote!\n"); //printf("Client is in state '%s'", state_to_string().c_str()); return false; } return true; } }; // Use this to configure the remote host (the Python server) // Returns 0 if the connection succedeed, 1 otherwise extern "C" int configure(const char *hostname, int port) { Connection &conn = Connection::instance(); conn.set_state(ConnectionState::CONFIGURED); // Create socket int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (sockfd == -1) { perror("Failed to create socket"); exit(1); } // Assign PORT struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); // See if we got an ip or a hostname (like localhost) struct hostent *server = gethostbyname(hostname); if (server == NULL) { servaddr.sin_addr.s_addr = inet_addr(hostname); } else { memcpy((char *) &(servaddr.sin_addr.s_addr), server->h_addr, server->h_length); } // Try to connect int status = 0; do { status = connect(sockfd, (sockaddr *) &servaddr, sizeof(servaddr)); } while (status != 0 && status != EINPROGRESS); if (status != 0) { perror("Connect failed"); exit(1); } printf("Connected to %s:%u\n", hostname, port); conn.set_state(ConnectionState::CONNECTED); conn.set_sockfd(sockfd); return conn.get_state() != ConnectionState::CONNECTED; } extern "C" void set_timeout(const int miliseconds) { Connection &conn = Connection::instance(); conn.set_timeout(miliseconds); } extern "C" int send_data(const char *data, int len, int* result) { Connection &conn = Connection::instance(); try{ *result = conn.do_send(data, len); } catch (int i){ if(i == -1){ consume_time(); } else if(i == 1){ printf("\n Error while polling socket! errno = %s \n", std::strerror(errno)); } return -1; } return run_finished; } extern "C" int recv_thread() { Connection &conn = Connection::instance(); conn.do_recv_forever(); // During the test, the task is enabled, therefore must return 0 // At the end of the test, the task is disabled, therefore must return 1 return run_finished; } extern "C" void set_run_finish() { printf("\n-------------------Called set_run_finish-------------------------\n"); run_finished = 1; } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "types.hpp" namespace ox { template<typename T> [[nodiscard]] inline constexpr T rotateLeft(T i, std::size_t shift) { constexpr auto bits = sizeof(i) * 8; return (i << shift) | (i >> (bits - shift)); } template<typename T> [[nodiscard]] constexpr T onMask(int bits = sizeof(T) * 8) { T out = 0; for (auto i = 0; i < bits; i++) { out |= static_cast<T>(1) << i; } return out; } static_assert(onMask<int>(1) == 1); static_assert(onMask<int>(2) == 3); static_assert(onMask<int>(3) == 7); static_assert(onMask<int>(4) == 15); } <commit_msg>[ox/std] Add noexcept to bitops functions<commit_after>/* * Copyright 2015 - 2018 [email protected] * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "types.hpp" namespace ox { template<typename T> [[nodiscard]] inline constexpr T rotateLeft(T i, std::size_t shift) noexcept { constexpr auto bits = sizeof(i) * 8; return (i << shift) | (i >> (bits - shift)); } template<typename T> [[nodiscard]] constexpr T onMask(int bits = sizeof(T) << 3 /* *8 */) noexcept { T out = 0; for (auto i = 0; i < bits; i++) { out |= static_cast<T>(1) << i; } return out; } static_assert(onMask<int>(1) == 1); static_assert(onMask<int>(2) == 3); static_assert(onMask<int>(3) == 7); static_assert(onMask<int>(4) == 15); } <|endoftext|>
<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * Copyright 2013 Justin Crawford <[email protected]> * Copyright 2015 Pawel 'l0ner' Soltys * * 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. */ // Based on: github.com/freebsd/freebsd/blob/master/usr.bin/top/machine.c // Based on: Apple.cpp for load_string/mem_string and apple's documentation #include <sys/types.h> #include <unistd.h> // usleep #include "getsysctl.h" #include "cpu.h" float cpu_percentage( unsigned int cpu_usage_delay ) { int32_t load1[CPUSTATES]; int32_t load2[CPUSTATES]; GETSYSCTL( "kern.cp_time", load1 ); usleep( cpu_usage_delay ); GETSYSCTL( "kern.cp_time", load2 ); // Current load times unsigned long long current_user = load1[CP_USER]; unsigned long long current_system = load1[CP_SYS]; unsigned long long current_nice = load1[CP_NICE]; unsigned long long current_idle = load1[CP_IDLE]; // Next load times unsigned long long next_user = load2[CP_USER]; unsigned long long next_system = load2[CP_SYS]; unsigned long long next_nice = load2[CP_NICE]; unsigned long long next_idle = load2[CP_IDLE]; // Difference between the two unsigned long long diff_user = next_user - current_user; unsigned long long diff_system = next_system - current_system; unsigned long long diff_nice = next_nice - current_nice; unsigned long long diff_idle = next_idle - current_idle; return static_cast<float>( diff_user + diff_system + diff_nice ) / static_cast<float>( diff_user + diff_system + diff_nice + diff_idle ) * 100.0; } <commit_msg>Fix for cpu sysctl failing on 64bit FreeBSD same as commit 80d70b7a4d5ee9a4ba79deae0e840c65ccaf4131<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * Copyright 2013 Justin Crawford <[email protected]> * Copyright 2015 Pawel 'l0ner' Soltys * * 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. */ // Based on: github.com/freebsd/freebsd/blob/master/usr.bin/top/machine.c // Based on: Apple.cpp for load_string/mem_string and apple's documentation #include <sys/types.h> #include <unistd.h> // usleep #include "getsysctl.h" #include "cpu.h" float cpu_percentage( unsigned int cpu_usage_delay ) { #if __x86_64__ || __ppc64__ u_int64_t load1[CPUSTATES]; u_int64_t load2[CPUSTATES]; #else u_int32_t load1[CPUSTATES]; u_int32_t load2[CPUSTATES]; #endif GETSYSCTL( "kern.cp_time", load1 ); usleep( cpu_usage_delay ); GETSYSCTL( "kern.cp_time", load2 ); // Current load times unsigned long long current_user = load1[CP_USER]; unsigned long long current_system = load1[CP_SYS]; unsigned long long current_nice = load1[CP_NICE]; unsigned long long current_idle = load1[CP_IDLE]; // Next load times unsigned long long next_user = load2[CP_USER]; unsigned long long next_system = load2[CP_SYS]; unsigned long long next_nice = load2[CP_NICE]; unsigned long long next_idle = load2[CP_IDLE]; // Difference between the two unsigned long long diff_user = next_user - current_user; unsigned long long diff_system = next_system - current_system; unsigned long long diff_nice = next_nice - current_nice; unsigned long long diff_idle = next_idle - current_idle; return static_cast<float>( diff_user + diff_system + diff_nice ) / static_cast<float>( diff_user + diff_system + diff_nice + diff_idle ) * 100.0; } <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_player.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "audio_player.h" #include "engine.h" void AudioStreamPlayer::_mix_internal(bool p_fadeout) { int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus); //get data AudioFrame *buffer = mix_buffer.ptrw(); int buffer_size = mix_buffer.size(); if (p_fadeout) { buffer_size = MIN(buffer_size, 16); //short fadeout ramp } //mix stream_playback->mix(buffer, 1.0, buffer_size); //multiply volume interpolating to avoid clicks if this changes float target_volume = p_fadeout ? -80.0 : volume_db; float vol = Math::db2linear(mix_volume_db); float vol_inc = (Math::db2linear(target_volume) - vol) / float(buffer_size); for (int i = 0; i < buffer_size; i++) { buffer[i] *= vol; vol += vol_inc; } //set volume for next mix mix_volume_db = target_volume; AudioFrame *targets[4] = { NULL, NULL, NULL, NULL }; if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_MODE_STEREO) { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } else { switch (mix_target) { case MIX_TARGET_STEREO: { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } break; case MIX_TARGET_SURROUND: { for (int i = 0; i < AudioServer::get_singleton()->get_channel_count(); i++) { targets[i] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, i); } } break; case MIX_TARGET_CENTER: { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1); } break; } } for (int c = 0; c < 4; c++) { if (!targets[c]) break; for (int i = 0; i < buffer_size; i++) { targets[c][i] += buffer[i]; } } } void AudioStreamPlayer::_mix_audio() { if (!stream_playback.is_valid()) { return; } if (!active) { return; } if (setseek >= 0.0) { if (stream_playback->is_playing()) { //fade out to avoid pops _mix_internal(true); } stream_playback->start(setseek); setseek = -1.0; //reset seek mix_volume_db = volume_db; //reset ramp } _mix_internal(false); } void AudioStreamPlayer::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { AudioServer::get_singleton()->add_callback(_mix_audios, this); if (autoplay && !Engine::get_singleton()->is_editor_hint()) { play(); } } if (p_what == NOTIFICATION_INTERNAL_PROCESS) { if (!active || (setseek < 0 && !stream_playback->is_playing())) { active = false; emit_signal("finished"); set_process_internal(false); } } if (p_what == NOTIFICATION_EXIT_TREE) { AudioServer::get_singleton()->remove_callback(_mix_audios, this); } } void AudioStreamPlayer::set_stream(Ref<AudioStream> p_stream) { AudioServer::get_singleton()->lock(); mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size()); if (stream_playback.is_valid()) { stream_playback.unref(); stream.unref(); active = false; setseek = -1; } if (p_stream.is_valid()) { stream = p_stream; stream_playback = p_stream->instance_playback(); } AudioServer::get_singleton()->unlock(); if (p_stream.is_valid() && stream_playback.is_null()) { stream.unref(); ERR_FAIL_COND(stream_playback.is_null()); } } Ref<AudioStream> AudioStreamPlayer::get_stream() const { return stream; } void AudioStreamPlayer::set_volume_db(float p_volume) { volume_db = p_volume; } float AudioStreamPlayer::get_volume_db() const { return volume_db; } void AudioStreamPlayer::play(float p_from_pos) { if (stream_playback.is_valid()) { //mix_volume_db = volume_db; do not reset volume ramp here, can cause clicks setseek = p_from_pos; active = true; set_process_internal(true); } } void AudioStreamPlayer::seek(float p_seconds) { if (stream_playback.is_valid()) { setseek = p_seconds; } } void AudioStreamPlayer::stop() { if (stream_playback.is_valid()) { active = false; set_process_internal(false); } } bool AudioStreamPlayer::is_playing() const { if (stream_playback.is_valid()) { return active; //&& stream_playback->is_playing(); } return false; } float AudioStreamPlayer::get_playback_position() { if (stream_playback.is_valid()) { return stream_playback->get_playback_position(); } return 0; } void AudioStreamPlayer::set_bus(const StringName &p_bus) { //if audio is active, must lock this AudioServer::get_singleton()->lock(); bus = p_bus; AudioServer::get_singleton()->unlock(); } StringName AudioStreamPlayer::get_bus() const { for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { if (AudioServer::get_singleton()->get_bus_name(i) == bus) { return bus; } } return "Master"; } void AudioStreamPlayer::set_autoplay(bool p_enable) { autoplay = p_enable; } bool AudioStreamPlayer::is_autoplay_enabled() { return autoplay; } void AudioStreamPlayer::set_mix_target(MixTarget p_target) { mix_target = p_target; } AudioStreamPlayer::MixTarget AudioStreamPlayer::get_mix_target() const { return mix_target; } void AudioStreamPlayer::_set_playing(bool p_enable) { if (p_enable) play(); else stop(); } bool AudioStreamPlayer::_is_active() const { return active; } void AudioStreamPlayer::_validate_property(PropertyInfo &property) const { if (property.name == "bus") { String options; for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { if (i > 0) options += ","; String name = AudioServer::get_singleton()->get_bus_name(i); options += name; } property.hint_string = options; } } void AudioStreamPlayer::_bus_layout_changed() { _change_notify(); } void AudioStreamPlayer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer::set_stream); ClassDB::bind_method(D_METHOD("get_stream"), &AudioStreamPlayer::get_stream); ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioStreamPlayer::set_volume_db); ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioStreamPlayer::get_volume_db); ClassDB::bind_method(D_METHOD("play", "from_position"), &AudioStreamPlayer::play, DEFVAL(0.0)); ClassDB::bind_method(D_METHOD("seek", "to_position"), &AudioStreamPlayer::seek); ClassDB::bind_method(D_METHOD("stop"), &AudioStreamPlayer::stop); ClassDB::bind_method(D_METHOD("is_playing"), &AudioStreamPlayer::is_playing); ClassDB::bind_method(D_METHOD("get_playback_position"), &AudioStreamPlayer::get_playback_position); ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioStreamPlayer::set_bus); ClassDB::bind_method(D_METHOD("get_bus"), &AudioStreamPlayer::get_bus); ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioStreamPlayer::set_autoplay); ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioStreamPlayer::is_autoplay_enabled); ClassDB::bind_method(D_METHOD("set_mix_target", "mix_target"), &AudioStreamPlayer::set_mix_target); ClassDB::bind_method(D_METHOD("get_mix_target"), &AudioStreamPlayer::get_mix_target); ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioStreamPlayer::_set_playing); ClassDB::bind_method(D_METHOD("_is_active"), &AudioStreamPlayer::_is_active); ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioStreamPlayer::_bus_layout_changed); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24"), "set_volume_db", "get_volume_db"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "is_playing"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled"); ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_target", PROPERTY_HINT_ENUM, "Stereo,Surround,Center"), "set_mix_target", "get_mix_target"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus"); ADD_SIGNAL(MethodInfo("finished")); BIND_ENUM_CONSTANT(MIX_TARGET_STEREO); BIND_ENUM_CONSTANT(MIX_TARGET_SURROUND); BIND_ENUM_CONSTANT(MIX_TARGET_CENTER); } AudioStreamPlayer::AudioStreamPlayer() { mix_volume_db = 0; volume_db = 0; autoplay = false; setseek = -1; active = false; mix_target = MIX_TARGET_STEREO; AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); } AudioStreamPlayer::~AudioStreamPlayer() { } <commit_msg>Fix issue 15895, audio streams don't signalling finished after the first one if the audio player is set to play again due to the order of calls in _notification. First it emits the signal, and later it disable the internal processing regardless what the callback did.<commit_after>/*************************************************************************/ /* audio_player.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "audio_player.h" #include "engine.h" void AudioStreamPlayer::_mix_internal(bool p_fadeout) { int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus); //get data AudioFrame *buffer = mix_buffer.ptrw(); int buffer_size = mix_buffer.size(); if (p_fadeout) { buffer_size = MIN(buffer_size, 16); //short fadeout ramp } //mix stream_playback->mix(buffer, 1.0, buffer_size); //multiply volume interpolating to avoid clicks if this changes float target_volume = p_fadeout ? -80.0 : volume_db; float vol = Math::db2linear(mix_volume_db); float vol_inc = (Math::db2linear(target_volume) - vol) / float(buffer_size); for (int i = 0; i < buffer_size; i++) { buffer[i] *= vol; vol += vol_inc; } //set volume for next mix mix_volume_db = target_volume; AudioFrame *targets[4] = { NULL, NULL, NULL, NULL }; if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_MODE_STEREO) { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } else { switch (mix_target) { case MIX_TARGET_STEREO: { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0); } break; case MIX_TARGET_SURROUND: { for (int i = 0; i < AudioServer::get_singleton()->get_channel_count(); i++) { targets[i] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, i); } } break; case MIX_TARGET_CENTER: { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1); } break; } } for (int c = 0; c < 4; c++) { if (!targets[c]) break; for (int i = 0; i < buffer_size; i++) { targets[c][i] += buffer[i]; } } } void AudioStreamPlayer::_mix_audio() { if (!stream_playback.is_valid()) { return; } if (!active) { return; } if (setseek >= 0.0) { if (stream_playback->is_playing()) { //fade out to avoid pops _mix_internal(true); } stream_playback->start(setseek); setseek = -1.0; //reset seek mix_volume_db = volume_db; //reset ramp } _mix_internal(false); } void AudioStreamPlayer::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { AudioServer::get_singleton()->add_callback(_mix_audios, this); if (autoplay && !Engine::get_singleton()->is_editor_hint()) { play(); } } if (p_what == NOTIFICATION_INTERNAL_PROCESS) { if (!active || (setseek < 0 && !stream_playback->is_playing())) { active = false; set_process_internal(false); emit_signal("finished"); } } if (p_what == NOTIFICATION_EXIT_TREE) { AudioServer::get_singleton()->remove_callback(_mix_audios, this); } } void AudioStreamPlayer::set_stream(Ref<AudioStream> p_stream) { AudioServer::get_singleton()->lock(); mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size()); if (stream_playback.is_valid()) { stream_playback.unref(); stream.unref(); active = false; setseek = -1; } if (p_stream.is_valid()) { stream = p_stream; stream_playback = p_stream->instance_playback(); } AudioServer::get_singleton()->unlock(); if (p_stream.is_valid() && stream_playback.is_null()) { stream.unref(); ERR_FAIL_COND(stream_playback.is_null()); } } Ref<AudioStream> AudioStreamPlayer::get_stream() const { return stream; } void AudioStreamPlayer::set_volume_db(float p_volume) { volume_db = p_volume; } float AudioStreamPlayer::get_volume_db() const { return volume_db; } void AudioStreamPlayer::play(float p_from_pos) { if (stream_playback.is_valid()) { //mix_volume_db = volume_db; do not reset volume ramp here, can cause clicks setseek = p_from_pos; active = true; set_process_internal(true); } } void AudioStreamPlayer::seek(float p_seconds) { if (stream_playback.is_valid()) { setseek = p_seconds; } } void AudioStreamPlayer::stop() { if (stream_playback.is_valid()) { active = false; set_process_internal(false); } } bool AudioStreamPlayer::is_playing() const { if (stream_playback.is_valid()) { return active; //&& stream_playback->is_playing(); } return false; } float AudioStreamPlayer::get_playback_position() { if (stream_playback.is_valid()) { return stream_playback->get_playback_position(); } return 0; } void AudioStreamPlayer::set_bus(const StringName &p_bus) { //if audio is active, must lock this AudioServer::get_singleton()->lock(); bus = p_bus; AudioServer::get_singleton()->unlock(); } StringName AudioStreamPlayer::get_bus() const { for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { if (AudioServer::get_singleton()->get_bus_name(i) == bus) { return bus; } } return "Master"; } void AudioStreamPlayer::set_autoplay(bool p_enable) { autoplay = p_enable; } bool AudioStreamPlayer::is_autoplay_enabled() { return autoplay; } void AudioStreamPlayer::set_mix_target(MixTarget p_target) { mix_target = p_target; } AudioStreamPlayer::MixTarget AudioStreamPlayer::get_mix_target() const { return mix_target; } void AudioStreamPlayer::_set_playing(bool p_enable) { if (p_enable) play(); else stop(); } bool AudioStreamPlayer::_is_active() const { return active; } void AudioStreamPlayer::_validate_property(PropertyInfo &property) const { if (property.name == "bus") { String options; for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) { if (i > 0) options += ","; String name = AudioServer::get_singleton()->get_bus_name(i); options += name; } property.hint_string = options; } } void AudioStreamPlayer::_bus_layout_changed() { _change_notify(); } void AudioStreamPlayer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer::set_stream); ClassDB::bind_method(D_METHOD("get_stream"), &AudioStreamPlayer::get_stream); ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioStreamPlayer::set_volume_db); ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioStreamPlayer::get_volume_db); ClassDB::bind_method(D_METHOD("play", "from_position"), &AudioStreamPlayer::play, DEFVAL(0.0)); ClassDB::bind_method(D_METHOD("seek", "to_position"), &AudioStreamPlayer::seek); ClassDB::bind_method(D_METHOD("stop"), &AudioStreamPlayer::stop); ClassDB::bind_method(D_METHOD("is_playing"), &AudioStreamPlayer::is_playing); ClassDB::bind_method(D_METHOD("get_playback_position"), &AudioStreamPlayer::get_playback_position); ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioStreamPlayer::set_bus); ClassDB::bind_method(D_METHOD("get_bus"), &AudioStreamPlayer::get_bus); ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioStreamPlayer::set_autoplay); ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioStreamPlayer::is_autoplay_enabled); ClassDB::bind_method(D_METHOD("set_mix_target", "mix_target"), &AudioStreamPlayer::set_mix_target); ClassDB::bind_method(D_METHOD("get_mix_target"), &AudioStreamPlayer::get_mix_target); ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioStreamPlayer::_set_playing); ClassDB::bind_method(D_METHOD("_is_active"), &AudioStreamPlayer::_is_active); ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioStreamPlayer::_bus_layout_changed); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24"), "set_volume_db", "get_volume_db"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "is_playing"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled"); ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_target", PROPERTY_HINT_ENUM, "Stereo,Surround,Center"), "set_mix_target", "get_mix_target"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus"); ADD_SIGNAL(MethodInfo("finished")); BIND_ENUM_CONSTANT(MIX_TARGET_STEREO); BIND_ENUM_CONSTANT(MIX_TARGET_SURROUND); BIND_ENUM_CONSTANT(MIX_TARGET_CENTER); } AudioStreamPlayer::AudioStreamPlayer() { mix_volume_db = 0; volume_db = 0; autoplay = false; setseek = -1; active = false; mix_target = MIX_TARGET_STEREO; AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed"); } AudioStreamPlayer::~AudioStreamPlayer() { } <|endoftext|>
<commit_before>/*************************************************************************/ /* grid_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "grid_container.h" void GridContainer::_notification(int p_what) { switch(p_what) { case NOTIFICATION_SORT_CHILDREN: { Map<int,int> col_minw; Map<int,int> row_minh; Set<int> col_expanded; Set<int> row_expanded; int sep=get_constant("separation"); int idx=0; int max_row=0; int max_col=0; Size2 size = get_size(); for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; Size2i ms = c->get_combined_minimum_size(); if (col_minw.has(col)) col_minw[col] = MAX(col_minw[col],ms.width); else col_minw[col]=ms.width; if (row_minh.has(row)) row_minh[row] = MAX(row_minh[row],ms.height); else row_minh[row]=ms.height; if (c->get_h_size_flags()&SIZE_EXPAND) col_expanded.insert(col); if (c->get_v_size_flags()&SIZE_EXPAND) row_expanded.insert(row); max_col=MAX(col,max_col); max_row=MAX(row,max_row); idx++; } Size2 ms; int expand_rows=0; int expand_cols=0; for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) { ms.width+=E->get(); if (col_expanded.has(E->key())) expand_cols++; } for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) { ms.height+=E->get(); if (row_expanded.has(E->key())) expand_rows++; } ms.height+=sep*max_row; ms.width+=sep*max_col; int row_expand = expand_rows?(size.y-ms.y)/expand_rows:0; int col_expand = expand_cols?(size.x-ms.x)/expand_cols:0; int col_ofs=0; int row_ofs=0; idx=0; for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; if (col==0) { col_ofs=0; if (row>0 && row_minh.has(row-1)) row_ofs+=row_minh[row-1]+sep+(row_expanded.has(row-1)?row_expand:0); } if (c->is_visible()) { Size2 s; if (col_minw.has(col)) s.width=col_minw[col]; if (row_minh.has(row)) s.height=row_minh[col]; if (row_expanded.has(row)) s.height+=row_expand; if (col_expanded.has(col)) s.width+=col_expand; Point2 p(col_ofs,row_ofs); fit_child_in_rect(c,Rect2(p,s)); } if (col_minw.has(col)) { col_ofs+=col_minw[col]+sep+(col_expanded.has(col)?col_expand:0); } idx++; } } break; } } void GridContainer::set_columns(int p_columns) { columns=p_columns; queue_sort(); } int GridContainer::get_columns() const{ return columns; } void GridContainer::_bind_methods(){ ObjectTypeDB::bind_method(_MD("set_columns","columns"),&GridContainer::set_columns); ObjectTypeDB::bind_method(_MD("get_columns"),&GridContainer::get_columns); ADD_PROPERTY( PropertyInfo(Variant::INT,"columns",PROPERTY_HINT_RANGE,"1,1024,1"),_SCS("set_columns"),_SCS("get_columns")); } Size2 GridContainer::get_minimum_size() const { Map<int,int> col_minw; Map<int,int> row_minh; int sep=get_constant("separation"); int idx=0; int max_row=0; int max_col=0; for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; Size2i ms = c->get_combined_minimum_size(); if (col_minw.has(col)) col_minw[col] = MAX(col_minw[col],ms.width); else col_minw[col]=ms.width; if (row_minh.has(row)) row_minh[row] = MAX(row_minh[row],ms.height); else row_minh[row]=ms.height; max_col=MAX(col,max_col); max_row=MAX(row,max_row); idx++; } Size2 ms; for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) { ms.width+=E->get(); } for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) { ms.height+=E->get(); } ms.height+=sep*max_row; ms.width+=sep*max_col; return ms; } GridContainer::GridContainer() { set_stop_mouse(false); columns=1; } <commit_msg>bad lookup in grid container corrected, cells are properly aligned again. Fixes #1462<commit_after>/*************************************************************************/ /* grid_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "grid_container.h" void GridContainer::_notification(int p_what) { switch(p_what) { case NOTIFICATION_SORT_CHILDREN: { Map<int,int> col_minw; Map<int,int> row_minh; Set<int> col_expanded; Set<int> row_expanded; int sep=get_constant("separation"); int idx=0; int max_row=0; int max_col=0; Size2 size = get_size(); for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; Size2i ms = c->get_combined_minimum_size(); if (col_minw.has(col)) col_minw[col] = MAX(col_minw[col],ms.width); else col_minw[col]=ms.width; if (row_minh.has(row)) row_minh[row] = MAX(row_minh[row],ms.height); else row_minh[row]=ms.height; // print_line("store row "+itos(row)+" mw "+itos(ms.height)); if (c->get_h_size_flags()&SIZE_EXPAND) col_expanded.insert(col); if (c->get_v_size_flags()&SIZE_EXPAND) row_expanded.insert(row); max_col=MAX(col,max_col); max_row=MAX(row,max_row); idx++; } Size2 ms; int expand_rows=0; int expand_cols=0; for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) { ms.width+=E->get(); if (col_expanded.has(E->key())) expand_cols++; } for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) { ms.height+=E->get(); if (row_expanded.has(E->key())) expand_rows++; } ms.height+=sep*max_row; ms.width+=sep*max_col; int row_expand = expand_rows?(size.y-ms.y)/expand_rows:0; int col_expand = expand_cols?(size.x-ms.x)/expand_cols:0; int col_ofs=0; int row_ofs=0; idx=0; for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; if (col==0) { col_ofs=0; if (row>0 && row_minh.has(row-1)) row_ofs+=row_minh[row-1]+sep+(row_expanded.has(row-1)?row_expand:0); } Size2 s; if (col_minw.has(col)) s.width=col_minw[col]; if (row_minh.has(row)) s.height=row_minh[row]; if (row_expanded.has(row)) s.height+=row_expand; if (col_expanded.has(col)) s.width+=col_expand; Point2 p(col_ofs,row_ofs); // print_line("col: "+itos(col)+" row: "+itos(row)+" col_ofs: "+itos(col_ofs)+" row_ofs: "+itos(row_ofs)); fit_child_in_rect(c,Rect2(p,s)); //print_line("col: "+itos(col)+" row: "+itos(row)+" rect: "+Rect2(p,s)); if (col_minw.has(col)) { col_ofs+=col_minw[col]+sep+(col_expanded.has(col)?col_expand:0); } idx++; } } break; } } void GridContainer::set_columns(int p_columns) { columns=p_columns; queue_sort(); } int GridContainer::get_columns() const{ return columns; } void GridContainer::_bind_methods(){ ObjectTypeDB::bind_method(_MD("set_columns","columns"),&GridContainer::set_columns); ObjectTypeDB::bind_method(_MD("get_columns"),&GridContainer::get_columns); ADD_PROPERTY( PropertyInfo(Variant::INT,"columns",PROPERTY_HINT_RANGE,"1,1024,1"),_SCS("set_columns"),_SCS("get_columns")); } Size2 GridContainer::get_minimum_size() const { Map<int,int> col_minw; Map<int,int> row_minh; int sep=get_constant("separation"); int idx=0; int max_row=0; int max_col=0; for(int i=0;i<get_child_count();i++) { Control *c = get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; int row = idx / columns; int col = idx % columns; Size2i ms = c->get_combined_minimum_size(); if (col_minw.has(col)) col_minw[col] = MAX(col_minw[col],ms.width); else col_minw[col]=ms.width; if (row_minh.has(row)) row_minh[row] = MAX(row_minh[row],ms.height); else row_minh[row]=ms.height; max_col=MAX(col,max_col); max_row=MAX(row,max_row); idx++; } Size2 ms; for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) { ms.width+=E->get(); } for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) { ms.height+=E->get(); } ms.height+=sep*max_row; ms.width+=sep*max_col; return ms; } GridContainer::GridContainer() { set_stop_mouse(false); columns=1; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Environment.h" #include <regex> #include <set> #include "Handle.h" #include "ErrorUtilities.h" #include "StringUtilities.h" static const wregex EnvVarRegex = wregex(L"(.+)=(.*)"); // In upper case static const set<wstring> AutoOverrides = { L"APPDATA", L"HOMEPATH", L"LOCALAPPDATA", L"USERDOMAIN", L"USERDOMAIN_ROAMINGPROFILE", L"USERNAME", L"USERPROFILE" }; Result<Environment> Environment::CreateForCurrentProcess() { auto environment = GetEnvironmentStringsW(); Environment newEnvironment; try { newEnvironment.CreateVariableMap(environment); } catch(...) { } FreeEnvironmentStringsW(environment); return newEnvironment; } Result<Environment> Environment::CreateForUser(Handle& token, bool inherit) { Environment newEnvironment; LPVOID environment; if (!CreateEnvironmentBlock(&environment, token, inherit)) { return Result<Environment>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"CreateEnvironmentBlock")); } try { newEnvironment.CreateVariableMap(environment); } catch (...) { } DestroyEnvironmentBlock(environment); return newEnvironment; } Environment Environment::CreateFormString(wstring variables) { auto vars = StringUtilities::Split(variables, L"\n"); Environment environment; wsmatch matchResult; for (auto varsIterrator = vars.begin(); varsIterrator != vars.end(); ++varsIterrator) { if (!regex_search(*varsIterrator, matchResult, EnvVarRegex)) { continue; } auto envName = matchResult._At(1).str(); auto envValue = matchResult._At(2).str(); environment._vars[envName] = envValue; environment._empty = false; } return environment; } Environment Environment::Override(Environment& destinarionEnvironment, Environment& sourceEnvironment) { Environment targetEnvironment; for (auto varsIterator = destinarionEnvironment._vars.begin(); varsIterator != destinarionEnvironment._vars.end(); ++varsIterator) { targetEnvironment._vars[varsIterator->first] = varsIterator->second; targetEnvironment._empty = false; } auto autoOverrides = GetAutoOverrides(); for (auto varsIterator = sourceEnvironment._vars.begin(); varsIterator != sourceEnvironment._vars.end(); ++varsIterator) { auto varNameInLowCase = StringUtilities::Convert(varsIterator->first, toupper); if (autoOverrides.find(varNameInLowCase) != autoOverrides.end()) { targetEnvironment._vars[varsIterator->first] = varsIterator->second; } } return targetEnvironment; } Environment::~Environment() { for (auto environmentBlockIterator = _environmentBlocks.begin(); environmentBlockIterator != _environmentBlocks.end(); ++environmentBlockIterator) { delete *environmentBlockIterator; } _environmentBlocks.clear(); } void Environment::CreateVariableMap(LPVOID environment) { _vars.clear(); auto curVar = static_cast<LPCWSTR>(environment); size_t len; do { wstring curVarValue(curVar); len = curVarValue.size(); if (len == 0) { continue; } curVar += len + 1; wsmatch matchResult; if (!regex_search(curVarValue, matchResult, EnvVarRegex)) { continue; } auto envName = matchResult._At(1).str(); auto envValue = matchResult._At(2).str(); _vars[envName] = envValue; _empty = false; } while (len > 0); } LPVOID* Environment::CreateEnvironmentFromMap() { size_t size = 0; for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { size += varsIterator->first.size() + varsIterator->second.size() + 2; } size++; auto environment = new _TCHAR[size]; memset(environment, 0, sizeof(_TCHAR) * size); size_t pointer = 0; for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { auto curSize = varsIterator->first.size(); memcpy(environment + pointer, varsIterator->first.c_str(), curSize * sizeof(_TCHAR)); pointer += curSize; environment[pointer] = _TCHAR('='); pointer ++; curSize = varsIterator->second.size(); memcpy(environment + pointer, varsIterator->second.c_str(), curSize * sizeof(_TCHAR)); pointer += curSize; pointer ++; } return reinterpret_cast<LPVOID*>(environment); } LPVOID* Environment::CreateEnvironment() { if(_empty) { return nullptr; } auto environment = CreateEnvironmentFromMap(); _environmentBlocks.push_back(environment); return environment; } wstring Environment::TryGetValue(wstring variableName) { auto curVarNameInLowCase = StringUtilities::Convert(variableName, tolower); for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { auto varNameInLowCase = StringUtilities::Convert(varsIterator->first, tolower); if (varNameInLowCase == curVarNameInLowCase) { return varsIterator->second; } } return L""; } set<wstring> Environment::GetAutoOverrides() { return AutoOverrides; }<commit_msg>Add HOMEDRIVE env var to the list of overrides<commit_after>#include "stdafx.h" #include "Environment.h" #include <regex> #include <set> #include "Handle.h" #include "ErrorUtilities.h" #include "StringUtilities.h" static const wregex EnvVarRegex = wregex(L"(.+)=(.*)"); // In upper case static const set<wstring> AutoOverrides = { L"APPDATA", L"HOMEPATH", L"HOMEDRIVE", L"LOCALAPPDATA", L"USERDOMAIN", L"USERDOMAIN_ROAMINGPROFILE", L"USERNAME", L"USERPROFILE" }; Result<Environment> Environment::CreateForCurrentProcess() { auto environment = GetEnvironmentStringsW(); Environment newEnvironment; try { newEnvironment.CreateVariableMap(environment); } catch(...) { } FreeEnvironmentStringsW(environment); return newEnvironment; } Result<Environment> Environment::CreateForUser(Handle& token, bool inherit) { Environment newEnvironment; LPVOID environment; if (!CreateEnvironmentBlock(&environment, token, inherit)) { return Result<Environment>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"CreateEnvironmentBlock")); } try { newEnvironment.CreateVariableMap(environment); } catch (...) { } DestroyEnvironmentBlock(environment); return newEnvironment; } Environment Environment::CreateFormString(wstring variables) { auto vars = StringUtilities::Split(variables, L"\n"); Environment environment; wsmatch matchResult; for (auto varsIterrator = vars.begin(); varsIterrator != vars.end(); ++varsIterrator) { if (!regex_search(*varsIterrator, matchResult, EnvVarRegex)) { continue; } auto envName = matchResult._At(1).str(); auto envValue = matchResult._At(2).str(); environment._vars[envName] = envValue; environment._empty = false; } return environment; } Environment Environment::Override(Environment& destinarionEnvironment, Environment& sourceEnvironment) { Environment targetEnvironment; for (auto varsIterator = destinarionEnvironment._vars.begin(); varsIterator != destinarionEnvironment._vars.end(); ++varsIterator) { targetEnvironment._vars[varsIterator->first] = varsIterator->second; targetEnvironment._empty = false; } auto autoOverrides = GetAutoOverrides(); for (auto varsIterator = sourceEnvironment._vars.begin(); varsIterator != sourceEnvironment._vars.end(); ++varsIterator) { auto varNameInLowCase = StringUtilities::Convert(varsIterator->first, toupper); if (autoOverrides.find(varNameInLowCase) != autoOverrides.end()) { targetEnvironment._vars[varsIterator->first] = varsIterator->second; } } return targetEnvironment; } Environment::~Environment() { for (auto environmentBlockIterator = _environmentBlocks.begin(); environmentBlockIterator != _environmentBlocks.end(); ++environmentBlockIterator) { delete *environmentBlockIterator; } _environmentBlocks.clear(); } void Environment::CreateVariableMap(LPVOID environment) { _vars.clear(); auto curVar = static_cast<LPCWSTR>(environment); size_t len; do { wstring curVarValue(curVar); len = curVarValue.size(); if (len == 0) { continue; } curVar += len + 1; wsmatch matchResult; if (!regex_search(curVarValue, matchResult, EnvVarRegex)) { continue; } auto envName = matchResult._At(1).str(); auto envValue = matchResult._At(2).str(); _vars[envName] = envValue; _empty = false; } while (len > 0); } LPVOID* Environment::CreateEnvironmentFromMap() { size_t size = 0; for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { size += varsIterator->first.size() + varsIterator->second.size() + 2; } size++; auto environment = new _TCHAR[size]; memset(environment, 0, sizeof(_TCHAR) * size); size_t pointer = 0; for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { auto curSize = varsIterator->first.size(); memcpy(environment + pointer, varsIterator->first.c_str(), curSize * sizeof(_TCHAR)); pointer += curSize; environment[pointer] = _TCHAR('='); pointer ++; curSize = varsIterator->second.size(); memcpy(environment + pointer, varsIterator->second.c_str(), curSize * sizeof(_TCHAR)); pointer += curSize; pointer ++; } return reinterpret_cast<LPVOID*>(environment); } LPVOID* Environment::CreateEnvironment() { if(_empty) { return nullptr; } auto environment = CreateEnvironmentFromMap(); _environmentBlocks.push_back(environment); return environment; } wstring Environment::TryGetValue(wstring variableName) { auto curVarNameInLowCase = StringUtilities::Convert(variableName, tolower); for (auto varsIterator = _vars.begin(); varsIterator != _vars.end(); ++varsIterator) { auto varNameInLowCase = StringUtilities::Convert(varsIterator->first, tolower); if (varNameInLowCase == curVarNameInLowCase) { return varsIterator->second; } } return L""; } set<wstring> Environment::GetAutoOverrides() { return AutoOverrides; }<|endoftext|>
<commit_before>// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | \ // RUN: FileCheck -check-prefixes=CHECK,CHECK-OLD %s // RUN: %clang_cc1 -triple x86_64-apple-darwin -new-struct-path-tbaa \ // RUN: -emit-llvm -o - -O1 %s | \ // RUN: FileCheck -check-prefixes=CHECK,CHECK-NEW %s // // Check that we generate TBAA metadata for struct copies correctly. struct A { short s; int i; char c; int j; }; typedef A __attribute__((may_alias)) AA; void copy(A *a1, A *a2) { // CHECK-LABEL: _Z4copyP1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 4 dereferenceable(16) %{{.*}}, i8* noalias align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_A:![0-9]*]] *a1 = *a2; } struct B { char c; A a; int i; }; void copy2(B *b1, B *b2) { // CHECK-LABEL: _Z5copy2P1BS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 4 dereferenceable(24) %{{.*}}, i8* noalias align 4 dereferenceable(24) %{{.*}}, i64 24, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS2:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_B:![0-9]*]] *b1 = *b2; } struct S { _Complex char cc; _Complex int ci; }; union U { _Complex int ci; S s; }; void copy3(U *u1, U *u2) { // CHECK-LABEL: _Z5copy3P1US0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 4 dereferenceable(12) %{{.*}}, i8* noalias align 4 dereferenceable(12) %{{.*}}, i64 12, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS3:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_U:![0-9]*]] *u1 = *u2; } // Make sure that zero-length bitfield works. struct C { char a; int : 0; // Shall not be ignored; see r185018. char b; char c; } __attribute__((ms_struct)); void copy4(C *c1, C *c2) { // CHECK-LABEL: _Z5copy4P1CS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 1 dereferenceable(3) {{.*}}, i8* noalias align 1 dereferenceable(3) {{.*}}, i64 3, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS4:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_C:![0-9]*]] *c1 = *c2; } struct D { char a; int : 0; char b; char c; }; void copy5(D *d1, D *d2) { // CHECK-LABEL: _Z5copy5P1DS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 1 dereferenceable(6) {{.*}}, i8* noalias align 1 dereferenceable(6) {{.*}}, i64 6, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS5:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_D:![0-9]*]] *d1 = *d2; } void copy6(AA *a1, A *a2) { // CHECK-LABEL: _Z5copy6P1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 4 dereferenceable(16) %{{.*}}, i8* noalias align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS]] // CHECK-NEW-SAME: !tbaa [[TAG_char:![0-9]*]] *a1 = *a2; } void copy7(A *a1, AA *a2) { // CHECK-LABEL: _Z5copy7P1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias align 4 dereferenceable(16) %{{.*}}, i8* noalias align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS]] // CHECK-NEW-SAME: !tbaa [[TAG_char]] *a1 = *a2; } // CHECK-OLD: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}} // CHECK-OLD: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}} // CHECK-OLD: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0} // CHECK-OLD: [[INT]] = !{!"int", [[CHAR]] // CHECK-OLD: [[TAG_CHAR:!.*]] = !{[[CHAR]], [[CHAR]], i64 0} // (offset, size) = (0,1) char; (4,2) short; (8,4) int; (12,1) char; (16,4) int; (20,4) int // CHECK-OLD: [[TS2]] = !{i64 0, i64 1, !{{.*}}, i64 4, i64 2, !{{.*}}, i64 8, i64 4, !{{.*}}, i64 12, i64 1, !{{.*}}, i64 16, i64 4, {{.*}}, i64 20, i64 4, {{.*}}} // (offset, size) = (0,8) char; (0,2) char; (4,8) char // CHECK-OLD: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, i64 8, !{{.*}}} // CHECK-OLD: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 1, [[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]} // CHECK-OLD: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 1, [[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]} // CHECK-NEW-DAG: [[TYPE_char:!.*]] = !{{{.*}}, i64 1, !"omnipotent char"} // CHECK-NEW-DAG: [[TAG_char]] = !{[[TYPE_char]], [[TYPE_char]], i64 0, i64 0} // CHECK-NEW-DAG: [[TYPE_short:!.*]] = !{[[TYPE_char]], i64 2, !"short"} // CHECK-NEW-DAG: [[TYPE_int:!.*]] = !{[[TYPE_char]], i64 4, !"int"} // CHECK-NEW-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 16, !"_ZTS1A", [[TYPE_short]], i64 0, i64 2, [[TYPE_int]], i64 4, i64 4, [[TYPE_char]], i64 8, i64 1, [[TYPE_int]], i64 12, i64 4} // CHECK-NEW-DAG: [[TAG_A]] = !{[[TYPE_A]], [[TYPE_A]], i64 0, i64 16} // CHECK-NEW-DAG: [[TYPE_B:!.*]] = !{[[TYPE_char]], i64 24, !"_ZTS1B", [[TYPE_char]], i64 0, i64 1, [[TYPE_A]], i64 4, i64 16, [[TYPE_int]], i64 20, i64 4} // CHECK-NEW-DAG: [[TAG_B]] = !{[[TYPE_B]], [[TYPE_B]], i64 0, i64 24} // CHECK-NEW-DAG: [[TAG_U]] = !{[[TYPE_char]], [[TYPE_char]], i64 0, i64 12} // CHECK-NEW-DAG: [[TYPE_C:!.*]] = !{[[TYPE_char]], i64 3, !"_ZTS1C", [[TYPE_char]], i64 0, i64 1, [[TYPE_char]], i64 1, i64 1, [[TYPE_char]], i64 2, i64 1} // CHECK-NEW-DAG: [[TAG_C]] = !{[[TYPE_C]], [[TYPE_C]], i64 0, i64 3} // CHECK-NEW-DAG: [[TYPE_D:!.*]] = !{[[TYPE_char]], i64 6, !"_ZTS1D", [[TYPE_char]], i64 0, i64 1, [[TYPE_char]], i64 4, i64 1, [[TYPE_char]], i64 5, i64 1} // CHECK-NEW-DAG: [[TAG_D]] = !{[[TYPE_D]], [[TYPE_D]], i64 0, i64 6} <commit_msg>[NFC] Updated tests after r368875<commit_after>// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | \ // RUN: FileCheck -check-prefixes=CHECK,CHECK-OLD %s // RUN: %clang_cc1 -triple x86_64-apple-darwin -new-struct-path-tbaa \ // RUN: -emit-llvm -o - -O1 %s | \ // RUN: FileCheck -check-prefixes=CHECK,CHECK-NEW %s // // Check that we generate TBAA metadata for struct copies correctly. struct A { short s; int i; char c; int j; }; typedef A __attribute__((may_alias)) AA; void copy(A *a1, A *a2) { // CHECK-LABEL: _Z4copyP1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 dereferenceable(16) %{{.*}}, i8* align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_A:![0-9]*]] *a1 = *a2; } struct B { char c; A a; int i; }; void copy2(B *b1, B *b2) { // CHECK-LABEL: _Z5copy2P1BS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 dereferenceable(24) %{{.*}}, i8* align 4 dereferenceable(24) %{{.*}}, i64 24, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS2:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_B:![0-9]*]] *b1 = *b2; } struct S { _Complex char cc; _Complex int ci; }; union U { _Complex int ci; S s; }; void copy3(U *u1, U *u2) { // CHECK-LABEL: _Z5copy3P1US0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 dereferenceable(12) %{{.*}}, i8* align 4 dereferenceable(12) %{{.*}}, i64 12, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS3:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_U:![0-9]*]] *u1 = *u2; } // Make sure that zero-length bitfield works. struct C { char a; int : 0; // Shall not be ignored; see r185018. char b; char c; } __attribute__((ms_struct)); void copy4(C *c1, C *c2) { // CHECK-LABEL: _Z5copy4P1CS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 dereferenceable(3) {{.*}}, i8* align 1 dereferenceable(3) {{.*}}, i64 3, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS4:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_C:![0-9]*]] *c1 = *c2; } struct D { char a; int : 0; char b; char c; }; void copy5(D *d1, D *d2) { // CHECK-LABEL: _Z5copy5P1DS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 dereferenceable(6) {{.*}}, i8* align 1 dereferenceable(6) {{.*}}, i64 6, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS5:!.*]] // CHECK-NEW-SAME: !tbaa [[TAG_D:![0-9]*]] *d1 = *d2; } void copy6(AA *a1, A *a2) { // CHECK-LABEL: _Z5copy6P1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 dereferenceable(16) %{{.*}}, i8* align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS]] // CHECK-NEW-SAME: !tbaa [[TAG_char:![0-9]*]] *a1 = *a2; } void copy7(A *a1, AA *a2) { // CHECK-LABEL: _Z5copy7P1AS0_ // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 dereferenceable(16) %{{.*}}, i8* align 4 dereferenceable(16) %{{.*}}, i64 16, i1 false) // CHECK-OLD-SAME: !tbaa.struct [[TS]] // CHECK-NEW-SAME: !tbaa [[TAG_char]] *a1 = *a2; } // CHECK-OLD: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}} // CHECK-OLD: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}} // CHECK-OLD: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0} // CHECK-OLD: [[INT]] = !{!"int", [[CHAR]] // CHECK-OLD: [[TAG_CHAR:!.*]] = !{[[CHAR]], [[CHAR]], i64 0} // (offset, size) = (0,1) char; (4,2) short; (8,4) int; (12,1) char; (16,4) int; (20,4) int // CHECK-OLD: [[TS2]] = !{i64 0, i64 1, !{{.*}}, i64 4, i64 2, !{{.*}}, i64 8, i64 4, !{{.*}}, i64 12, i64 1, !{{.*}}, i64 16, i64 4, {{.*}}, i64 20, i64 4, {{.*}}} // (offset, size) = (0,8) char; (0,2) char; (4,8) char // CHECK-OLD: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, i64 8, !{{.*}}} // CHECK-OLD: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 1, [[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]} // CHECK-OLD: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 1, [[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]} // CHECK-NEW-DAG: [[TYPE_char:!.*]] = !{{{.*}}, i64 1, !"omnipotent char"} // CHECK-NEW-DAG: [[TAG_char]] = !{[[TYPE_char]], [[TYPE_char]], i64 0, i64 0} // CHECK-NEW-DAG: [[TYPE_short:!.*]] = !{[[TYPE_char]], i64 2, !"short"} // CHECK-NEW-DAG: [[TYPE_int:!.*]] = !{[[TYPE_char]], i64 4, !"int"} // CHECK-NEW-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 16, !"_ZTS1A", [[TYPE_short]], i64 0, i64 2, [[TYPE_int]], i64 4, i64 4, [[TYPE_char]], i64 8, i64 1, [[TYPE_int]], i64 12, i64 4} // CHECK-NEW-DAG: [[TAG_A]] = !{[[TYPE_A]], [[TYPE_A]], i64 0, i64 16} // CHECK-NEW-DAG: [[TYPE_B:!.*]] = !{[[TYPE_char]], i64 24, !"_ZTS1B", [[TYPE_char]], i64 0, i64 1, [[TYPE_A]], i64 4, i64 16, [[TYPE_int]], i64 20, i64 4} // CHECK-NEW-DAG: [[TAG_B]] = !{[[TYPE_B]], [[TYPE_B]], i64 0, i64 24} // CHECK-NEW-DAG: [[TAG_U]] = !{[[TYPE_char]], [[TYPE_char]], i64 0, i64 12} // CHECK-NEW-DAG: [[TYPE_C:!.*]] = !{[[TYPE_char]], i64 3, !"_ZTS1C", [[TYPE_char]], i64 0, i64 1, [[TYPE_char]], i64 1, i64 1, [[TYPE_char]], i64 2, i64 1} // CHECK-NEW-DAG: [[TAG_C]] = !{[[TYPE_C]], [[TYPE_C]], i64 0, i64 3} // CHECK-NEW-DAG: [[TYPE_D:!.*]] = !{[[TYPE_char]], i64 6, !"_ZTS1D", [[TYPE_char]], i64 0, i64 1, [[TYPE_char]], i64 4, i64 1, [[TYPE_char]], i64 5, i64 1} // CHECK-NEW-DAG: [[TAG_D]] = !{[[TYPE_D]], [[TYPE_D]], i64 0, i64 6} <|endoftext|>
<commit_before>#include <UnitTest++/UnitTest++.h> #include <memory> #include <sstream> #include <utility> #include "Article.h" #include "JsonSerializer.h" SUITE(ArticleJsonSerializerTests) { using namespace WikiWalker; #define WW_PROTOCOL_HEADER \ R"("program":"wikiwalker","scheme-version":2,"ArticleCollection":)" TEST(WriteUnanalyzedArticleWithoutLinks_LinksIsNull) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; ac.add(std::make_shared<Article>("Farm")); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":null})" "}" "}", oss.str()); } TEST(WriteAnalyzedArticleWithoutLinks_LinksIsEmptyArray) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; auto a = std::make_shared<Article>("Farm"); ac.add(a); a->analyzed(true); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":[]})" "}" "}", oss.str()); } TEST(WriteArticleWithOneLink) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":["Animal"]})" "}" "}", oss.str()); } TEST(WriteArticleWithMultipleLinks) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); auto al1 = std::make_shared<Article>("Animal"), al2 = std::make_shared<Article>("Pig"), al3 = std::make_shared<Article>("Equality"); a->addLink(al1); a->addLink(al2); a->addLink(al3); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":["Animal","Pig","Equality"]})" "}" "}", oss.str()); } TEST(WriteEmptyArticleCollection) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{}" "}", oss.str()); } TEST(WriteArticleCollection_OneUnanalyzedArticleWithoutLinks_LinksIsNull) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto linked = std::make_shared<Article>("Foo"); ac.add(linked); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Foo":{"forward_links":null})" "}" "}", oss.str()); } TEST(WriteArticleCollection_OneAnalyzedArticleWithoutLinks_LinksIsEmptyArray) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto a = std::make_shared<Article>("Foo"); a->analyzed(true); ac.add(a); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Foo":{"forward_links":[]})" "}" "}", oss.str()); } TEST( WriteArticleCollection_MultipleArticles_WithMultipleLinks_MatchesExpected) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto a = std::make_shared<Article>("Foo"); auto b = std::make_shared<Article>("Bar"); auto c = std::make_shared<Article>("Baz"); a->addLink(b); b->addLink(a); b->addLink(c); ac.add(a); ac.add(b); ac.add(c); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Bar":{"forward_links":["Foo","Baz"]},)" R"("Baz":{"forward_links":null},)" R"("Foo":{"forward_links":["Bar"]})" "}" "}", oss.str()); } TEST(SerializeArticleWithOnlyNullptr_NullptrWillBeSkipped) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); { // will be skipped on serialization, since it'll become nullptr auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); } atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":[]})" "}" "}", oss.str()); } TEST(SerializeArticleWithValidArticleAndANullptr_NullptrWillBeSkipped) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); { // will be skipped on serialization, since it'll become nullptr auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); } auto linked2 = std::make_shared<Article>("Barn"); a->addLink(linked2); atj.serialize(ac, oss); CHECK_EQUAL("{" WW_PROTOCOL_HEADER "{" R"("Farm":{"forward_links":["Barn"]})" "}" "}", oss.str()); } } <commit_msg>Use string::fine instead of direct compare<commit_after>#include <UnitTest++/UnitTest++.h> #include <memory> #include <sstream> #include <string> #include <utility> #include "Article.h" #include "JsonSerializer.h" #include "StringUtils.h" SUITE(ArticleJsonSerializerTests) { using namespace WikiWalker; #define WW_PROTOCOL_COLLECTION_KEY R"("ArticleCollection":)" #define WW_PROTOCOL_HEADER_1 R"("program":"wikiwalker")" #define WW_PROTOCOL_HEADER_2 R"("scheme-version":2)" TEST(WriteUnanalyzedArticleWithoutLinks_LinksIsNull) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; ac.add(std::make_shared<Article>("Farm")); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":null}})") != std::string::npos); } TEST(WriteAnalyzedArticleWithoutLinks_LinksIsEmptyArray) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; auto a = std::make_shared<Article>("Farm"); ac.add(a); a->analyzed(true); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":[]}})") != std::string::npos); } TEST(WriteArticleWithOneLink) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":["Animal"]}})") != std::string::npos); } TEST(WriteArticleWithMultipleLinks) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); auto al1 = std::make_shared<Article>("Animal"), al2 = std::make_shared<Article>("Pig"), al3 = std::make_shared<Article>("Equality"); a->addLink(al1); a->addLink(al2); a->addLink(al3); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find( WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":["Animal","Pig","Equality"]}})") != std::string::npos); } TEST(WriteEmptyArticleCollection) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY "{}") != std::string::npos); } TEST(WriteArticleCollection_OneUnanalyzedArticleWithoutLinks_LinksIsNull) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto linked = std::make_shared<Article>("Foo"); ac.add(linked); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Foo":{"forward_links":null}})") != std::string::npos); } TEST(WriteArticleCollection_OneAnalyzedArticleWithoutLinks_LinksIsEmptyArray) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto a = std::make_shared<Article>("Foo"); a->analyzed(true); ac.add(a); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Foo":{"forward_links":[]}})") != std::string::npos); } TEST( WriteArticleCollection_MultipleArticles_WithMultipleLinks_MatchesExpected) { JsonSerializer atj; ArticleCollection ac; std::ostringstream oss; auto a = std::make_shared<Article>("Foo"); auto b = std::make_shared<Article>("Bar"); auto c = std::make_shared<Article>("Baz"); a->addLink(b); b->addLink(a); b->addLink(c); ac.add(a); ac.add(b); ac.add(c); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY "{" R"("Bar":{"forward_links":["Foo","Baz"]},)" R"("Baz":{"forward_links":null},)" R"("Foo":{"forward_links":["Bar"]})" "}") != std::string::npos); } TEST(SerializeArticleWithOnlyNullptr_NullptrWillBeSkipped) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); { // will be skipped on serialization, since it'll become nullptr auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); } atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":[]}})") != std::string::npos); } TEST(SerializeArticleWithValidArticleAndANullptr_NullptrWillBeSkipped) { JsonSerializer atj; std::ostringstream oss; ArticleCollection ac; // yes, only a is inserted, since we want to emulate article-only auto a = std::make_shared<Article>("Farm"); ac.add(a); { // will be skipped on serialization, since it'll become nullptr auto linked = std::make_shared<Article>("Animal"); a->addLink(linked); } auto linked2 = std::make_shared<Article>("Barn"); a->addLink(linked2); atj.serialize(ac, oss); auto serString = oss.str(); CHECK(serString.find(WW_PROTOCOL_HEADER_1) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_HEADER_2) != std::string::npos); CHECK(serString.find(WW_PROTOCOL_COLLECTION_KEY R"({"Farm":{"forward_links":["Barn"]}})") != std::string::npos); } } <|endoftext|>
<commit_before>#include "atomic.hh" #include "locks.hh" #include <pthread.h> #include <unistd.h> #include "assert.h" #define NUM_THREADS 90 #define NUM_ITEMS 100000 struct thread_args { SyncObject mutex; SyncObject gate; AtomicQueue<int> queue; int counter; }; void *launch_consumer_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); int count(0); std::queue<int> outQueue; LockHolder lh(args->mutex); LockHolder lhg(args->gate); args->counter++; lhg.unlock(); args->gate.notify(); args->mutex.wait(); lh.unlock(); while(count < NUM_THREADS * NUM_ITEMS) { args->queue.size(); args->queue.getAll(outQueue); while (!outQueue.empty()) { count++; outQueue.pop(); } } sleep(1); assert(args->queue.empty()); assert(outQueue.empty()); return static_cast<void *>(0); } void *launch_test_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); int i(0); LockHolder lh(args->mutex); LockHolder lhg(args->gate); args->counter++; lhg.unlock(); args->gate.notify(); args->mutex.wait(); lh.unlock(); for (i = 0; i < NUM_ITEMS; ++i) { args->queue.push(i); } return static_cast<void *>(0); } int main() { pthread_t threads[NUM_THREADS]; pthread_t consumer; int i(0), rc(0), result(-1); struct thread_args args; alarm(60); args.counter = 0; rc = pthread_create(&consumer, NULL, launch_consumer_thread, &args); assert(rc == 0); for (i = 0; i < NUM_THREADS; ++i) { rc = pthread_create(&threads[i], NULL, launch_test_thread, &args); assert(rc == 0); } // Wait for all threads to reach the starting gate int counter; while (true) { LockHolder lh(args.gate); counter = args.counter; if (counter == NUM_THREADS + 1) { break; } args.gate.wait(); } args.mutex.notify(); for (i = 0; i < NUM_THREADS; ++i) { rc = pthread_join(threads[i], reinterpret_cast<void **>(&result)); assert(rc == 0); assert(result == 0); } rc = pthread_join(consumer, reinterpret_cast<void **>(&result)); assert(rc == 0); assert(result == 0); assert(args.queue.empty()); } <commit_msg>Remove compile warnings<commit_after>#include "atomic.hh" #include "locks.hh" #include <pthread.h> #include <unistd.h> #include "assert.h" #define NUM_THREADS 90 #define NUM_ITEMS 100000 struct thread_args { SyncObject mutex; SyncObject gate; AtomicQueue<int> queue; int counter; }; extern "C" { static void *launch_consumer_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); int count(0); std::queue<int> outQueue; LockHolder lh(args->mutex); LockHolder lhg(args->gate); args->counter++; lhg.unlock(); args->gate.notify(); args->mutex.wait(); lh.unlock(); while(count < NUM_THREADS * NUM_ITEMS) { args->queue.size(); args->queue.getAll(outQueue); while (!outQueue.empty()) { count++; outQueue.pop(); } } sleep(1); assert(args->queue.empty()); assert(outQueue.empty()); return static_cast<void *>(0); } static void *launch_test_thread(void *arg) { struct thread_args *args = static_cast<struct thread_args *>(arg); int i(0); LockHolder lh(args->mutex); LockHolder lhg(args->gate); args->counter++; lhg.unlock(); args->gate.notify(); args->mutex.wait(); lh.unlock(); for (i = 0; i < NUM_ITEMS; ++i) { args->queue.push(i); } return static_cast<void *>(0); } } int main() { pthread_t threads[NUM_THREADS]; pthread_t consumer; int i(0), rc(0), result(-1); struct thread_args args; alarm(60); args.counter = 0; rc = pthread_create(&consumer, NULL, launch_consumer_thread, &args); assert(rc == 0); for (i = 0; i < NUM_THREADS; ++i) { rc = pthread_create(&threads[i], NULL, launch_test_thread, &args); assert(rc == 0); } // Wait for all threads to reach the starting gate int counter; while (true) { LockHolder lh(args.gate); counter = args.counter; if (counter == NUM_THREADS + 1) { break; } args.gate.wait(); } args.mutex.notify(); for (i = 0; i < NUM_THREADS; ++i) { rc = pthread_join(threads[i], reinterpret_cast<void **>(&result)); assert(rc == 0); assert(result == 0); } rc = pthread_join(consumer, reinterpret_cast<void **>(&result)); assert(rc == 0); assert(result == 0); assert(args.queue.empty()); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include "Sofa_test.h" #include<sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/core/ExecParams.h> //Including Simulation #include <sofa/simulation/common/Simulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> // Including constraint, force and mass #include <sofa/component/topology/RegularGridTopology.h> #include <sofa/component/projectiveconstraintset/BilinearMovementConstraint.h> #include <sofa/component/container/MechanicalObject.h> #include <sofa/component/interactionforcefield/MeshSpringForceField.h> #include <sofa/component/forcefield/TetrahedronFEMForceField.h> #include <sofa/core/MechanicalParams.h> #include <sofa/defaulttype/VecTypes.h> #include <plugins/SceneCreator/SceneCreator.h> namespace sofa { using std::cout; using std::cerr; using std::endl; using namespace component; using namespace defaulttype; using namespace modeling; /** Test suite for ProjectToLineConstraint. The test cases are defined in the #Test_Cases member group. */ template <typename _DataTypes> struct Patch_test : public Sofa_test<typename _DataTypes::Real> { typedef _DataTypes DataTypes; typedef typename DataTypes::VecCoord VecCoord; typedef typename DataTypes::VecDeriv VecDeriv; typedef typename DataTypes::Deriv Deriv; typedef projectiveconstraintset::BilinearMovementConstraint<DataTypes> BilinearMovementConstraint; typedef container::MechanicalObject<DataTypes> MechanicalObject; typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField; typedef typename component::forcefield::TetrahedronFEMForceField<DataTypes> TetraForceField; /// Root of the scene graph simulation::Node::SPtr root; /// Simulation simulation::Simulation* simulation; // Structure which contains current node and pointers to the mechanical object and the bilinear constraint PatchTestStruct<DataTypes> patchStruct; // Create the context for the scene void SetUp() { // Init simulation sofa::component::init(); sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); } // Create a scene with a 2D regular grid and a bilinear constraint void createScene2DRegularGrid() { // Initialization Vec<6,Real> box (-0.1,-0.1,0,1.1,1.1,0); helper::vector< Vec<6,Real> > vecBox; vecBox.push_back(box); // Create a scene with a regular grid patchStruct = createRegularGridScene<DataTypes>( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,0), // End point of regular grid 5,5,1, // Resolution of the regular grid vecBox, // BoxRoi to find all mesh points Vec<6,Real>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi Vec<6,Real>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; //Force field for 2D Grid MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField"); meshSpringForceField->setStiffness(10); // Set the corner movements of the bilinear constraint VecDeriv cornerMovementsData = patchStruct.bilinearConstraint->m_cornerMovements.getValue(); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(0.01,-0.01,0)); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(-0.01,0.01,0)); patchStruct.bilinearConstraint->m_cornerMovements.setValue(cornerMovementsData); } // Create a scene with a 3D regular grid and a bilinear constraint void createScene3DRegularGrid() { // Initialization Vec<6,Real> box (-0.1,-0.1,-0.1,1.1,1.1,1.1); helper::vector< Vec<6,Real> > vecBox; vecBox.push_back(box); // Create a scene with a regular grid patchStruct = createRegularGridScene<DataTypes>( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,1), // End point of regular grid 5,5,5, // Resolution of the regular grid vecBox, // BoxRoi to find all mesh points Vec<6,Real>(-0.1,-0.1,-0.1,1.1,1.1,1.1), // inclusive box of pair box roi Vec<6,Real>(0.1,0.1,0.1,0.9,0.9,0.9)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; // Force field for 3D Grid TetraForceField::SPtr tetraFEM = addNew<TetraForceField>(SquareNode,"forceField"); tetraFEM->setMethod("polar"); tetraFEM->setYoungModulus(20); tetraFEM->setPoissonRatio(0.4); // Set the corner movements of the bilinear constraint VecDeriv cornerMovementsData = patchStruct.bilinearConstraint->m_cornerMovements.getValue(); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(0.01,-0.01,-0.01)); cornerMovementsData.push_back(Deriv(0.01,0.01,-0.01)); cornerMovementsData.push_back(Deriv(-0.01,0.01,-0.01)); cornerMovementsData.push_back(Deriv(-0.01,-0.01,0.01)); cornerMovementsData.push_back(Deriv(0.01,-0.01,0.01)); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(-0.01,0.01,0.01)); patchStruct.bilinearConstraint->m_cornerMovements.setValue(cornerMovementsData); } bool test_projectPosition() { // Init simulation sofa::simulation::getSimulation()->init(root.get()); // Animate do {sofa::simulation::getSimulation()->animate(root.get(),0.5);} while(root->getAnimationLoop()->getTime() < 22); // Get the simulated final positions typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions(); // Compute the theoretical final positions VecCoord finalPos; patchStruct.bilinearConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) ); // Compare the theoretical positions and the simulated positions bool succeed=true; for(size_t i=0; i<finalPos.size(); i++ ) { if((finalPos[i]-x[i]).norm()>7e-4) { succeed = false; ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl; } } return succeed; } void TearDown() { if (root!=NULL) sofa::simulation::getSimulation()->unload(root); // cerr<<"tearing down"<<endl; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< Vec3Types, Vec3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(Patch_test, DataTypes); // first test case TYPED_TEST( Patch_test , patchTest2D ) { this->createScene2DRegularGrid(); ASSERT_TRUE( this->test_projectPosition()); } // second test case TYPED_TEST( Patch_test , patchTest3D ) { this->createScene3DRegularGrid(); ASSERT_TRUE( this->test_projectPosition()); } } // namespace sofa <commit_msg>r10542/sofa : FIX: try to fix compilation on Linux.<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include "Sofa_test.h" #include<sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/core/ExecParams.h> //Including Simulation #include <sofa/simulation/common/Simulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> // Including constraint, force and mass #include <sofa/component/topology/RegularGridTopology.h> #include <sofa/component/projectiveconstraintset/BilinearMovementConstraint.h> #include <sofa/component/container/MechanicalObject.h> #include <sofa/component/interactionforcefield/MeshSpringForceField.h> #include <sofa/component/forcefield/TetrahedronFEMForceField.h> #include <sofa/core/MechanicalParams.h> #include <sofa/defaulttype/VecTypes.h> #include <plugins/SceneCreator/SceneCreator.h> namespace sofa { using std::cout; using std::cerr; using std::endl; using namespace component; using namespace defaulttype; using namespace modeling; /** Test suite for ProjectToLineConstraint. The test cases are defined in the #Test_Cases member group. */ template <typename _DataTypes> struct Patch_test : public Sofa_test<typename _DataTypes::Real> { typedef _DataTypes DataTypes; typedef typename DataTypes::VecCoord VecCoord; typedef typename DataTypes::VecDeriv VecDeriv; typedef typename DataTypes::Deriv Deriv; typedef projectiveconstraintset::BilinearMovementConstraint<DataTypes> BilinearMovementConstraint; typedef container::MechanicalObject<DataTypes> MechanicalObject; typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField; typedef typename component::forcefield::TetrahedronFEMForceField<DataTypes> TetraForceField; /// Root of the scene graph simulation::Node::SPtr root; /// Simulation simulation::Simulation* simulation; // Structure which contains current node and pointers to the mechanical object and the bilinear constraint PatchTestStruct<DataTypes> patchStruct; // Create the context for the scene void SetUp() { // Init simulation sofa::component::init(); sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); } // Create a scene with a 2D regular grid and a bilinear constraint void createScene2DRegularGrid() { // Initialization Vec<6,SReal> box (-0.1,-0.1,0,1.1,1.1,0); helper::vector< Vec<6,SReal> > vecBox; vecBox.push_back(box); // Create a scene with a regular grid patchStruct = createRegularGridScene<DataTypes>( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,0), // End point of regular grid 5,5,1, // Resolution of the regular grid vecBox, // BoxRoi to find all mesh points Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi Vec<6,SReal>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; //Force field for 2D Grid typename MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField"); meshSpringForceField->setStiffness(10); // Set the corner movements of the bilinear constraint VecDeriv cornerMovementsData = patchStruct.bilinearConstraint->m_cornerMovements.getValue(); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(0.01,-0.01,0)); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(-0.01,0.01,0)); patchStruct.bilinearConstraint->m_cornerMovements.setValue(cornerMovementsData); } // Create a scene with a 3D regular grid and a bilinear constraint void createScene3DRegularGrid() { // Initialization Vec<6,SReal> box (-0.1,-0.1,-0.1,1.1,1.1,1.1); helper::vector< Vec<6,SReal> > vecBox; vecBox.push_back(box); // Create a scene with a regular grid patchStruct = createRegularGridScene<DataTypes>( root, // attached to the root node Vec<3,SReal>(0,0,0), // Start point of regular grid Vec<3,SReal>(1,1,1), // End point of regular grid 5,5,5, // Resolution of the regular grid vecBox, // BoxRoi to find all mesh points Vec<6,SReal>(-0.1,-0.1,-0.1,1.1,1.1,1.1), // inclusive box of pair box roi Vec<6,SReal>(0.1,0.1,0.1,0.9,0.9,0.9)); // included box of pair box roi simulation::Node::SPtr SquareNode = patchStruct.SquareNode; // Force field for 3D Grid typename TetraForceField::SPtr tetraFEM = addNew<TetraForceField>(SquareNode,"forceField"); tetraFEM->setMethod("polar"); tetraFEM->setYoungModulus(20); tetraFEM->setPoissonRatio(0.4); // Set the corner movements of the bilinear constraint VecDeriv cornerMovementsData = patchStruct.bilinearConstraint->m_cornerMovements.getValue(); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(0.01,-0.01,-0.01)); cornerMovementsData.push_back(Deriv(0.01,0.01,-0.01)); cornerMovementsData.push_back(Deriv(-0.01,0.01,-0.01)); cornerMovementsData.push_back(Deriv(-0.01,-0.01,0.01)); cornerMovementsData.push_back(Deriv(0.01,-0.01,0.01)); cornerMovementsData.push_back(Deriv(0,0,0)); cornerMovementsData.push_back(Deriv(-0.01,0.01,0.01)); patchStruct.bilinearConstraint->m_cornerMovements.setValue(cornerMovementsData); } bool test_projectPosition() { // Init simulation sofa::simulation::getSimulation()->init(root.get()); // Animate do {sofa::simulation::getSimulation()->animate(root.get(),0.5);} while(root->getAnimationLoop()->getTime() < 22); // Get the simulated final positions typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions(); // Compute the theoretical final positions VecCoord finalPos; patchStruct.bilinearConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) ); // Compare the theoretical positions and the simulated positions bool succeed=true; for(size_t i=0; i<finalPos.size(); i++ ) { if((finalPos[i]-x[i]).norm()>7e-4) { succeed = false; ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl; } } return succeed; } void TearDown() { if (root!=NULL) sofa::simulation::getSimulation()->unload(root); // cerr<<"tearing down"<<endl; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< Vec3Types, Vec3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(Patch_test, DataTypes); // first test case TYPED_TEST( Patch_test , patchTest2D ) { this->createScene2DRegularGrid(); ASSERT_TRUE( this->test_projectPosition()); } // second test case TYPED_TEST( Patch_test , patchTest3D ) { this->createScene3DRegularGrid(); ASSERT_TRUE( this->test_projectPosition()); } } // namespace sofa <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // Copyright (c) 2017 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ #include <cstdio> #include <string> #include "PLT/File.h" namespace PLT { //! POSIX implementation of file access class File::Impl { public: Impl(const char* filename_, const char* mode_) : filename(filename_) { fp = fopen(getFilename(), mode_); } Impl(const char* filename_, const char* ext_, const char* mode_) { filename = filename_; filename += '.'; filename += ext_; fp = fopen(getFilename(), mode_); } ~Impl() { if (isOpen()) fclose(fp); } //! Return the filename const char* getFilename() const { return filename.c_str(); } //! Return true if the file is open bool isOpen() const { return fp != nullptr; } //! Get next character from input stream bool getChar(char& ch) { if (!isOpen()) return false; int c = fgetc(fp); if (c == EOF) { fclose(fp); fp = nullptr; return false; } ch = c; if (ch == '\n') ++line_no; return true; } //! Get next line from input stream bool getLine(char* buffer, size_t size) { return fgets(buffer, size, fp) != nullptr; } //! Seek to the given file offser bool seek(size_t offset) { return fseek(fp, offset, SEEK_SET) == 0; } //! Read raw data bool read(void* data, size_t bytes) { return fread(data, bytes, 1, fp) == 1; } //! Formated output void vprint(const char* format, va_list ap) { vfprintf(fp, format, ap); } //! Write raw data bool write(const void* data, size_t bytes) { return fwrite(data, bytes, 1, fp) == 1; } //! Flush output stream void flush() { fflush(fp); } //! Report an error void verror(const char* format, va_list ap) { fprintf(stderr, "ERROR %s:%u - ", getFilename(), line_no); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } private: std::string filename; FILE* fp{nullptr}; unsigned line_no{1}; }; File::File(const char* filename, const char* mode) : pimpl(new Impl(filename, mode)) {} File::File(const char* filename, const char* ext, const char* mode) : pimpl(new Impl(filename, ext, mode)) {} File::~File() { delete pimpl; } bool File::isOpen() const { return pimpl->isOpen(); } const char* File::getFilename() const { return pimpl->getFilename(); } bool File::getChar(char& ch) { return pimpl->getChar(ch); } bool File::seek(size_t offset) { return pimpl->seek(offset); } bool File::read(void* data, size_t bytes) { return pimpl->read(data, bytes); } bool File::getLine(char* buffer, size_t size) { return pimpl->getLine(buffer, size); } void File::print(const char* format, ...) { va_list ap; va_start(ap, format); pimpl->vprint(format, ap); va_end(ap); } bool File::write(const void* data, size_t bytes) { return pimpl->write(data, bytes); } void File::flush() { pimpl->flush(); } bool File::error(const char* format, ...) { va_list ap; va_start(ap, format); pimpl->verror(format, ap); va_end(ap); return false; } } // namespace PLT <commit_msg>Fix missing include on Linux<commit_after>//------------------------------------------------------------------------------ // Copyright (c) 2017 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ #include <cstdio> #include <cstdarg> #include <string> #include "PLT/File.h" namespace PLT { //! POSIX implementation of file access class File::Impl { public: Impl(const char* filename_, const char* mode_) : filename(filename_) { fp = fopen(getFilename(), mode_); } Impl(const char* filename_, const char* ext_, const char* mode_) { filename = filename_; filename += '.'; filename += ext_; fp = fopen(getFilename(), mode_); } ~Impl() { if (isOpen()) fclose(fp); } //! Return the filename const char* getFilename() const { return filename.c_str(); } //! Return true if the file is open bool isOpen() const { return fp != nullptr; } //! Get next character from input stream bool getChar(char& ch) { if (!isOpen()) return false; int c = fgetc(fp); if (c == EOF) { fclose(fp); fp = nullptr; return false; } ch = c; if (ch == '\n') ++line_no; return true; } //! Get next line from input stream bool getLine(char* buffer, size_t size) { return fgets(buffer, size, fp) != nullptr; } //! Seek to the given file offser bool seek(size_t offset) { return fseek(fp, offset, SEEK_SET) == 0; } //! Read raw data bool read(void* data, size_t bytes) { return fread(data, bytes, 1, fp) == 1; } //! Formated output void vprint(const char* format, va_list ap) { vfprintf(fp, format, ap); } //! Write raw data bool write(const void* data, size_t bytes) { return fwrite(data, bytes, 1, fp) == 1; } //! Flush output stream void flush() { fflush(fp); } //! Report an error void verror(const char* format, va_list ap) { fprintf(stderr, "ERROR %s:%u - ", getFilename(), line_no); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } private: std::string filename; FILE* fp{nullptr}; unsigned line_no{1}; }; File::File(const char* filename, const char* mode) : pimpl(new Impl(filename, mode)) {} File::File(const char* filename, const char* ext, const char* mode) : pimpl(new Impl(filename, ext, mode)) {} File::~File() { delete pimpl; } bool File::isOpen() const { return pimpl->isOpen(); } const char* File::getFilename() const { return pimpl->getFilename(); } bool File::getChar(char& ch) { return pimpl->getChar(ch); } bool File::seek(size_t offset) { return pimpl->seek(offset); } bool File::read(void* data, size_t bytes) { return pimpl->read(data, bytes); } bool File::getLine(char* buffer, size_t size) { return pimpl->getLine(buffer, size); } void File::print(const char* format, ...) { va_list ap; va_start(ap, format); pimpl->vprint(format, ap); va_end(ap); } bool File::write(const void* data, size_t bytes) { return pimpl->write(data, bytes); } void File::flush() { pimpl->flush(); } bool File::error(const char* format, ...) { va_list ap; va_start(ap, format); pimpl->verror(format, ap); va_end(ap); return false; } } // namespace PLT <|endoftext|>
<commit_before>// // Copyright (c) 2008-2016 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 <Urho3D/Engine/Application.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/UI/Cursor.h> #include <Urho3D/Engine/DebugHud.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/UI/Sprite.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Core/Timer.h> #include <Urho3D/UI/UI.h> #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/IO/Log.h> Sample::Sample(Context* context) : Application(context), yaw_(0.0f), pitch_(0.0f), touchEnabled_(false), screenJoystickIndex_(M_MAX_UNSIGNED), screenJoystickSettingsIndex_(M_MAX_UNSIGNED), paused_(false), useMouseMode_(MM_ABSOLUTE) { } void Sample::Setup() { // Modify engine startup parameters engineParameters_["WindowTitle"] = GetTypeName(); engineParameters_["LogName"] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("urho3d", "logs") + GetTypeName() + ".log"; engineParameters_["FullScreen"] = false; engineParameters_["Headless"] = false; engineParameters_["Sound"] = false; // Construct a search path to find the resource prefix with two entries: // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location if (!engineParameters_.Contains("ResourcePrefixPaths")) engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources"; } void Sample::Start() { if (GetPlatform() == "Android" || GetPlatform() == "iOS") // On mobile platform, enable touch by adding a screen joystick InitTouchInput(); else if (GetSubsystem<Input>()->GetNumJoysticks() == 0) // On desktop platform, do not detect touch when we already got a joystick SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Sample, HandleTouchBegin)); // Create logo CreateLogo(); // Set custom window Title & Icon SetWindowTitleAndIcon(); // Create console and debug HUD CreateConsoleAndDebugHud(); // Subscribe key down event SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Sample, HandleKeyDown)); // Subscribe key up event SubscribeToEvent(E_KEYUP, URHO3D_HANDLER(Sample, HandleKeyUp)); // Subscribe scene update event SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(Sample, HandleSceneUpdate)); } void Sample::Stop() { engine_->DumpResources(true); } void Sample::InitTouchInput() { touchEnabled_ = true; ResourceCache* cache = GetSubsystem<ResourceCache>(); Input* input = GetSubsystem<Input>(); XMLFile* layout = cache->GetResource<XMLFile>("UI/ScreenJoystick_Samples.xml"); const String& patchString = GetScreenJoystickPatchString(); if (!patchString.Empty()) { // Patch the screen joystick layout further on demand SharedPtr<XMLFile> patchFile(new XMLFile(context_)); if (patchFile->FromString(patchString)) layout->Patch(patchFile); } screenJoystickIndex_ = input->AddScreenJoystick(layout, cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, true); } void Sample::InitMouseMode(MouseMode mode) { useMouseMode_ = mode; Input* input = GetSubsystem<Input>(); if (GetPlatform() != "Web") { if (useMouseMode_ == MM_FREE) input->SetMouseVisible(true); Console* console = GetSubsystem<Console>(); if (useMouseMode_ != MM_ABSOLUTE) { input->SetMouseMode(useMouseMode_); if (console && console->IsVisible()) input->SetMouseMode(MM_ABSOLUTE, true); } } else { input->SetMouseVisible(true); SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(Sample, HandleMouseModeRequest)); SubscribeToEvent(E_MOUSEMODECHANGED, URHO3D_HANDLER(Sample, HandleMouseModeChange)); } } void Sample::SetLogoVisible(bool enable) { if (logoSprite_) logoSprite_->SetVisible(enable); } void Sample::CreateLogo() { // Get logo texture ResourceCache* cache = GetSubsystem<ResourceCache>(); Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/LogoLarge.png"); if (!logoTexture) return; // Create logo sprite and add to the UI layout UI* ui = GetSubsystem<UI>(); logoSprite_ = ui->GetRoot()->CreateChild<Sprite>(); // Set logo sprite texture logoSprite_->SetTexture(logoTexture); int textureWidth = logoTexture->GetWidth(); int textureHeight = logoTexture->GetHeight(); // Set logo sprite scale logoSprite_->SetScale(256.0f / textureWidth); // Set logo sprite size logoSprite_->SetSize(textureWidth, textureHeight); // Set logo sprite hot spot logoSprite_->SetHotSpot(0, textureHeight); // Set logo sprite alignment logoSprite_->SetAlignment(HA_LEFT, VA_BOTTOM); // Make logo not fully opaque to show the scene underneath logoSprite_->SetOpacity(0.75f); // Set a low priority for the logo so that other UI elements can be drawn on top logoSprite_->SetPriority(-100); } void Sample::SetWindowTitleAndIcon() { ResourceCache* cache = GetSubsystem<ResourceCache>(); Graphics* graphics = GetSubsystem<Graphics>(); Image* icon = cache->GetResource<Image>("Textures/UrhoIcon.png"); graphics->SetWindowIcon(icon); graphics->SetWindowTitle("Urho3D Sample"); } void Sample::CreateConsoleAndDebugHud() { // Get default style ResourceCache* cache = GetSubsystem<ResourceCache>(); XMLFile* xmlFile = cache->GetResource<XMLFile>("UI/DefaultStyle.xml"); // Create console Console* console = engine_->CreateConsole(); console->SetDefaultStyle(xmlFile); console->GetBackground()->SetOpacity(0.8f); // Create debug HUD. DebugHud* debugHud = engine_->CreateDebugHud(); debugHud->SetDefaultStyle(xmlFile); } void Sample::HandleKeyUp(StringHash eventType, VariantMap& eventData) { using namespace KeyUp; int key = eventData[P_KEY].GetInt(); // Close console (if open) or exit when ESC is pressed if (key == KEY_ESC) { Console* console = GetSubsystem<Console>(); if (console->IsVisible()) console->SetVisible(false); else { if (GetPlatform() == "Web") { GetSubsystem<Input>()->SetMouseVisible(true); if (useMouseMode_ != MM_ABSOLUTE) GetSubsystem<Input>()->SetMouseMode(MM_FREE); } else engine_->Exit(); } } } void Sample::HandleKeyDown(StringHash eventType, VariantMap& eventData) { using namespace KeyDown; int key = eventData[P_KEY].GetInt(); // Toggle console with F1 or Z if (key == KEY_F1 || key == 'Z') GetSubsystem<Console>()->Toggle(); // Toggle debug HUD with F2 else if (key == KEY_F2) { DebugHud* debugHud = GetSubsystem<DebugHud>(); if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL_MEMORY) debugHud->SetMode(DEBUGHUD_SHOW_ALL); else debugHud->SetMode(DEBUGHUD_SHOW_NONE); } else if (key == KEY_F3) { DebugHud* debugHud = GetSubsystem<DebugHud>(); if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL) debugHud->SetMode(DEBUGHUD_SHOW_ALL_MEMORY); else debugHud->SetMode(DEBUGHUD_SHOW_NONE); } // Common rendering quality controls, only when UI has no focused element else if (!GetSubsystem<UI>()->GetFocusElement()) { Renderer* renderer = GetSubsystem<Renderer>(); // Preferences / Pause if (key == KEY_SELECT && touchEnabled_) { paused_ = !paused_; Input* input = GetSubsystem<Input>(); if (screenJoystickSettingsIndex_ == M_MAX_UNSIGNED) { // Lazy initialization ResourceCache* cache = GetSubsystem<ResourceCache>(); screenJoystickSettingsIndex_ = input->AddScreenJoystick(cache->GetResource<XMLFile>("UI/ScreenJoystickSettings_Samples.xml"), cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); } else input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, paused_); } // Texture quality else if (key == '1') { int quality = renderer->GetTextureQuality(); ++quality; if (quality > QUALITY_HIGH) quality = QUALITY_LOW; renderer->SetTextureQuality(quality); } // Material quality else if (key == '2') { int quality = renderer->GetMaterialQuality(); ++quality; if (quality > QUALITY_HIGH) quality = QUALITY_LOW; renderer->SetMaterialQuality(quality); } // Specular lighting else if (key == '3') renderer->SetSpecularLighting(!renderer->GetSpecularLighting()); // Shadow rendering else if (key == '4') renderer->SetDrawShadows(!renderer->GetDrawShadows()); // Shadow map resolution else if (key == '5') { int shadowMapSize = renderer->GetShadowMapSize(); shadowMapSize *= 2; if (shadowMapSize > 2048) shadowMapSize = 512; renderer->SetShadowMapSize(shadowMapSize); } // Shadow depth and filtering quality else if (key == '6') { ShadowQuality quality = renderer->GetShadowQuality(); quality = (ShadowQuality)(quality + 1); if (quality > SHADOWQUALITY_BLUR_VSM) quality = SHADOWQUALITY_SIMPLE_16BIT; renderer->SetShadowQuality(quality); } // Occlusion culling else if (key == '7') { bool occlusion = renderer->GetMaxOccluderTriangles() > 0; occlusion = !occlusion; renderer->SetMaxOccluderTriangles(occlusion ? 5000 : 0); } // Instancing else if (key == '8') renderer->SetDynamicInstancing(!renderer->GetDynamicInstancing()); // Take screenshot else if (key == '9') { Graphics* graphics = GetSubsystem<Graphics>(); Image screenshot(context_); graphics->TakeScreenShot(screenshot); // Here we save in the Data folder with date and time appended screenshot.SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" + Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png"); } } } void Sample::HandleSceneUpdate(StringHash eventType, VariantMap& eventData) { // Move the camera by touch, if the camera node is initialized by descendant sample class if (touchEnabled_ && cameraNode_) { Input* input = GetSubsystem<Input>(); for (unsigned i = 0; i < input->GetNumTouches(); ++i) { TouchState* state = input->GetTouch(i); if (!state->touchedElement_) // Touch on empty space { if (state->delta_.x_ ||state->delta_.y_) { Camera* camera = cameraNode_->GetComponent<Camera>(); if (!camera) return; Graphics* graphics = GetSubsystem<Graphics>(); yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_; pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_; // Construct new orientation for the camera scene node from yaw and pitch; roll is fixed to zero cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f)); } else { // Move the cursor to the touch position Cursor* cursor = GetSubsystem<UI>()->GetCursor(); if (cursor && cursor->IsVisible()) cursor->SetPosition(state->position_); } } } } } void Sample::HandleTouchBegin(StringHash eventType, VariantMap& eventData) { // On some platforms like Windows the presence of touch input can only be detected dynamically InitTouchInput(); UnsubscribeFromEvent("TouchBegin"); } // If the user clicks the canvas, attempt to switch to relative mouse mode on web platform void Sample::HandleMouseModeRequest(StringHash eventType, VariantMap& eventData) { Console* console = GetSubsystem<Console>(); if (console && console->IsVisible()) return; Input* input = GetSubsystem<Input>(); if (useMouseMode_ == MM_ABSOLUTE) input->SetMouseVisible(false); else if (useMouseMode_ == MM_FREE) input->SetMouseVisible(true); input->SetMouseMode(useMouseMode_); } void Sample::HandleMouseModeChange(StringHash eventType, VariantMap& eventData) { Input* input = GetSubsystem<Input>(); bool mouseLocked = eventData[MouseModeChanged::P_MOUSELOCKED].GetBool(); input->SetMouseVisible(!mouseLocked); } <commit_msg>Remove "z" shortcut for console (consistent with scripting samples).<commit_after>// // Copyright (c) 2008-2016 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 <Urho3D/Engine/Application.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/UI/Cursor.h> #include <Urho3D/Engine/DebugHud.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/UI/Sprite.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Core/Timer.h> #include <Urho3D/UI/UI.h> #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/IO/Log.h> Sample::Sample(Context* context) : Application(context), yaw_(0.0f), pitch_(0.0f), touchEnabled_(false), screenJoystickIndex_(M_MAX_UNSIGNED), screenJoystickSettingsIndex_(M_MAX_UNSIGNED), paused_(false), useMouseMode_(MM_ABSOLUTE) { } void Sample::Setup() { // Modify engine startup parameters engineParameters_["WindowTitle"] = GetTypeName(); engineParameters_["LogName"] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("urho3d", "logs") + GetTypeName() + ".log"; engineParameters_["FullScreen"] = false; engineParameters_["Headless"] = false; engineParameters_["Sound"] = false; // Construct a search path to find the resource prefix with two entries: // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location if (!engineParameters_.Contains("ResourcePrefixPaths")) engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources"; } void Sample::Start() { if (GetPlatform() == "Android" || GetPlatform() == "iOS") // On mobile platform, enable touch by adding a screen joystick InitTouchInput(); else if (GetSubsystem<Input>()->GetNumJoysticks() == 0) // On desktop platform, do not detect touch when we already got a joystick SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Sample, HandleTouchBegin)); // Create logo CreateLogo(); // Set custom window Title & Icon SetWindowTitleAndIcon(); // Create console and debug HUD CreateConsoleAndDebugHud(); // Subscribe key down event SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Sample, HandleKeyDown)); // Subscribe key up event SubscribeToEvent(E_KEYUP, URHO3D_HANDLER(Sample, HandleKeyUp)); // Subscribe scene update event SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(Sample, HandleSceneUpdate)); } void Sample::Stop() { engine_->DumpResources(true); } void Sample::InitTouchInput() { touchEnabled_ = true; ResourceCache* cache = GetSubsystem<ResourceCache>(); Input* input = GetSubsystem<Input>(); XMLFile* layout = cache->GetResource<XMLFile>("UI/ScreenJoystick_Samples.xml"); const String& patchString = GetScreenJoystickPatchString(); if (!patchString.Empty()) { // Patch the screen joystick layout further on demand SharedPtr<XMLFile> patchFile(new XMLFile(context_)); if (patchFile->FromString(patchString)) layout->Patch(patchFile); } screenJoystickIndex_ = input->AddScreenJoystick(layout, cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, true); } void Sample::InitMouseMode(MouseMode mode) { useMouseMode_ = mode; Input* input = GetSubsystem<Input>(); if (GetPlatform() != "Web") { if (useMouseMode_ == MM_FREE) input->SetMouseVisible(true); Console* console = GetSubsystem<Console>(); if (useMouseMode_ != MM_ABSOLUTE) { input->SetMouseMode(useMouseMode_); if (console && console->IsVisible()) input->SetMouseMode(MM_ABSOLUTE, true); } } else { input->SetMouseVisible(true); SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(Sample, HandleMouseModeRequest)); SubscribeToEvent(E_MOUSEMODECHANGED, URHO3D_HANDLER(Sample, HandleMouseModeChange)); } } void Sample::SetLogoVisible(bool enable) { if (logoSprite_) logoSprite_->SetVisible(enable); } void Sample::CreateLogo() { // Get logo texture ResourceCache* cache = GetSubsystem<ResourceCache>(); Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/LogoLarge.png"); if (!logoTexture) return; // Create logo sprite and add to the UI layout UI* ui = GetSubsystem<UI>(); logoSprite_ = ui->GetRoot()->CreateChild<Sprite>(); // Set logo sprite texture logoSprite_->SetTexture(logoTexture); int textureWidth = logoTexture->GetWidth(); int textureHeight = logoTexture->GetHeight(); // Set logo sprite scale logoSprite_->SetScale(256.0f / textureWidth); // Set logo sprite size logoSprite_->SetSize(textureWidth, textureHeight); // Set logo sprite hot spot logoSprite_->SetHotSpot(0, textureHeight); // Set logo sprite alignment logoSprite_->SetAlignment(HA_LEFT, VA_BOTTOM); // Make logo not fully opaque to show the scene underneath logoSprite_->SetOpacity(0.75f); // Set a low priority for the logo so that other UI elements can be drawn on top logoSprite_->SetPriority(-100); } void Sample::SetWindowTitleAndIcon() { ResourceCache* cache = GetSubsystem<ResourceCache>(); Graphics* graphics = GetSubsystem<Graphics>(); Image* icon = cache->GetResource<Image>("Textures/UrhoIcon.png"); graphics->SetWindowIcon(icon); graphics->SetWindowTitle("Urho3D Sample"); } void Sample::CreateConsoleAndDebugHud() { // Get default style ResourceCache* cache = GetSubsystem<ResourceCache>(); XMLFile* xmlFile = cache->GetResource<XMLFile>("UI/DefaultStyle.xml"); // Create console Console* console = engine_->CreateConsole(); console->SetDefaultStyle(xmlFile); console->GetBackground()->SetOpacity(0.8f); // Create debug HUD. DebugHud* debugHud = engine_->CreateDebugHud(); debugHud->SetDefaultStyle(xmlFile); } void Sample::HandleKeyUp(StringHash eventType, VariantMap& eventData) { using namespace KeyUp; int key = eventData[P_KEY].GetInt(); // Close console (if open) or exit when ESC is pressed if (key == KEY_ESC) { Console* console = GetSubsystem<Console>(); if (console->IsVisible()) console->SetVisible(false); else { if (GetPlatform() == "Web") { GetSubsystem<Input>()->SetMouseVisible(true); if (useMouseMode_ != MM_ABSOLUTE) GetSubsystem<Input>()->SetMouseMode(MM_FREE); } else engine_->Exit(); } } } void Sample::HandleKeyDown(StringHash eventType, VariantMap& eventData) { using namespace KeyDown; int key = eventData[P_KEY].GetInt(); // Toggle console with F1 if (key == KEY_F1) GetSubsystem<Console>()->Toggle(); // Toggle debug HUD with F2 else if (key == KEY_F2) { DebugHud* debugHud = GetSubsystem<DebugHud>(); if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL_MEMORY) debugHud->SetMode(DEBUGHUD_SHOW_ALL); else debugHud->SetMode(DEBUGHUD_SHOW_NONE); } else if (key == KEY_F3) { DebugHud* debugHud = GetSubsystem<DebugHud>(); if (debugHud->GetMode() == 0 || debugHud->GetMode() == DEBUGHUD_SHOW_ALL) debugHud->SetMode(DEBUGHUD_SHOW_ALL_MEMORY); else debugHud->SetMode(DEBUGHUD_SHOW_NONE); } // Common rendering quality controls, only when UI has no focused element else if (!GetSubsystem<UI>()->GetFocusElement()) { Renderer* renderer = GetSubsystem<Renderer>(); // Preferences / Pause if (key == KEY_SELECT && touchEnabled_) { paused_ = !paused_; Input* input = GetSubsystem<Input>(); if (screenJoystickSettingsIndex_ == M_MAX_UNSIGNED) { // Lazy initialization ResourceCache* cache = GetSubsystem<ResourceCache>(); screenJoystickSettingsIndex_ = input->AddScreenJoystick(cache->GetResource<XMLFile>("UI/ScreenJoystickSettings_Samples.xml"), cache->GetResource<XMLFile>("UI/DefaultStyle.xml")); } else input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, paused_); } // Texture quality else if (key == '1') { int quality = renderer->GetTextureQuality(); ++quality; if (quality > QUALITY_HIGH) quality = QUALITY_LOW; renderer->SetTextureQuality(quality); } // Material quality else if (key == '2') { int quality = renderer->GetMaterialQuality(); ++quality; if (quality > QUALITY_HIGH) quality = QUALITY_LOW; renderer->SetMaterialQuality(quality); } // Specular lighting else if (key == '3') renderer->SetSpecularLighting(!renderer->GetSpecularLighting()); // Shadow rendering else if (key == '4') renderer->SetDrawShadows(!renderer->GetDrawShadows()); // Shadow map resolution else if (key == '5') { int shadowMapSize = renderer->GetShadowMapSize(); shadowMapSize *= 2; if (shadowMapSize > 2048) shadowMapSize = 512; renderer->SetShadowMapSize(shadowMapSize); } // Shadow depth and filtering quality else if (key == '6') { ShadowQuality quality = renderer->GetShadowQuality(); quality = (ShadowQuality)(quality + 1); if (quality > SHADOWQUALITY_BLUR_VSM) quality = SHADOWQUALITY_SIMPLE_16BIT; renderer->SetShadowQuality(quality); } // Occlusion culling else if (key == '7') { bool occlusion = renderer->GetMaxOccluderTriangles() > 0; occlusion = !occlusion; renderer->SetMaxOccluderTriangles(occlusion ? 5000 : 0); } // Instancing else if (key == '8') renderer->SetDynamicInstancing(!renderer->GetDynamicInstancing()); // Take screenshot else if (key == '9') { Graphics* graphics = GetSubsystem<Graphics>(); Image screenshot(context_); graphics->TakeScreenShot(screenshot); // Here we save in the Data folder with date and time appended screenshot.SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" + Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png"); } } } void Sample::HandleSceneUpdate(StringHash eventType, VariantMap& eventData) { // Move the camera by touch, if the camera node is initialized by descendant sample class if (touchEnabled_ && cameraNode_) { Input* input = GetSubsystem<Input>(); for (unsigned i = 0; i < input->GetNumTouches(); ++i) { TouchState* state = input->GetTouch(i); if (!state->touchedElement_) // Touch on empty space { if (state->delta_.x_ ||state->delta_.y_) { Camera* camera = cameraNode_->GetComponent<Camera>(); if (!camera) return; Graphics* graphics = GetSubsystem<Graphics>(); yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_; pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_; // Construct new orientation for the camera scene node from yaw and pitch; roll is fixed to zero cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f)); } else { // Move the cursor to the touch position Cursor* cursor = GetSubsystem<UI>()->GetCursor(); if (cursor && cursor->IsVisible()) cursor->SetPosition(state->position_); } } } } } void Sample::HandleTouchBegin(StringHash eventType, VariantMap& eventData) { // On some platforms like Windows the presence of touch input can only be detected dynamically InitTouchInput(); UnsubscribeFromEvent("TouchBegin"); } // If the user clicks the canvas, attempt to switch to relative mouse mode on web platform void Sample::HandleMouseModeRequest(StringHash eventType, VariantMap& eventData) { Console* console = GetSubsystem<Console>(); if (console && console->IsVisible()) return; Input* input = GetSubsystem<Input>(); if (useMouseMode_ == MM_ABSOLUTE) input->SetMouseVisible(false); else if (useMouseMode_ == MM_FREE) input->SetMouseVisible(true); input->SetMouseMode(useMouseMode_); } void Sample::HandleMouseModeChange(StringHash eventType, VariantMap& eventData) { Input* input = GetSubsystem<Input>(); bool mouseLocked = eventData[MouseModeChanged::P_MOUSELOCKED].GetBool(); input->SetMouseVisible(!mouseLocked); } <|endoftext|>
<commit_before>// File: main_louvain.cpp // -- community detection, sample main file //----------------------------------------------------------------------------- // Community detection // Based on the article "Fast unfolding of community hierarchies in large networks" // Copyright (C) 2008 V. Blondel, J.-L. Guillaume, R. Lambiotte, E. Lefebvre // // And based on the article // Copyright (C) 2013 R. Campigotto, P. Conde Céspedes, J.-L. Guillaume // // This file is part of Louvain algorithm. // // Louvain algorithm is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Louvain algorithm 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 Louvain algorithm. If not, see <http://www.gnu.org/licenses/>. //----------------------------------------------------------------------------- // Author : E. Lefebvre, adapted by J.-L. Guillaume and R. Campigotto // Email : [email protected] // Location : Paris, France // Time : July 2013 //----------------------------------------------------------------------------- // see README.txt for more details #include "graph_binary.h" #include "louvain.h" #include <unistd.h> #include "modularity.h" #include "zahn.h" #include "owzad.h" #include "goldberg.h" #include "condora.h" #include "devind.h" #include "devuni.h" #include "dp.h" #include "shimalik.h" #include "balmod.h" using namespace std; char *filename = NULL; char *filename_w = NULL; char *filename_part = NULL; int type = UNWEIGHTED; int nb_pass = 0; long double precision = 0.000001L; int display_level = -2; unsigned short id_qual = 0; long double alpha = 0.5L; int kmin = 1; long double sum_se = 0.0L; long double sum_sq = 0.0L; long double max_w = 1.0L; Quality *q; bool verbose = false; void usage(char *prog_name, const char *more) { cerr << more; cerr << "usage: " << prog_name << " input_file [-q id_qual] [-c alpha] [-k min] [-w weight_file] [-p part_file] [-e epsilon] [-l display_level] [-v] [-h]" << endl << endl; cerr << "input_file: file containing the graph to decompose in communities" << endl; cerr << "-q id\tthe quality function used to compute partition of the graph (modularity is chosen by default):" << endl << endl; cerr << "\tid = 0\t -> the classical Newman-Girvan criterion (also called \"Modularity\")" << endl; cerr << "\tid = 1\t -> the Zahn-Condorcet criterion" << endl; cerr << "\tid = 2\t -> the Owsinski-Zadrozny criterion (you should specify the value of the parameter with option -c)" << endl; cerr << "\tid = 3\t -> the Goldberg Density criterion" << endl; cerr << "\tid = 4\t -> the A-weighted Condorcet criterion" << endl; cerr << "\tid = 5\t -> the Deviation to Indetermination criterion" << endl; cerr << "\tid = 6\t -> the Deviation to Uniformity criterion" << endl; cerr << "\tid = 7\t -> the Profile Difference criterion" << endl; cerr << "\tid = 8\t -> the Shi-Malik criterion (you should specify the value of kappa_min with option -k)" << endl; cerr << "\tid = 9\t -> the Balanced Modularity criterion" << endl; cerr << endl; cerr << "-c al\tthe parameter for the Owsinski-Zadrozny quality function (between 0.0 and 1.0: 0.5 is chosen by default)" << endl; cerr << "-k min\tthe kappa_min value (for Shi-Malik quality function) (it must be > 0: 1 is chosen by default)" << endl; cerr << endl; cerr << "-w file\tread the graph as a weighted one (weights are set to 1 otherwise)" << endl; cerr << "-p file\tstart the computation with a given partition instead of the trivial partition" << endl; cerr << "\tfile must contain lines \"node community\"" << endl; cerr << "-e eps\ta given pass stops when the quality is increased by less than epsilon" << endl; cerr << "-l k\tdisplays the graph of level k rather than the hierachical structure" << endl; cerr << "\tif k=-1 then displays the hierarchical structure rather than the graph at a given level" << endl; cerr << "-v\tverbose mode: gives computation time, information about the hierarchy and quality" << endl; cerr << "-h\tshow this usage message" << endl; exit(0); } void parse_args(int argc, char **argv) { if (argc<2) usage(argv[0], "Bad arguments number\n"); for (int i = 1; i < argc; i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { case 'w': type = WEIGHTED; filename_w = argv[i+1]; i++; break; case 'q': id_qual = (unsigned short)atoi(argv[i+1]); i++; break; case 'c': alpha = atof(argv[i+1]); i++; break; case 'k': kmin = atoi(argv[i+1]); i++; break; case 'p': filename_part = argv[i+1]; i++; break; case 'e': precision = atof(argv[i+1]); i++; break; case 'l': display_level = atoi(argv[i+1]); i++; break; case 'v': verbose = true; break; case 'h': usage(argv[0], ""); break; default: usage(argv[0], "Unknown option\n"); } } else { if (filename==NULL) filename = argv[i]; else usage(argv[0], "More than one filename\n"); } } if (filename == NULL) usage(argv[0], "No input file has been provided\n"); } void display_time(const char *str) { time_t rawtime; time ( &rawtime ); cerr << str << ": " << ctime (&rawtime); } void init_quality(Graph *g, unsigned short nbc) { if (nbc > 0) delete q; switch (id_qual) { case 0: q = new Modularity(*g); break; case 1: if (nbc == 0) max_w = g->max_weight(); q = new Zahn(*g, max_w); break; case 2: if (nbc == 0) max_w = g->max_weight(); if (alpha <= 0. || alpha >= 1.0) alpha = 0.5; q = new OwZad(*g, alpha, max_w); break; case 3: if (nbc == 0) max_w = g->max_weight(); q = new Goldberg(*g, max_w); break; case 4: if (nbc == 0) { g->add_selfloops(); sum_se = CondorA::graph_weighting(g); } q = new CondorA(*g, sum_se); break; case 5: q = new DevInd(*g); break; case 6: q = new DevUni(*g); break; case 7: if (nbc == 0) { max_w = g->max_weight(); sum_sq = DP::graph_weighting(g); } q = new DP(*g, sum_sq, max_w); break; case 8: if (kmin < 1) kmin = 1; q = new ShiMalik(*g, kmin); break; case 9: if (nbc == 0) max_w = g->max_weight(); q = new BalMod(*g, max_w); break; default: q = new Modularity(*g); break; } } int main(int argc, char **argv) { srand(time(NULL)+getpid()); parse_args(argc, argv); time_t time_begin, time_end; time(&time_begin); unsigned short nb_calls = 0; // if (verbose) // display_time("Begin"); Graph g(filename, filename_w, type); init_quality(&g, nb_calls); nb_calls++; // if (verbose) // cerr << endl << "Computation of communities with the " << q->name << " quality function" << endl << endl; Louvain c(-1, precision, q); if (filename_part!=NULL) c.init_partition(filename_part); bool improvement = true; long double quality = (c.qual)->quality(); long double new_qual; int level = 0; // cerr << "Initial number of communities: " << (c.qual)->g.nb_nodes; // cerr << "Initial modularity: " << (c.qual)->quality() << endl; do { if (verbose) { cerr << "level " << level << ":\n"; display_time(" start computation"); cerr << " network size: "; cerr << (c.qual)->g.nb_nodes << " nodes, " << (c.qual)->g.nb_links << " links, " << (c.qual)->g.total_weight << " weight" << endl; } improvement = c.one_level(); new_qual = (c.qual)->quality(); if (++level==display_level) (c.qual)->g.display(); if (display_level==-1) c.display_partition(); g = c.partition2graph_binary(); init_quality(&g, nb_calls); nb_calls++; c = Louvain(-1, precision, q); if (verbose) cerr << " quality increased from " << quality << " to " << new_qual << endl; //quality = (c.qual)->quality(); quality = new_qual; // if (verbose) // display_time(" end computation"); if (filename_part!=NULL && level==1) // do at least one more computation if partition is provided improvement=true; } while(improvement); time(&time_end); // if (verbose) { // // display_time("End"); // // } // c.display_partition(); // cerr << "Number of communities after mod max: " << (c.qual)->g.nb_nodes << endl; // cerr << "Final modularity: " << new_qual << endl; delete q; } <commit_msg>Update main_louvain.cpp<commit_after>// File: main_louvain.cpp // -- community detection, sample main file //----------------------------------------------------------------------------- // Community detection // Based on the article "Fast unfolding of community hierarchies in large networks" // Copyright (C) 2008 V. Blondel, J.-L. Guillaume, R. Lambiotte, E. Lefebvre // // And based on the article // Copyright (C) 2013 R. Campigotto, P. Conde Céspedes, J.-L. Guillaume // // This file is part of Louvain algorithm. // // Louvain algorithm is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Louvain algorithm 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 Louvain algorithm. If not, see <http://www.gnu.org/licenses/>. //----------------------------------------------------------------------------- // Author : E. Lefebvre, adapted by J.-L. Guillaume and R. Campigotto // Email : [email protected] // Location : Paris, France // Time : July 2013 //----------------------------------------------------------------------------- // see README.txt for more details #include "graph_binary.h" #include "louvain.h" #include <unistd.h> #include "modularity.h" #include "zahn.h" #include "owzad.h" #include "goldberg.h" #include "condora.h" #include "devind.h" #include "devuni.h" #include "dp.h" #include "shimalik.h" #include "balmod.h" using namespace std; char *filename = NULL; char *filename_w = NULL; char *filename_part = NULL; int type = UNWEIGHTED; int nb_pass = 0; long double precision = 0.000001L; int display_level = -2; unsigned short id_qual = 0; long double alpha = 0.5L; int kmin = 1; long double sum_se = 0.0L; long double sum_sq = 0.0L; long double max_w = 1.0L; Quality *q; bool verbose = false; void usage(char *prog_name, const char *more) { cerr << more; cerr << "usage: " << prog_name << " input_file [-q id_qual] [-c alpha] [-k min] [-w weight_file] [-p part_file] [-e epsilon] [-l display_level] [-v] [-h]" << endl << endl; cerr << "input_file: file containing the graph to decompose in communities" << endl; cerr << "-q id\tthe quality function used to compute partition of the graph (modularity is chosen by default):" << endl << endl; cerr << "\tid = 0\t -> the classical Newman-Girvan criterion (also called \"Modularity\")" << endl; cerr << "\tid = 1\t -> the Zahn-Condorcet criterion" << endl; cerr << "\tid = 2\t -> the Owsinski-Zadrozny criterion (you should specify the value of the parameter with option -c)" << endl; cerr << "\tid = 3\t -> the Goldberg Density criterion" << endl; cerr << "\tid = 4\t -> the A-weighted Condorcet criterion" << endl; cerr << "\tid = 5\t -> the Deviation to Indetermination criterion" << endl; cerr << "\tid = 6\t -> the Deviation to Uniformity criterion" << endl; cerr << "\tid = 7\t -> the Profile Difference criterion" << endl; cerr << "\tid = 8\t -> the Shi-Malik criterion (you should specify the value of kappa_min with option -k)" << endl; cerr << "\tid = 9\t -> the Balanced Modularity criterion" << endl; cerr << endl; cerr << "-c al\tthe parameter for the Owsinski-Zadrozny quality function (between 0.0 and 1.0: 0.5 is chosen by default)" << endl; cerr << "-k min\tthe kappa_min value (for Shi-Malik quality function) (it must be > 0: 1 is chosen by default)" << endl; cerr << endl; cerr << "-w file\tread the graph as a weighted one (weights are set to 1 otherwise)" << endl; cerr << "-p file\tstart the computation with a given partition instead of the trivial partition" << endl; cerr << "\tfile must contain lines \"node community\"" << endl; cerr << "-e eps\ta given pass stops when the quality is increased by less than epsilon" << endl; cerr << "-l k\tdisplays the graph of level k rather than the hierachical structure" << endl; cerr << "\tif k=-1 then displays the hierarchical structure rather than the graph at a given level" << endl; cerr << "-v\tverbose mode: gives computation time, information about the hierarchy and quality" << endl; cerr << "-h\tshow this usage message" << endl; exit(0); } void parse_args(int argc, char **argv) { if (argc<2) usage(argv[0], "Bad arguments number\n"); for (int i = 1; i < argc; i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { case 'w': type = WEIGHTED; filename_w = argv[i+1]; i++; break; case 'q': id_qual = (unsigned short)atoi(argv[i+1]); i++; break; case 'c': alpha = atof(argv[i+1]); i++; break; case 'k': kmin = atoi(argv[i+1]); i++; break; case 'p': filename_part = argv[i+1]; i++; break; case 'e': precision = atof(argv[i+1]); i++; break; case 'l': display_level = atoi(argv[i+1]); i++; break; case 'v': verbose = true; break; case 'h': usage(argv[0], ""); break; default: usage(argv[0], "Unknown option\n"); } } else { if (filename==NULL) filename = argv[i]; else usage(argv[0], "More than one filename\n"); } } if (filename == NULL) usage(argv[0], "No input file has been provided\n"); } void display_time(const char *str) { time_t rawtime; time ( &rawtime ); cerr << str << ": " << ctime (&rawtime); } void init_quality(Graph *g, unsigned short nbc) { if (nbc > 0) delete q; switch (id_qual) { case 0: q = new Modularity(*g); break; case 1: if (nbc == 0) max_w = g->max_weight(); q = new Zahn(*g, max_w); break; case 2: if (nbc == 0) max_w = g->max_weight(); if (alpha <= 0. || alpha >= 1.0) alpha = 0.5; q = new OwZad(*g, alpha, max_w); break; case 3: if (nbc == 0) max_w = g->max_weight(); q = new Goldberg(*g, max_w); break; case 4: if (nbc == 0) { g->add_selfloops(); sum_se = CondorA::graph_weighting(g); } q = new CondorA(*g, sum_se); break; case 5: q = new DevInd(*g); break; case 6: q = new DevUni(*g); break; case 7: if (nbc == 0) { max_w = g->max_weight(); sum_sq = DP::graph_weighting(g); } q = new DP(*g, sum_sq, max_w); break; case 8: if (kmin < 1) kmin = 1; q = new ShiMalik(*g, kmin); break; case 9: if (nbc == 0) max_w = g->max_weight(); q = new BalMod(*g, max_w); break; default: q = new Modularity(*g); break; } } int main(int argc, char **argv) { srand(time(NULL)+getpid()); parse_args(argc, argv); time_t time_begin, time_end; time(&time_begin); unsigned short nb_calls = 0; // if (verbose) // display_time("Begin"); Graph g(filename, filename_w, type); init_quality(&g, nb_calls); nb_calls++; // if (verbose) // cerr << endl << "Computation of communities with the " << q->name << " quality function" << endl << endl; Louvain c(-1, precision, q); if (filename_part!=NULL) c.init_partition(filename_part); bool improvement = true; long double quality = (c.qual)->quality(); long double new_qual; int level = 0; // cerr << "Initial number of communities: " << (c.qual)->g.nb_nodes; // cerr << "Initial modularity: " << (c.qual)->quality() << endl; do { if (verbose) { cerr << "level " << level << ":\n"; display_time(" start computation"); cerr << " network size: "; cerr << (c.qual)->g.nb_nodes << " nodes, " << (c.qual)->g.nb_links << " links, " << (c.qual)->g.total_weight << " weight" << endl; } improvement = c.one_level(); new_qual = (c.qual)->quality(); if (++level==display_level) (c.qual)->g.display(); if (display_level==-1) c.display_partition(); g = c.partition2graph_binary(); init_quality(&g, nb_calls); nb_calls++; c = Louvain(-1, precision, q); if (verbose) cerr << " quality increased from " << quality << " to " << new_qual << endl; //quality = (c.qual)->quality(); quality = new_qual; // if (verbose) // display_time(" end computation"); if (filename_part!=NULL && level==1) // do at least one more computation if partition is provided improvement=true; } while(improvement); time(&time_end); // if (verbose) { // // display_time("End"); // // } // c.display_partition(); cerr << "Number of communities after mod max: " << (c.qual)->g.nb_nodes << endl; cerr << "Final modularity: " << new_qual << endl; delete q; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <sofa/helper/ArgumentParser.h> #include <sofa/helper/UnitTest.h> #include <sofa/helper/vector_algebra.h> #include <sofa/helper/vector.h> #include <sofa/helper/BackTrace.h> #include <sofa/helper/system/PluginManager.h> //#include <sofa/simulation/tree/TreeSimulation.h> #ifdef SOFA_HAVE_DAG #include <sofa/simulation/graph/DAGSimulation.h> #endif #ifdef SOFA_HAVE_BGL #include <sofa/simulation/bgl/BglSimulation.h> #endif #include <sofa/simulation/common/Node.h> #include <sofa/simulation/common/xml/initXml.h> #include <sofa/gui/GUIManager.h> #include <sofa/gui/Main.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #include <sofa/component/topology/MeshTopology.h> #include <sofa/component/topology/EdgeSetTopologyContainer.h> #include <sofa/component/topology/RegularGridTopology.h> #include <sofa/component/collision/SphereModel.h> #include <sofa/component/topology/CubeTopology.h> #include <sofa/component/visualmodel/VisualStyle.h> #include <sofa/component/odesolver/EulerImplicitSolver.h> #include <sofa/component/linearsolver/CGLinearSolver.h> //Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT. #include <sofa/component/typedef/Sofa_typedef.h> using namespace sofa; using namespace sofa::helper; using helper::vector; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using namespace sofa::component::container; using namespace sofa::component::topology; using namespace sofa::component::collision; using namespace sofa::component::visualmodel; using namespace sofa::component::mapping; using namespace sofa::component::forcefield; typedef SReal Scalar; typedef Vec<3,SReal> Vec3; typedef Vec<1,SReal> Vec1; typedef component::odesolver::EulerImplicitSolver EulerImplicitSolver; typedef component::linearsolver::CGLinearSolver<component::linearsolver::GraphScatteredMatrix, component::linearsolver::GraphScatteredVector> CGLinearSolver; bool startAnim = true; bool verbose = false; SReal complianceValue = 0.1; SReal dampingRatio = 0.1; Vec3 gravity(0,-1,0); SReal dt = 0.01; /// helper for more compact component creation template<class Component> typename Component::SPtr addNew( Node::SPtr parentNode, std::string name="" ) { typename Component::SPtr component = New<Component>(); parentNode->addObject(component); component->setName(parentNode->getName()+"_"+name); return component; } /// Create an assembly of a siff hexahedral grid with other objects simulation::Node::SPtr createGridScene(Vec3 startPoint, Vec3 endPoint, unsigned numX, unsigned numY, unsigned numZ, double totalMass, double stiffnessValue, double dampingRatio=0.0 ) { using helper::vector; // The graph root node Node::SPtr root = simulation::getSimulation()->createNewGraph("root"); root->setGravity( Coord3(0,-10,0) ); root->setAnimate(false); root->setDt(0.01); addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true); Node::SPtr simulatedScene = root->createChild("simulatedScene"); EulerImplicitSolver::SPtr eulerImplicitSolver = New<EulerImplicitSolver>(); simulatedScene->addObject( eulerImplicitSolver ); CGLinearSolver::SPtr cgLinearSolver = New<CGLinearSolver>(); simulatedScene->addObject(cgLinearSolver); // The rigid object Node::SPtr rigidNode = simulatedScene->createChild("rigidNode"); MechanicalObjectRigid3d::SPtr rigid_dof = addNew<MechanicalObjectRigid3d>(rigidNode, "dof"); UniformMassRigid3d::SPtr rigid_mass = addNew<UniformMassRigid3d>(rigidNode,"mass"); FixedConstraintRigid3d::SPtr rigid_fixedConstraint = addNew<FixedConstraintRigid3d>(rigidNode,"fixedConstraint"); // Particles mapped to the rigid object Node::SPtr mappedParticles = rigidNode->createChild("mappedParticles"); MechanicalObject3d::SPtr mappedParticles_dof = addNew< MechanicalObject3d>(mappedParticles,"dof"); RigidMappingRigid3d_to_3d::SPtr mappedParticles_mapping = addNew<RigidMappingRigid3d_to_3d>(mappedParticles,"mapping"); mappedParticles_mapping->setModels( rigid_dof.get(), mappedParticles_dof.get() ); // The independent particles Node::SPtr independentParticles = simulatedScene->createChild("independentParticles"); MechanicalObject3d::SPtr independentParticles_dof = addNew< MechanicalObject3d>(independentParticles,"dof"); // The deformable grid, connected to its 2 parents using a MultiMapping Node::SPtr deformableGrid = independentParticles->createChild("deformableGrid"); // first parent mappedParticles->addChild(deformableGrid); // second parent RegularGridTopology::SPtr deformableGrid_grid = addNew<RegularGridTopology>( deformableGrid, "grid" ); deformableGrid_grid->setNumVertices(numX,numY,numZ); deformableGrid_grid->setPos(startPoint[0],endPoint[0],startPoint[1],endPoint[1],startPoint[2],endPoint[2]); MechanicalObject3d::SPtr deformableGrid_dof = addNew< MechanicalObject3d>(deformableGrid,"dof"); SubsetMultiMapping3d_to_3d::SPtr deformableGrid_mapping = addNew<SubsetMultiMapping3d_to_3d>(deformableGrid,"mapping"); deformableGrid_mapping->addInputModel(independentParticles_dof.get()); // first parent deformableGrid_mapping->addInputModel(mappedParticles_dof.get()); // second parent deformableGrid_mapping->addOutputModel(deformableGrid_dof.get()); UniformMass3::SPtr mass = addNew<UniformMass3>(deformableGrid,"mass" ); mass->mass.setValue( totalMass/(numX*numY*numZ) ); HexahedronFEMForceField3d::SPtr hexaFem = addNew<HexahedronFEMForceField3d>(deformableGrid, "hexaFEM"); hexaFem->f_youngModulus.setValue(1000); hexaFem->f_poissonRatio.setValue(0.4); // ====== Set up the multimapping and its parents, based on its child deformableGrid_grid->init(); // initialize the grid, so that the particles are located in space deformableGrid_dof->init(); // create the state vectors MechanicalObject3::ReadVecCoord xgrid = deformableGrid_dof->readPositions(); // cerr<<"xgrid = " << xgrid << endl; // create the rigid frames and their bounding boxes unsigned numRigid = 2; vector<BoundingBox> boxes(numRigid); vector< vector<unsigned> > indices(numRigid); // indices of the particles in each box double eps = (endPoint[0]-startPoint[0])/(numX*2); // first box, x=xmin boxes[0] = BoundingBox(Vec3d(startPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps), Vec3d(startPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps)); // second box, x=xmax boxes[1] = BoundingBox(Vec3d(endPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps), Vec3d(endPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps)); rigid_dof->resize(numRigid); MechanicalObjectRigid3d::WriteVecCoord xrigid = rigid_dof->writePositions(); xrigid[0].getCenter()=Vec3d(startPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2])); xrigid[1].getCenter()=Vec3d( endPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2])); // find the particles in each box vector<bool> isFree(xgrid.size(),true); unsigned numMapped = 0; for(unsigned i=0; i<xgrid.size(); i++){ for(unsigned b=0; b<numRigid; b++ ) { if( isFree[i] && boxes[b].contains(xgrid[i]) ) { indices[b].push_back(i); // associate the particle with the box isFree[i] = false; numMapped++; } } } // distribution of the grid particles to the different parents (independent particle or solids. vector< pair<MechanicalObject3d*,unsigned> > parentParticles(xgrid.size()); // Copy the independent particles to their parent DOF independentParticles_dof->resize( numX*numY*numZ - numMapped ); MechanicalObject3::WriteVecCoord xindependent = independentParticles_dof->writePositions(); // parent positions unsigned independentIndex=0; for( unsigned i=0; i<xgrid.size(); i++ ){ if( isFree[i] ){ parentParticles[i]=make_pair(independentParticles_dof.get(),independentIndex); xindependent[independentIndex] = xgrid[i]; independentIndex++; } } // Mapped particles. The RigidMapping requires to cluster the particles based on their parent frame. mappedParticles_dof->resize(numMapped); MechanicalObject3::WriteVecCoord xmapped = mappedParticles_dof->writePositions(); // parent positions mappedParticles_mapping->globalToLocalCoords.setValue(true); // to define the mapped positions in world coordinates vector<unsigned>* pointsPerFrame = mappedParticles_mapping->pointsPerFrame.beginEdit(); // to set how many particles are attached to each frame unsigned mappedIndex=0; for( unsigned b=0; b<numRigid; b++ ) { const vector<unsigned>& ind = indices[b]; pointsPerFrame->push_back(ind.size()); // Tell the mapping the number of points associated with this frame. One box per frame for(unsigned i=0; i<ind.size(); i++) { parentParticles[ind[i]]=make_pair(mappedParticles_dof.get(),mappedIndex); xmapped[mappedIndex] = xgrid[ ind[i] ]; mappedIndex++; } } mappedParticles_mapping->pointsPerFrame.endEdit(); // Declare all the particles to the multimapping for( unsigned i=0; i<xgrid.size(); i++ ) { deformableGrid_mapping->addPoint( parentParticles[i].first, parentParticles[i].second ); } return root; } int main(int argc, char** argv) { sofa::helper::BackTrace::autodump(); sofa::core::ExecParams::defaultInstance()->setAspectID(0); sofa::helper::parse("This is a SOFA application. Here are the command line arguments") .option(&startAnim,'a',"start","start the animation loop") .option(&verbose,'v',"verbose","print debug info") (argc,argv); glutInit(&argc,argv); sofa::simulation::setSimulation(new sofa::simulation::graph::DAGSimulation()); sofa::component::init(); sofa::gui::initMain(); if (int err = sofa::gui::GUIManager::Init(argv[0],"")) return err; if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err; sofa::gui::GUIManager::SetDimension(800,600); //================================================= sofa::simulation::Node::SPtr groot = createGridScene(Vec3(0,0,0), Vec3(5,1,1), 6,2,2, 1.0, 100 ); //================================================= sofa::simulation::getSimulation()->init(groot.get()); sofa::gui::GUIManager::SetScene(groot); // Run the main loop if (int err = sofa::gui::GUIManager::MainLoop(groot)) return err; sofa::simulation::getSimulation()->unload(groot); sofa::gui::GUIManager::closeGUI(); return 0; } <commit_msg>r9424/sofa : fixed compositeObject build (depends on DAG/BGL options setup)<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <sofa/helper/ArgumentParser.h> #include <sofa/helper/UnitTest.h> #include <sofa/helper/vector_algebra.h> #include <sofa/helper/vector.h> #include <sofa/helper/BackTrace.h> #include <sofa/helper/system/PluginManager.h> #include <sofa/simulation/common/Simulation.h> #include <sofa/simulation/tree/TreeSimulation.h> #ifdef SOFA_HAVE_DAG #include <sofa/simulation/graph/DAGSimulation.h> #endif #ifdef SOFA_HAVE_BGL #include <sofa/simulation/bgl/BglSimulation.h> #endif #include <sofa/simulation/common/Node.h> #include <sofa/simulation/common/xml/initXml.h> #include <sofa/gui/GUIManager.h> #include <sofa/gui/Main.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #include <sofa/component/topology/MeshTopology.h> #include <sofa/component/topology/EdgeSetTopologyContainer.h> #include <sofa/component/topology/RegularGridTopology.h> #include <sofa/component/collision/SphereModel.h> #include <sofa/component/topology/CubeTopology.h> #include <sofa/component/visualmodel/VisualStyle.h> #include <sofa/component/odesolver/EulerImplicitSolver.h> #include <sofa/component/linearsolver/CGLinearSolver.h> //Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT. #include <sofa/component/typedef/Sofa_typedef.h> using namespace sofa; using namespace sofa::helper; using helper::vector; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using namespace sofa::component::container; using namespace sofa::component::topology; using namespace sofa::component::collision; using namespace sofa::component::visualmodel; using namespace sofa::component::mapping; using namespace sofa::component::forcefield; typedef SReal Scalar; typedef Vec<3,SReal> Vec3; typedef Vec<1,SReal> Vec1; typedef component::odesolver::EulerImplicitSolver EulerImplicitSolver; typedef component::linearsolver::CGLinearSolver<component::linearsolver::GraphScatteredMatrix, component::linearsolver::GraphScatteredVector> CGLinearSolver; bool startAnim = true; bool verbose = false; SReal complianceValue = 0.1; SReal dampingRatio = 0.1; Vec3 gravity(0,-1,0); SReal dt = 0.01; /// helper for more compact component creation template<class Component> typename Component::SPtr addNew( Node::SPtr parentNode, std::string name="" ) { typename Component::SPtr component = New<Component>(); parentNode->addObject(component); component->setName(parentNode->getName()+"_"+name); return component; } /// Create an assembly of a siff hexahedral grid with other objects simulation::Node::SPtr createGridScene(Vec3 startPoint, Vec3 endPoint, unsigned numX, unsigned numY, unsigned numZ, double totalMass, double stiffnessValue, double dampingRatio=0.0 ) { using helper::vector; // The graph root node Node::SPtr root = simulation::getSimulation()->createNewGraph("root"); root->setGravity( Coord3(0,-10,0) ); root->setAnimate(false); root->setDt(0.01); addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true); Node::SPtr simulatedScene = root->createChild("simulatedScene"); EulerImplicitSolver::SPtr eulerImplicitSolver = New<EulerImplicitSolver>(); simulatedScene->addObject( eulerImplicitSolver ); CGLinearSolver::SPtr cgLinearSolver = New<CGLinearSolver>(); simulatedScene->addObject(cgLinearSolver); // The rigid object Node::SPtr rigidNode = simulatedScene->createChild("rigidNode"); MechanicalObjectRigid3d::SPtr rigid_dof = addNew<MechanicalObjectRigid3d>(rigidNode, "dof"); UniformMassRigid3d::SPtr rigid_mass = addNew<UniformMassRigid3d>(rigidNode,"mass"); FixedConstraintRigid3d::SPtr rigid_fixedConstraint = addNew<FixedConstraintRigid3d>(rigidNode,"fixedConstraint"); // Particles mapped to the rigid object Node::SPtr mappedParticles = rigidNode->createChild("mappedParticles"); MechanicalObject3d::SPtr mappedParticles_dof = addNew< MechanicalObject3d>(mappedParticles,"dof"); RigidMappingRigid3d_to_3d::SPtr mappedParticles_mapping = addNew<RigidMappingRigid3d_to_3d>(mappedParticles,"mapping"); mappedParticles_mapping->setModels( rigid_dof.get(), mappedParticles_dof.get() ); // The independent particles Node::SPtr independentParticles = simulatedScene->createChild("independentParticles"); MechanicalObject3d::SPtr independentParticles_dof = addNew< MechanicalObject3d>(independentParticles,"dof"); // The deformable grid, connected to its 2 parents using a MultiMapping Node::SPtr deformableGrid = independentParticles->createChild("deformableGrid"); // first parent mappedParticles->addChild(deformableGrid); // second parent RegularGridTopology::SPtr deformableGrid_grid = addNew<RegularGridTopology>( deformableGrid, "grid" ); deformableGrid_grid->setNumVertices(numX,numY,numZ); deformableGrid_grid->setPos(startPoint[0],endPoint[0],startPoint[1],endPoint[1],startPoint[2],endPoint[2]); MechanicalObject3d::SPtr deformableGrid_dof = addNew< MechanicalObject3d>(deformableGrid,"dof"); SubsetMultiMapping3d_to_3d::SPtr deformableGrid_mapping = addNew<SubsetMultiMapping3d_to_3d>(deformableGrid,"mapping"); deformableGrid_mapping->addInputModel(independentParticles_dof.get()); // first parent deformableGrid_mapping->addInputModel(mappedParticles_dof.get()); // second parent deformableGrid_mapping->addOutputModel(deformableGrid_dof.get()); UniformMass3::SPtr mass = addNew<UniformMass3>(deformableGrid,"mass" ); mass->mass.setValue( totalMass/(numX*numY*numZ) ); HexahedronFEMForceField3d::SPtr hexaFem = addNew<HexahedronFEMForceField3d>(deformableGrid, "hexaFEM"); hexaFem->f_youngModulus.setValue(1000); hexaFem->f_poissonRatio.setValue(0.4); // ====== Set up the multimapping and its parents, based on its child deformableGrid_grid->init(); // initialize the grid, so that the particles are located in space deformableGrid_dof->init(); // create the state vectors MechanicalObject3::ReadVecCoord xgrid = deformableGrid_dof->readPositions(); // cerr<<"xgrid = " << xgrid << endl; // create the rigid frames and their bounding boxes unsigned numRigid = 2; vector<BoundingBox> boxes(numRigid); vector< vector<unsigned> > indices(numRigid); // indices of the particles in each box double eps = (endPoint[0]-startPoint[0])/(numX*2); // first box, x=xmin boxes[0] = BoundingBox(Vec3d(startPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps), Vec3d(startPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps)); // second box, x=xmax boxes[1] = BoundingBox(Vec3d(endPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps), Vec3d(endPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps)); rigid_dof->resize(numRigid); MechanicalObjectRigid3d::WriteVecCoord xrigid = rigid_dof->writePositions(); xrigid[0].getCenter()=Vec3d(startPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2])); xrigid[1].getCenter()=Vec3d( endPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2])); // find the particles in each box vector<bool> isFree(xgrid.size(),true); unsigned numMapped = 0; for(unsigned i=0; i<xgrid.size(); i++){ for(unsigned b=0; b<numRigid; b++ ) { if( isFree[i] && boxes[b].contains(xgrid[i]) ) { indices[b].push_back(i); // associate the particle with the box isFree[i] = false; numMapped++; } } } // distribution of the grid particles to the different parents (independent particle or solids. vector< pair<MechanicalObject3d*,unsigned> > parentParticles(xgrid.size()); // Copy the independent particles to their parent DOF independentParticles_dof->resize( numX*numY*numZ - numMapped ); MechanicalObject3::WriteVecCoord xindependent = independentParticles_dof->writePositions(); // parent positions unsigned independentIndex=0; for( unsigned i=0; i<xgrid.size(); i++ ){ if( isFree[i] ){ parentParticles[i]=make_pair(independentParticles_dof.get(),independentIndex); xindependent[independentIndex] = xgrid[i]; independentIndex++; } } // Mapped particles. The RigidMapping requires to cluster the particles based on their parent frame. mappedParticles_dof->resize(numMapped); MechanicalObject3::WriteVecCoord xmapped = mappedParticles_dof->writePositions(); // parent positions mappedParticles_mapping->globalToLocalCoords.setValue(true); // to define the mapped positions in world coordinates vector<unsigned>* pointsPerFrame = mappedParticles_mapping->pointsPerFrame.beginEdit(); // to set how many particles are attached to each frame unsigned mappedIndex=0; for( unsigned b=0; b<numRigid; b++ ) { const vector<unsigned>& ind = indices[b]; pointsPerFrame->push_back(ind.size()); // Tell the mapping the number of points associated with this frame. One box per frame for(unsigned i=0; i<ind.size(); i++) { parentParticles[ind[i]]=make_pair(mappedParticles_dof.get(),mappedIndex); xmapped[mappedIndex] = xgrid[ ind[i] ]; mappedIndex++; } } mappedParticles_mapping->pointsPerFrame.endEdit(); // Declare all the particles to the multimapping for( unsigned i=0; i<xgrid.size(); i++ ) { deformableGrid_mapping->addPoint( parentParticles[i].first, parentParticles[i].second ); } return root; } int main(int argc, char** argv) { sofa::helper::BackTrace::autodump(); sofa::core::ExecParams::defaultInstance()->setAspectID(0); sofa::helper::parse("This is a SOFA application. Here are the command line arguments") .option(&startAnim,'a',"start","start the animation loop") .option(&verbose,'v',"verbose","print debug info") (argc,argv); glutInit(&argc,argv); #if defined(SOFA_HAVE_DAG) sofa::simulation::setSimulation(new sofa::simulation::graph::DAGSimulation()); #elif defined(SOFA_HAVE_BGL) sofa::simulation::setSimulation(new sofa::simulation::bgl::BglSimulation()); #else sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation()); #endif sofa::component::init(); sofa::gui::initMain(); if (int err = sofa::gui::GUIManager::Init(argv[0],"")) return err; if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err; sofa::gui::GUIManager::SetDimension(800,600); //================================================= sofa::simulation::Node::SPtr groot = createGridScene(Vec3(0,0,0), Vec3(5,1,1), 6,2,2, 1.0, 100 ); //================================================= sofa::simulation::getSimulation()->init(groot.get()); sofa::gui::GUIManager::SetScene(groot); // Run the main loop if (int err = sofa::gui::GUIManager::MainLoop(groot)) return err; sofa::simulation::getSimulation()->unload(groot); sofa::gui::GUIManager::closeGUI(); return 0; } <|endoftext|>
<commit_before>#include "domain.h" #include "person.h" #include <iostream> #include <algorithm> #include <vector> #include "data.h" #include "console.h" using namespace std; Domain::Domain() { } bool agePerson (const Person& lsh, const Person& rhs) // sort by birthyear { return (lsh.getBirth() < rhs.getBirth()); } void Domain::ageSorting(vector<Person> &ageSort) //sort by birthyear { std::sort(ageSort.begin(), ageSort.end(), agePerson); } bool nameAlpha(const Person& lhs, const Person& rhs) { return (lhs.getName() < rhs.getName()); } void Domain::alphabeticSort(vector<Person> &alphaSort) { std::sort(alphaSort.begin(), alphaSort.end(), nameAlpha); } /* bool sortAge (const Domain& lsh, const Domain& rhs) //sort by age { return (lsh.findAge() < rhs.findAge()); } void Domain::sortingAge(vector<Person> &ageSort) //sort by age { std::sort(ageSort.begin(), ageSort.end(), sortAge); }*/ int Domain::findAge(Person& sciAge) const { int x; int y; int resultDead; int resultAlive; const int currentYear = 2016; x = sciAge.getDeath(); y = sciAge.getBirth(); if(x == 0) { resultAlive = currentYear - y; return resultAlive; } else { resultDead = x - y; return resultDead; } } vector<Person> Domain::search(vector<Person>& p, string name) { vector<Person> results; for(unsigned int i = 0; i < p.size(); i++) { string nameFind; char genderFind; int birthFind; int deathFind; nameFind = p[i].getName(); std::size_t found = nameFind.find(name); if (found!=std::string::npos) { p[i].getName(); genderFind = p[i].getGender(); birthFind = p[i].getBirth(); deathFind = p[i].getDeath(); Person p2(nameFind, genderFind, birthFind, deathFind); results.push_back(p2); } } return results; } <commit_msg>throwaway<commit_after>#include "domain.h" #include "person.h" #include <iostream> #include <algorithm> #include <vector> #include "data.h" #include "console.h" using namespace std; Domain::Domain() { } bool agePerson (const Person& lsh, const Person& rhs) // sort by birthyear { return (lsh.getBirth() < rhs.getBirth()); } void Domain::ageSorting(vector<Person> &ageSort) //sort by birthyear { std::sort(ageSort.begin(), ageSort.end(), agePerson); } bool nameAlpha(const Person& lhs, const Person& rhs) { return (lhs.getName() < rhs.getName()); } void Domain::alphabeticSort(vector<Person> &alphaSort) { std::sort(alphaSort.begin(), alphaSort.end(), nameAlpha); } bool sortAge (const Domain& lsh, const Domain& rhs) //sort by age { return (lsh.findAge() < rhs.findAge()); } void Domain::sortingAge(vector<Person> &ageSort) //sort by age { std::sort(ageSort.begin(), ageSort.end(), sortAge); } int Domain::findAge(Person& sciAge) const { int x; int y; int resultDead; int resultAlive; const int currentYear = 2016; x = sciAge.getDeath(); y = sciAge.getBirth(); if(x == 0) { resultAlive = currentYear - y; return resultAlive; } else { resultDead = x - y; return resultDead; } } vector<Person> Domain::search(vector<Person>& p, string name) { vector<Person> results; for(unsigned int i = 0; i < p.size(); i++) { string nameFind; char genderFind; int birthFind; int deathFind; nameFind = p[i].getName(); std::size_t found = nameFind.find(name); if (found!=std::string::npos) { p[i].getName(); genderFind = p[i].getGender(); birthFind = p[i].getBirth(); deathFind = p[i].getDeath(); Person p2(nameFind, genderFind, birthFind, deathFind); results.push_back(p2); } } return results; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include <errno.h> #include <fcntl.h> #include <linux/limits.h> #include <poll.h> #include <sys/inotify.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <string> #include <vector> #include "file_watcher_inotify.h" #include "logging.h" #include "util/posix.h" namespace file_watcher { FileWatcherInotify::FileWatcherInotify() {} FileWatcherInotify::~FileWatcherInotify() {} bool FileWatcherInotify::RunEventLoop(const FileWatcher::HandlerMap& handlers, int read_pipe, int write_pipe) { inotify_fd_ = inotify_init1(IN_NONBLOCK); assert(inotify_fd_ >= 0); for (FileWatcher::HandlerMap::const_iterator it = handlers.begin(); it != handlers.end(); ++it) { RegisterFilter(it->first, it->second); } // Use the control pipe to signal readiness to the main thread, // before continuing with the event loop. WritePipe(write_pipe, "s", 1); struct pollfd poll_set[2]; poll_set[0].fd = read_pipe; poll_set[0].events = POLLHUP | POLLIN; poll_set[0].revents = 0; poll_set[1].fd = inotify_fd_; poll_set[1].events = POLLIN; poll_set[1].revents = 0; bool stop = false; while (!stop) { int ready = poll(poll_set, 2, -1); if (ready == -1) { if (errno == EINTR) { continue; } LogCvmfs(kLogCvmfs, kLogSyslogErr, "FileWatcherInotify - Could not poll events. Errno: %d", errno); return false; } if (ready == 0) { continue; } if (poll_set[0].revents & POLLHUP) { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Stopping.\n"); stop = true; continue; } if (poll_set[0].revents & POLLIN) { char buffer[1]; ReadPipe(read_pipe, &buffer, 1); LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Stopping.\n"); stop = true; continue; } const size_t event_size = sizeof(struct inotify_event); // We need a buffer large enough to accommodate an event for the largest path name const size_t buffer_size = event_size + PATH_MAX + 1; char buffer[buffer_size]; if (poll_set[1].revents & POLLIN) { int len = read(inotify_fd_, buffer, buffer_size); assert(len > 0); int i = 0; while (i < len) { struct inotify_event* inotify_event = reinterpret_cast<struct inotify_event*>(&buffer[i]); std::map<int, WatchRecord>::const_iterator it = watch_records_.find(inotify_event->wd); if (it != watch_records_.end()) { WatchRecord current_record = it->second; file_watcher::Event event = file_watcher::kInvalid; if (inotify_event->mask & IN_DELETE_SELF) { event = file_watcher::kDeleted; } else if (inotify_event->mask & IN_MODIFY) { // Modified event = file_watcher::kModified; } else if (inotify_event->mask & IN_MOVE_SELF) { // Renamed event = file_watcher::kRenamed; } else if (inotify_event->mask & IN_ATTRIB) { // Attributes event = file_watcher::kAttributes; } else if (inotify_event->mask & IN_IGNORED) { // IN_IGNORED event is generated after a file is deleted and the watch is // removed event = file_watcher::kIgnored; } bool clear_handler = true; if (event != file_watcher::kInvalid && event != file_watcher::kIgnored) { current_record.handler_->Handle(current_record.file_path_, event, &clear_handler); } else { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Unknown event 0x%x\n", inotify_event->mask); } // Perform post-handling actions (i.e. remove, reset filter) if (event == file_watcher::kDeleted) { watch_records_.erase(inotify_event->wd); if (!clear_handler) { RegisterFilter(current_record.file_path_, current_record.handler_); } } } else { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Unknown event ident: %ld", inotify_event->wd); } i += event_size + inotify_event->len; } } } watch_records_.clear(); close(inotify_fd_); return true; } int FileWatcherInotify::TryRegisterFilter(const std::string& file_path) { return inotify_add_watch( inotify_fd_, file_path.c_str(), IN_ATTRIB | IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF); } } // namespace file_watcher <commit_msg>Fix CPPLINT<commit_after>/** * This file is part of the CernVM File System. */ #include <errno.h> #include <fcntl.h> #include <linux/limits.h> #include <poll.h> #include <sys/inotify.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <string> #include <vector> #include "file_watcher_inotify.h" #include "logging.h" #include "util/posix.h" namespace file_watcher { FileWatcherInotify::FileWatcherInotify() {} FileWatcherInotify::~FileWatcherInotify() {} bool FileWatcherInotify::RunEventLoop(const FileWatcher::HandlerMap& handlers, int read_pipe, int write_pipe) { inotify_fd_ = inotify_init1(IN_NONBLOCK); assert(inotify_fd_ >= 0); for (FileWatcher::HandlerMap::const_iterator it = handlers.begin(); it != handlers.end(); ++it) { RegisterFilter(it->first, it->second); } // Use the control pipe to signal readiness to the main thread, // before continuing with the event loop. WritePipe(write_pipe, "s", 1); struct pollfd poll_set[2]; poll_set[0].fd = read_pipe; poll_set[0].events = POLLHUP | POLLIN; poll_set[0].revents = 0; poll_set[1].fd = inotify_fd_; poll_set[1].events = POLLIN; poll_set[1].revents = 0; bool stop = false; while (!stop) { int ready = poll(poll_set, 2, -1); if (ready == -1) { if (errno == EINTR) { continue; } LogCvmfs(kLogCvmfs, kLogSyslogErr, "FileWatcherInotify - Could not poll events. Errno: %d", errno); return false; } if (ready == 0) { continue; } if (poll_set[0].revents & POLLHUP) { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Stopping.\n"); stop = true; continue; } if (poll_set[0].revents & POLLIN) { char buffer[1]; ReadPipe(read_pipe, &buffer, 1); LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Stopping.\n"); stop = true; continue; } const size_t event_size = sizeof(struct inotify_event); // We need a large enough buffer for an event with the largest path name const size_t buffer_size = event_size + PATH_MAX + 1; char buffer[buffer_size]; if (poll_set[1].revents & POLLIN) { int len = read(inotify_fd_, buffer, buffer_size); assert(len > 0); int i = 0; while (i < len) { struct inotify_event* inotify_event = reinterpret_cast<struct inotify_event*>(&buffer[i]); std::map<int, WatchRecord>::const_iterator it = watch_records_.find(inotify_event->wd); if (it != watch_records_.end()) { WatchRecord current_record = it->second; file_watcher::Event event = file_watcher::kInvalid; if (inotify_event->mask & IN_DELETE_SELF) { event = file_watcher::kDeleted; } else if (inotify_event->mask & IN_MODIFY) { // Modified event = file_watcher::kModified; } else if (inotify_event->mask & IN_MOVE_SELF) { // Renamed event = file_watcher::kRenamed; } else if (inotify_event->mask & IN_ATTRIB) { // Attributes event = file_watcher::kAttributes; } else if (inotify_event->mask & IN_IGNORED) { // An IN_IGNORED event is generated after a file is deleted and the // watch is removed event = file_watcher::kIgnored; } bool clear_handler = true; if (event != file_watcher::kInvalid && event != file_watcher::kIgnored) { current_record.handler_->Handle(current_record.file_path_, event, &clear_handler); } else { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Unknown event 0x%x\n", inotify_event->mask); } // Perform post-handling actions (i.e. remove, reset filter) if (event == file_watcher::kDeleted) { watch_records_.erase(inotify_event->wd); if (!clear_handler) { RegisterFilter(current_record.file_path_, current_record.handler_); } } } else { LogCvmfs(kLogCvmfs, kLogDebug, "FileWatcherInotify - Unknown event ident: %ld", inotify_event->wd); } i += event_size + inotify_event->len; } } } watch_records_.clear(); close(inotify_fd_); return true; } int FileWatcherInotify::TryRegisterFilter(const std::string& file_path) { return inotify_add_watch( inotify_fd_, file_path.c_str(), IN_ATTRIB | IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF); } } // namespace file_watcher <|endoftext|>
<commit_before>/** * @file posixtimer.hpp * @brief Simple timer using POSIX functions. * @author Paolo D'Apice */ #ifndef VIS_UTILS_POSIXTIMER_HPP #define VIS_UTILS_POSIXTIMER_HPP #warning "This class has been deprecated" #include <sys/time.h> /// @brief Type used for timestamps. typedef unsigned long long timestamp_t; /// @brief Simple timer using POSIX functions. class PosixTimer { public: /// Start measuring time. void tic() { gettimeofday(&start, NULL); } /// Get measure of elapsed time since last \c tic(). void toc() { gettimeofday(&stop, NULL); elapsed = getMicroseconds(stop) - getMicroseconds(start); } /// @return Elapsed time in microseconds. timestamp_t getMicros() const { return elapsed; } /// @return Elapsed time in milliseconds. timestamp_t getMillis() const { return elapsed / 1e3; } /// @return Elapsed time in seconds. timestamp_t getSeconds() const { return elapsed / 1e6; } private: // Get current time in microseconds timestamp_t getMicroseconds(const timeval& t) { return t.tv_sec * 1000000 + t.tv_usec; } struct timeval start; struct timeval stop; timestamp_t elapsed; }; #endif /* VIS_UTILS_POSIXTIMER_HPP */ <commit_msg>Using C++11 attributes for deprecated class PosixTimer<commit_after>/** * @file posixtimer.hpp * @brief Simple timer using POSIX functions. * @author Paolo D'Apice */ #ifndef VIS_UTILS_POSIXTIMER_HPP #define VIS_UTILS_POSIXTIMER_HPP #include <sys/time.h> /// @brief Type used for timestamps. typedef unsigned long long timestamp_t; /// @brief Simple timer using POSIX functions. class [[deprecated]] PosixTimer { public: /// Start measuring time. void tic() { gettimeofday(&start, NULL); } /// Get measure of elapsed time since last \c tic(). void toc() { gettimeofday(&stop, NULL); elapsed = getMicroseconds(stop) - getMicroseconds(start); } /// @return Elapsed time in microseconds. timestamp_t getMicros() const { return elapsed; } /// @return Elapsed time in milliseconds. timestamp_t getMillis() const { return elapsed / 1e3; } /// @return Elapsed time in seconds. timestamp_t getSeconds() const { return elapsed / 1e6; } private: // Get current time in microseconds timestamp_t getMicroseconds(const timeval& t) { return t.tv_sec * 1000000 + t.tv_usec; } struct timeval start; struct timeval stop; timestamp_t elapsed; }; #endif /* VIS_UTILS_POSIXTIMER_HPP */ <|endoftext|>
<commit_before>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "Dialog.h" #include "../../3RVX/Logger.h" #include "Control.h" Dialog::Dialog(LPCWSTR className, LPCWSTR dlgTemplate) : Window(className) { _dlgHwnd = CreateDialogParam( Window::InstanceHandle(), dlgTemplate, Window::Handle(), StaticDialogProc, (LPARAM) this); } void Dialog::AddControl(Control *control) { if (control == nullptr) { return; } CLOG(L"Adding control id: %d", control->ID()); int id = control->ID(); _controlMap[id] = control; } HWND Dialog::DialogHandle() { return _dlgHwnd; } INT_PTR Dialog::StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { Dialog *dlg; if (uMsg == WM_INITDIALOG) { dlg = (Dialog *) lParam; SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg); } else { dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER); if (!dlg) { return FALSE; } } return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam); } INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { unsigned short nCode, ctrlId; switch (uMsg) { case WM_INITDIALOG: return FALSE; case WM_COMMAND: nCode = HIWORD(wParam); ctrlId = LOWORD(wParam); if (_controlMap.count(ctrlId) > 0) { return _controlMap[ctrlId]->Command(nCode); } else { return FALSE; } case WM_NOTIFY: NMHDR *nHdr = (NMHDR *) lParam; ctrlId = nHdr->idFrom; if (_controlMap.count(ctrlId) > 0) { return _controlMap[ctrlId]->Notification(nHdr); } else { return FALSE; } } return FALSE; } <commit_msg>Translate download dialog text<commit_after>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "Dialog.h" #include "../../3RVX/Logger.h" #include "../UITranslator.h" #include "Control.h" Dialog::Dialog(LPCWSTR className, LPCWSTR dlgTemplate) : Window(className) { _dlgHwnd = CreateDialogParam( Window::InstanceHandle(), dlgTemplate, Window::Handle(), StaticDialogProc, (LPARAM) this); UITranslator::TranslateWindowText(_dlgHwnd); } void Dialog::AddControl(Control *control) { if (control == nullptr) { return; } CLOG(L"Adding control id: %d", control->ID()); int id = control->ID(); _controlMap[id] = control; } HWND Dialog::DialogHandle() { return _dlgHwnd; } INT_PTR Dialog::StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { Dialog *dlg; if (uMsg == WM_INITDIALOG) { dlg = (Dialog *) lParam; SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg); } else { dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER); if (!dlg) { return FALSE; } } return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam); } INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { unsigned short nCode, ctrlId; switch (uMsg) { case WM_INITDIALOG: return FALSE; case WM_COMMAND: nCode = HIWORD(wParam); ctrlId = LOWORD(wParam); if (_controlMap.count(ctrlId) > 0) { return _controlMap[ctrlId]->Command(nCode); } else { return FALSE; } case WM_NOTIFY: NMHDR *nHdr = (NMHDR *) lParam; ctrlId = nHdr->idFrom; if (_controlMap.count(ctrlId) > 0) { return _controlMap[ctrlId]->Notification(nHdr); } else { return FALSE; } } return FALSE; } <|endoftext|>
<commit_before>#include "SpriteRenderer.hpp" #include "ShaderManager.hpp" #include <iostream> SpriteRenderer::SpriteRenderer() { } void SpriteRenderer::init() { m_VertexBuffer.init(); m_TexCoordBuffer.init(); } void SpriteRenderer::render(std::vector<Sprite>& sprites, Texture& texture) { clearVectors(); for (auto& sprite : sprites) { addVertices(sprite.getPosition(), sprite.getSize(), sprite.getRotationRads()); addTexCoords(sprite.getTextureBounds(), glm::vec2(texture.width, texture.height)); } texture.bind(); glActiveTexture(GL_TEXTURE0 + texture.getId()); passDataToBuffers(); m_VertexBuffer.bind(); ShaderManager::getInstance().getShader("Texture")->bind(); ShaderManager::getInstance().getShader("Texture")->setupVertexAttribPointer("in_Position"); m_TexCoordBuffer.bind(); ShaderManager::getInstance().getShader("Texture")->setupVertexAttribPointer("in_TexCoords"); ShaderManager::getInstance().getShader("Texture")->setUniform("in_Texture", texture.getId()); glDrawArrays(GL_TRIANGLES, 0, m_VertexBuffer.getDataSize()); } void SpriteRenderer::passDataToBuffers() { m_VertexBuffer.setData(m_Vertices); m_TexCoordBuffer.setData(m_TexCoords); } void SpriteRenderer::addTexCoords(const TextureBounds& textureBounds, const glm::vec2& textureSize) { // Bottom Left m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); // Bottom Right m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); // Top Right m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Top Right (2) m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Top Left m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Bottom Left (2) m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); } void SpriteRenderer::addVertices(const glm::vec2& position, const glm::vec2& size, float rotationRads) { auto sinAngle = glm::sin(rotationRads); auto cosAngle = glm::cos(rotationRads); auto offsetFromCenter = glm::vec2(-size.x / 2.f, -size.y / 2.f); auto bottomLeft = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(size.x / 2.f, -size.y / 2.f); auto bottomRight = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(size.x / 2.f, size.y / 2.f); auto topRight = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(-size.x / 2.f, size.y / 2.f); auto topLeft = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); // Bottom Left m_Vertices.push_back(bottomLeft.x); m_Vertices.push_back(bottomLeft.y); // Bottom Right m_Vertices.push_back(bottomRight.x); m_Vertices.push_back(bottomRight.y); // Top Right m_Vertices.push_back(topRight.x); m_Vertices.push_back(topRight.y); // Top Right (2) m_Vertices.push_back(topRight.x); m_Vertices.push_back(topRight.y); // Top Left m_Vertices.push_back(topLeft.x); m_Vertices.push_back(topLeft.y); // Bottom Left (2) m_Vertices.push_back(bottomLeft.x); m_Vertices.push_back(bottomLeft.y); } void SpriteRenderer::clearVectors() { m_Vertices.clear(); m_TexCoords.clear(); }<commit_msg>Fixed bug which was rendering the wrong textures (they were switched)<commit_after>#include "SpriteRenderer.hpp" #include "ShaderManager.hpp" #include <iostream> SpriteRenderer::SpriteRenderer() { } void SpriteRenderer::init() { m_VertexBuffer.init(); m_TexCoordBuffer.init(); } void SpriteRenderer::render(std::vector<Sprite>& sprites, Texture& texture) { clearVectors(); for (auto& sprite : sprites) { addVertices(sprite.getPosition(), sprite.getSize(), sprite.getRotationRads()); addTexCoords(sprite.getTextureBounds(), glm::vec2(texture.width, texture.height)); } texture.bind(); passDataToBuffers(); m_VertexBuffer.bind(); ShaderManager::getInstance().getShader("Texture")->bind(); ShaderManager::getInstance().getShader("Texture")->setupVertexAttribPointer("in_Position"); m_TexCoordBuffer.bind(); ShaderManager::getInstance().getShader("Texture")->setupVertexAttribPointer("in_TexCoords"); ShaderManager::getInstance().getShader("Texture")->setUniform("in_Texture", texture.getId()); glDrawArrays(GL_TRIANGLES, 0, m_VertexBuffer.getDataSize()); } void SpriteRenderer::passDataToBuffers() { m_VertexBuffer.setData(m_Vertices); m_TexCoordBuffer.setData(m_TexCoords); } void SpriteRenderer::addTexCoords(const TextureBounds& textureBounds, const glm::vec2& textureSize) { // Bottom Left m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); // Bottom Right m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); // Top Right m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Top Right (2) m_TexCoords.push_back((textureBounds.bottomLeft.x + textureBounds.size.x) / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Top Left m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - (textureBounds.bottomLeft.y + textureBounds.size.y)) / textureSize.y); // Bottom Left (2) m_TexCoords.push_back(textureBounds.bottomLeft.x / textureSize.x); m_TexCoords.push_back((textureSize.y - textureBounds.bottomLeft.y) / textureSize.y); } void SpriteRenderer::addVertices(const glm::vec2& position, const glm::vec2& size, float rotationRads) { auto sinAngle = glm::sin(rotationRads); auto cosAngle = glm::cos(rotationRads); auto offsetFromCenter = glm::vec2(-size.x / 2.f, -size.y / 2.f); auto bottomLeft = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(size.x / 2.f, -size.y / 2.f); auto bottomRight = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(size.x / 2.f, size.y / 2.f); auto topRight = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); offsetFromCenter = glm::vec2(-size.x / 2.f, size.y / 2.f); auto topLeft = glm::vec2(position.x + (offsetFromCenter.x * cosAngle - offsetFromCenter.y * sinAngle), position.y - (-offsetFromCenter.y * cosAngle - offsetFromCenter.x * sinAngle)); // Bottom Left m_Vertices.push_back(bottomLeft.x); m_Vertices.push_back(bottomLeft.y); // Bottom Right m_Vertices.push_back(bottomRight.x); m_Vertices.push_back(bottomRight.y); // Top Right m_Vertices.push_back(topRight.x); m_Vertices.push_back(topRight.y); // Top Right (2) m_Vertices.push_back(topRight.x); m_Vertices.push_back(topRight.y); // Top Left m_Vertices.push_back(topLeft.x); m_Vertices.push_back(topLeft.y); // Bottom Left (2) m_Vertices.push_back(bottomLeft.x); m_Vertices.push_back(bottomLeft.y); } void SpriteRenderer::clearVectors() { m_Vertices.clear(); m_TexCoords.clear(); }<|endoftext|>
<commit_before>// Copyright 2019 The TCMalloc Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "tcmalloc/parameters.h" #include "absl/time/time.h" #include "tcmalloc/common.h" #include "tcmalloc/experiment.h" #include "tcmalloc/experiment_config.h" #include "tcmalloc/huge_page_aware_allocator.h" #include "tcmalloc/lifetime_based_allocator.h" #include "tcmalloc/malloc_extension.h" #include "tcmalloc/static_vars.h" #include "tcmalloc/thread_cache.h" GOOGLE_MALLOC_SECTION_BEGIN namespace tcmalloc { namespace tcmalloc_internal { // As decide_subrelease() is determined at runtime, we cannot require constant // initialization for the atomic. This avoids an initialization order fiasco. static std::atomic<bool>* hpaa_subrelease_ptr() { static std::atomic<bool> v(decide_subrelease()); return &v; } // As skip_subrelease_interval_ns() is determined at runtime, we cannot require // constant initialization for the atomic. This avoids an initialization order // fiasco. static std::atomic<int64_t>& skip_subrelease_interval_ns() { static std::atomic<int64_t> v(absl::ToInt64Nanoseconds( #if defined(TCMALLOC_SMALL_BUT_SLOW) absl::ZeroDuration() #else absl::Seconds(60) #endif )); return v; } uint64_t Parameters::heap_size_hard_limit() { size_t amount; bool is_hard; std::tie(amount, is_hard) = Static::page_allocator().limit(); if (!is_hard) { amount = 0; } return amount; } void Parameters::set_heap_size_hard_limit(uint64_t value) { TCMalloc_Internal_SetHeapSizeHardLimit(value); } bool Parameters::hpaa_subrelease() { return hpaa_subrelease_ptr()->load(std::memory_order_relaxed); } void Parameters::set_hpaa_subrelease(bool value) { TCMalloc_Internal_SetHPAASubrelease(value); } ABSL_CONST_INIT std::atomic<MallocExtension::BytesPerSecond> Parameters::background_release_rate_(MallocExtension::BytesPerSecond{ 0 }); ABSL_CONST_INIT std::atomic<int64_t> Parameters::guarded_sampling_rate_( 50 * kDefaultProfileSamplingRate); ABSL_CONST_INIT std::atomic<bool> Parameters::shuffle_per_cpu_caches_enabled_( true); ABSL_CONST_INIT std::atomic<int32_t> Parameters::max_per_cpu_cache_size_( kMaxCpuCacheSize); ABSL_CONST_INIT std::atomic<bool> Parameters::prioritize_spans_enabled_(false); ABSL_CONST_INIT std::atomic<int64_t> Parameters::max_total_thread_cache_bytes_( kDefaultOverallThreadCacheSize); ABSL_CONST_INIT std::atomic<double> Parameters::peak_sampling_heap_growth_fraction_(1.1); ABSL_CONST_INIT std::atomic<bool> Parameters::per_cpu_caches_enabled_( #if defined(TCMALLOC_DEPRECATED_PERTHREAD) false #else true #endif ); ABSL_CONST_INIT std::atomic<bool> Parameters::per_cpu_caches_dynamic_slab_enabled_(false); ABSL_CONST_INIT std::atomic<double> Parameters::per_cpu_caches_dynamic_slab_grow_threshold_(0.9); ABSL_CONST_INIT std::atomic<double> Parameters::per_cpu_caches_dynamic_slab_shrink_threshold_(0.5); ABSL_CONST_INIT std::atomic<int64_t> Parameters::profile_sampling_rate_( kDefaultProfileSamplingRate); absl::Duration Parameters::filler_skip_subrelease_interval() { return absl::Nanoseconds( skip_subrelease_interval_ns().load(std::memory_order_relaxed)); } bool Parameters::pass_span_object_count_to_pageheap() { static bool v([]() { return IsExperimentActive( Experiment::TEST_ONLY_TCMALLOC_PASS_SPAN_OBJECT_COUNT_TO_PAGEHEAP); }()); return v; } } // namespace tcmalloc_internal } // namespace tcmalloc GOOGLE_MALLOC_SECTION_END using tcmalloc::tcmalloc_internal::kLog; using tcmalloc::tcmalloc_internal::Log; using tcmalloc::tcmalloc_internal::Parameters; using tcmalloc::tcmalloc_internal::Static; extern "C" { int64_t MallocExtension_Internal_GetProfileSamplingRate() { return Parameters::profile_sampling_rate(); } void MallocExtension_Internal_SetProfileSamplingRate(int64_t value) { Parameters::set_profile_sampling_rate(value); } int64_t MallocExtension_Internal_GetGuardedSamplingRate() { return Parameters::guarded_sampling_rate(); } void MallocExtension_Internal_SetGuardedSamplingRate(int64_t value) { Parameters::set_guarded_sampling_rate(value); } int64_t MallocExtension_Internal_GetMaxTotalThreadCacheBytes() { return Parameters::max_total_thread_cache_bytes(); } void MallocExtension_Internal_SetMaxTotalThreadCacheBytes(int64_t value) { Parameters::set_max_total_thread_cache_bytes(value); } void MallocExtension_Internal_GetSkipSubreleaseInterval(absl::Duration* ret) { *ret = Parameters::filler_skip_subrelease_interval(); } void MallocExtension_Internal_SetSkipSubreleaseInterval(absl::Duration value) { Parameters::set_filler_skip_subrelease_interval(value); } tcmalloc::MallocExtension::BytesPerSecond MallocExtension_Internal_GetBackgroundReleaseRate() { return Parameters::background_release_rate(); } void MallocExtension_Internal_SetBackgroundReleaseRate( tcmalloc::MallocExtension::BytesPerSecond rate) { Parameters::set_background_release_rate(rate); } void TCMalloc_Internal_SetBackgroundReleaseRate(size_t value) { Parameters::background_release_rate_.store( static_cast<tcmalloc::MallocExtension::BytesPerSecond>(value)); } uint64_t TCMalloc_Internal_GetHeapSizeHardLimit() { return Parameters::heap_size_hard_limit(); } bool TCMalloc_Internal_GetHPAASubrelease() { return Parameters::hpaa_subrelease(); } bool TCMalloc_Internal_GetShufflePerCpuCachesEnabled() { return Parameters::shuffle_per_cpu_caches(); } bool TCMalloc_Internal_GetPrioritizeSpansEnabled() { return Parameters::prioritize_spans(); } double TCMalloc_Internal_GetPeakSamplingHeapGrowthFraction() { return Parameters::peak_sampling_heap_growth_fraction(); } bool TCMalloc_Internal_GetPerCpuCachesEnabled() { return Parameters::per_cpu_caches(); } void TCMalloc_Internal_SetGuardedSamplingRate(int64_t v) { Parameters::guarded_sampling_rate_.store(v, std::memory_order_relaxed); } // update_lock guards changes via SetHeapSizeHardLimit. ABSL_CONST_INIT static absl::base_internal::SpinLock update_lock( absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY); void TCMalloc_Internal_SetHeapSizeHardLimit(uint64_t value) { // Ensure that page allocator is set up. Static::InitIfNecessary(); absl::base_internal::SpinLockHolder l(&update_lock); size_t limit = std::numeric_limits<size_t>::max(); bool active = false; if (value > 0) { limit = value; active = true; } bool currently_hard = Static::page_allocator().limit().second; if (active || currently_hard) { // Avoid resetting limit when current limit is soft. Static::page_allocator().set_limit(limit, active /* is_hard */); Log(kLog, __FILE__, __LINE__, "[tcmalloc] set page heap hard limit to", limit, "bytes"); } } void TCMalloc_Internal_SetHPAASubrelease(bool v) { tcmalloc::tcmalloc_internal::hpaa_subrelease_ptr()->store( v, std::memory_order_relaxed); } void TCMalloc_Internal_SetShufflePerCpuCachesEnabled(bool v) { Parameters::shuffle_per_cpu_caches_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetPrioritizeSpansEnabled(bool v) { Parameters::prioritize_spans_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetMaxPerCpuCacheSize(int32_t v) { Parameters::max_per_cpu_cache_size_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetMaxTotalThreadCacheBytes(int64_t v) { Parameters::max_total_thread_cache_bytes_.store(v, std::memory_order_relaxed); absl::base_internal::SpinLockHolder l( &tcmalloc::tcmalloc_internal::pageheap_lock); tcmalloc::tcmalloc_internal::ThreadCache::set_overall_thread_cache_size(v); } void TCMalloc_Internal_SetPeakSamplingHeapGrowthFraction(double v) { Parameters::peak_sampling_heap_growth_fraction_.store( v, std::memory_order_relaxed); } void TCMalloc_Internal_SetPerCpuCachesEnabled(bool v) { Parameters::per_cpu_caches_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetProfileSamplingRate(int64_t v) { Parameters::profile_sampling_rate_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_GetHugePageFillerSkipSubreleaseInterval( absl::Duration* v) { *v = Parameters::filler_skip_subrelease_interval(); } void TCMalloc_Internal_SetHugePageFillerSkipSubreleaseInterval( absl::Duration v) { tcmalloc::tcmalloc_internal::skip_subrelease_interval_ns().store( absl::ToInt64Nanoseconds(v), std::memory_order_relaxed); } void TCMalloc_Internal_SetLifetimeAllocatorOptions(absl::string_view s) { absl::base_internal::SpinLockHolder l( &tcmalloc::tcmalloc_internal::pageheap_lock); tcmalloc::tcmalloc_internal::HugePageAwareAllocator* hpaa = Static::page_allocator().default_hpaa(); if (hpaa != nullptr) { hpaa->lifetime_based_allocator().Enable( tcmalloc::tcmalloc_internal::LifetimePredictionOptions::FromFlag(s)); } } bool TCMalloc_Internal_GetPerCpuCachesDynamicSlabEnabled() { return Parameters::per_cpu_caches_dynamic_slab_enabled(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabEnabled(bool v) { Parameters::per_cpu_caches_dynamic_slab_enabled_.store( v, std::memory_order_relaxed); } double TCMalloc_Internal_GetPerCpuCachesDynamicSlabGrowThreshold() { return Parameters::per_cpu_caches_dynamic_slab_grow_threshold(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabGrowThreshold(double v) { Parameters::per_cpu_caches_dynamic_slab_grow_threshold_.store( v, std::memory_order_relaxed); } double TCMalloc_Internal_GetPerCpuCachesDynamicSlabShrinkThreshold() { return Parameters::per_cpu_caches_dynamic_slab_shrink_threshold(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabShrinkThreshold(double v) { Parameters::per_cpu_caches_dynamic_slab_shrink_threshold_.store( v, std::memory_order_relaxed); } } // extern "C" <commit_msg>Enable span prioritization by default in the central freelist.<commit_after>// Copyright 2019 The TCMalloc Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "tcmalloc/parameters.h" #include "absl/time/time.h" #include "tcmalloc/common.h" #include "tcmalloc/experiment.h" #include "tcmalloc/experiment_config.h" #include "tcmalloc/huge_page_aware_allocator.h" #include "tcmalloc/lifetime_based_allocator.h" #include "tcmalloc/malloc_extension.h" #include "tcmalloc/static_vars.h" #include "tcmalloc/thread_cache.h" GOOGLE_MALLOC_SECTION_BEGIN namespace tcmalloc { namespace tcmalloc_internal { // As decide_subrelease() is determined at runtime, we cannot require constant // initialization for the atomic. This avoids an initialization order fiasco. static std::atomic<bool>* hpaa_subrelease_ptr() { static std::atomic<bool> v(decide_subrelease()); return &v; } // As skip_subrelease_interval_ns() is determined at runtime, we cannot require // constant initialization for the atomic. This avoids an initialization order // fiasco. static std::atomic<int64_t>& skip_subrelease_interval_ns() { static std::atomic<int64_t> v(absl::ToInt64Nanoseconds( #if defined(TCMALLOC_SMALL_BUT_SLOW) absl::ZeroDuration() #else absl::Seconds(60) #endif )); return v; } uint64_t Parameters::heap_size_hard_limit() { size_t amount; bool is_hard; std::tie(amount, is_hard) = Static::page_allocator().limit(); if (!is_hard) { amount = 0; } return amount; } void Parameters::set_heap_size_hard_limit(uint64_t value) { TCMalloc_Internal_SetHeapSizeHardLimit(value); } bool Parameters::hpaa_subrelease() { return hpaa_subrelease_ptr()->load(std::memory_order_relaxed); } void Parameters::set_hpaa_subrelease(bool value) { TCMalloc_Internal_SetHPAASubrelease(value); } ABSL_CONST_INIT std::atomic<MallocExtension::BytesPerSecond> Parameters::background_release_rate_(MallocExtension::BytesPerSecond{ 0 }); ABSL_CONST_INIT std::atomic<int64_t> Parameters::guarded_sampling_rate_( 50 * kDefaultProfileSamplingRate); ABSL_CONST_INIT std::atomic<bool> Parameters::shuffle_per_cpu_caches_enabled_( true); ABSL_CONST_INIT std::atomic<int32_t> Parameters::max_per_cpu_cache_size_( kMaxCpuCacheSize); ABSL_CONST_INIT std::atomic<bool> Parameters::prioritize_spans_enabled_(true); ABSL_CONST_INIT std::atomic<int64_t> Parameters::max_total_thread_cache_bytes_( kDefaultOverallThreadCacheSize); ABSL_CONST_INIT std::atomic<double> Parameters::peak_sampling_heap_growth_fraction_(1.1); ABSL_CONST_INIT std::atomic<bool> Parameters::per_cpu_caches_enabled_( #if defined(TCMALLOC_DEPRECATED_PERTHREAD) false #else true #endif ); ABSL_CONST_INIT std::atomic<bool> Parameters::per_cpu_caches_dynamic_slab_enabled_(false); ABSL_CONST_INIT std::atomic<double> Parameters::per_cpu_caches_dynamic_slab_grow_threshold_(0.9); ABSL_CONST_INIT std::atomic<double> Parameters::per_cpu_caches_dynamic_slab_shrink_threshold_(0.5); ABSL_CONST_INIT std::atomic<int64_t> Parameters::profile_sampling_rate_( kDefaultProfileSamplingRate); absl::Duration Parameters::filler_skip_subrelease_interval() { return absl::Nanoseconds( skip_subrelease_interval_ns().load(std::memory_order_relaxed)); } bool Parameters::pass_span_object_count_to_pageheap() { static bool v([]() { return IsExperimentActive( Experiment::TEST_ONLY_TCMALLOC_PASS_SPAN_OBJECT_COUNT_TO_PAGEHEAP); }()); return v; } } // namespace tcmalloc_internal } // namespace tcmalloc GOOGLE_MALLOC_SECTION_END using tcmalloc::tcmalloc_internal::kLog; using tcmalloc::tcmalloc_internal::Log; using tcmalloc::tcmalloc_internal::Parameters; using tcmalloc::tcmalloc_internal::Static; extern "C" { int64_t MallocExtension_Internal_GetProfileSamplingRate() { return Parameters::profile_sampling_rate(); } void MallocExtension_Internal_SetProfileSamplingRate(int64_t value) { Parameters::set_profile_sampling_rate(value); } int64_t MallocExtension_Internal_GetGuardedSamplingRate() { return Parameters::guarded_sampling_rate(); } void MallocExtension_Internal_SetGuardedSamplingRate(int64_t value) { Parameters::set_guarded_sampling_rate(value); } int64_t MallocExtension_Internal_GetMaxTotalThreadCacheBytes() { return Parameters::max_total_thread_cache_bytes(); } void MallocExtension_Internal_SetMaxTotalThreadCacheBytes(int64_t value) { Parameters::set_max_total_thread_cache_bytes(value); } void MallocExtension_Internal_GetSkipSubreleaseInterval(absl::Duration* ret) { *ret = Parameters::filler_skip_subrelease_interval(); } void MallocExtension_Internal_SetSkipSubreleaseInterval(absl::Duration value) { Parameters::set_filler_skip_subrelease_interval(value); } tcmalloc::MallocExtension::BytesPerSecond MallocExtension_Internal_GetBackgroundReleaseRate() { return Parameters::background_release_rate(); } void MallocExtension_Internal_SetBackgroundReleaseRate( tcmalloc::MallocExtension::BytesPerSecond rate) { Parameters::set_background_release_rate(rate); } void TCMalloc_Internal_SetBackgroundReleaseRate(size_t value) { Parameters::background_release_rate_.store( static_cast<tcmalloc::MallocExtension::BytesPerSecond>(value)); } uint64_t TCMalloc_Internal_GetHeapSizeHardLimit() { return Parameters::heap_size_hard_limit(); } bool TCMalloc_Internal_GetHPAASubrelease() { return Parameters::hpaa_subrelease(); } bool TCMalloc_Internal_GetShufflePerCpuCachesEnabled() { return Parameters::shuffle_per_cpu_caches(); } bool TCMalloc_Internal_GetPrioritizeSpansEnabled() { return Parameters::prioritize_spans(); } double TCMalloc_Internal_GetPeakSamplingHeapGrowthFraction() { return Parameters::peak_sampling_heap_growth_fraction(); } bool TCMalloc_Internal_GetPerCpuCachesEnabled() { return Parameters::per_cpu_caches(); } void TCMalloc_Internal_SetGuardedSamplingRate(int64_t v) { Parameters::guarded_sampling_rate_.store(v, std::memory_order_relaxed); } // update_lock guards changes via SetHeapSizeHardLimit. ABSL_CONST_INIT static absl::base_internal::SpinLock update_lock( absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY); void TCMalloc_Internal_SetHeapSizeHardLimit(uint64_t value) { // Ensure that page allocator is set up. Static::InitIfNecessary(); absl::base_internal::SpinLockHolder l(&update_lock); size_t limit = std::numeric_limits<size_t>::max(); bool active = false; if (value > 0) { limit = value; active = true; } bool currently_hard = Static::page_allocator().limit().second; if (active || currently_hard) { // Avoid resetting limit when current limit is soft. Static::page_allocator().set_limit(limit, active /* is_hard */); Log(kLog, __FILE__, __LINE__, "[tcmalloc] set page heap hard limit to", limit, "bytes"); } } void TCMalloc_Internal_SetHPAASubrelease(bool v) { tcmalloc::tcmalloc_internal::hpaa_subrelease_ptr()->store( v, std::memory_order_relaxed); } void TCMalloc_Internal_SetShufflePerCpuCachesEnabled(bool v) { Parameters::shuffle_per_cpu_caches_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetPrioritizeSpansEnabled(bool v) { Parameters::prioritize_spans_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetMaxPerCpuCacheSize(int32_t v) { Parameters::max_per_cpu_cache_size_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetMaxTotalThreadCacheBytes(int64_t v) { Parameters::max_total_thread_cache_bytes_.store(v, std::memory_order_relaxed); absl::base_internal::SpinLockHolder l( &tcmalloc::tcmalloc_internal::pageheap_lock); tcmalloc::tcmalloc_internal::ThreadCache::set_overall_thread_cache_size(v); } void TCMalloc_Internal_SetPeakSamplingHeapGrowthFraction(double v) { Parameters::peak_sampling_heap_growth_fraction_.store( v, std::memory_order_relaxed); } void TCMalloc_Internal_SetPerCpuCachesEnabled(bool v) { Parameters::per_cpu_caches_enabled_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_SetProfileSamplingRate(int64_t v) { Parameters::profile_sampling_rate_.store(v, std::memory_order_relaxed); } void TCMalloc_Internal_GetHugePageFillerSkipSubreleaseInterval( absl::Duration* v) { *v = Parameters::filler_skip_subrelease_interval(); } void TCMalloc_Internal_SetHugePageFillerSkipSubreleaseInterval( absl::Duration v) { tcmalloc::tcmalloc_internal::skip_subrelease_interval_ns().store( absl::ToInt64Nanoseconds(v), std::memory_order_relaxed); } void TCMalloc_Internal_SetLifetimeAllocatorOptions(absl::string_view s) { absl::base_internal::SpinLockHolder l( &tcmalloc::tcmalloc_internal::pageheap_lock); tcmalloc::tcmalloc_internal::HugePageAwareAllocator* hpaa = Static::page_allocator().default_hpaa(); if (hpaa != nullptr) { hpaa->lifetime_based_allocator().Enable( tcmalloc::tcmalloc_internal::LifetimePredictionOptions::FromFlag(s)); } } bool TCMalloc_Internal_GetPerCpuCachesDynamicSlabEnabled() { return Parameters::per_cpu_caches_dynamic_slab_enabled(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabEnabled(bool v) { Parameters::per_cpu_caches_dynamic_slab_enabled_.store( v, std::memory_order_relaxed); } double TCMalloc_Internal_GetPerCpuCachesDynamicSlabGrowThreshold() { return Parameters::per_cpu_caches_dynamic_slab_grow_threshold(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabGrowThreshold(double v) { Parameters::per_cpu_caches_dynamic_slab_grow_threshold_.store( v, std::memory_order_relaxed); } double TCMalloc_Internal_GetPerCpuCachesDynamicSlabShrinkThreshold() { return Parameters::per_cpu_caches_dynamic_slab_shrink_threshold(); } void TCMalloc_Internal_SetPerCpuCachesDynamicSlabShrinkThreshold(double v) { Parameters::per_cpu_caches_dynamic_slab_shrink_threshold_.store( v, std::memory_order_relaxed); } } // extern "C" <|endoftext|>
<commit_before>// ComplexCi.cpp : ̨Ӧóڵ㡣 // //#include "stdafx.h" #include <iostream> #include <vector> #include <set> #include <fstream> #include <string> #include <map> #include <unordered_map> #include <unordered_set> #include <sstream> #include <iterator> #include <queue> #include <algorithm> #include <chrono> #include <bitset> using namespace std; using namespace std::chrono; template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } /*void getNeighbourFrontierAndScope(const vector<vector<int> > &adjListGraph, int scope, int currentNode, unordered_set<int> &currentSet, unordered_set<int>& alreadyAccess) { //alreadyAccess.reserve(100000); currentSet.insert(currentNode); alreadyAccess.insert(currentNode); for (int i = 0; i < scope; i++) { unordered_set<int> nextSet; //nextSet.reserve(30000); for (const auto& node : currentSet) { const vector<int>& neighbourNodeList = adjListGraph[node]; for (const auto& eachNeighbour : neighbourNodeList) { if (alreadyAccess.find(eachNeighbour) == alreadyAccess.end()) { nextSet.insert(eachNeighbour); alreadyAccess.insert(eachNeighbour); } } } currentSet = move(nextSet); } }*/ bitset<2000000> alreadyAccessBool; void getNeighbourFrontierAndScope(const vector<vector<int> > &adjListGraph, int scope, int currentNode, vector<int> &currentSet, vector<int>& alreadyAccess) { //alreadyAccessBool.reset(); currentSet.push_back(currentNode); alreadyAccess.push_back(currentNode); alreadyAccessBool[currentNode] = 1; for (int i = 0; i < scope; i++) { vector<int> nextSet; for (const auto& node : currentSet) { const vector<int>& neighbourNodeList = adjListGraph[node]; for (const auto& eachNeighbour : neighbourNodeList) { if (alreadyAccessBool[eachNeighbour] == 0) { nextSet.push_back(eachNeighbour); alreadyAccess.push_back(eachNeighbour); alreadyAccessBool[eachNeighbour] = 1; } } } currentSet = move(nextSet); } for (int node: alreadyAccess) { alreadyAccessBool.reset(node); } } long long basicCi(const vector<vector<int> > &adjListGraph, int ballRadius, int currentNode) { if (adjListGraph[currentNode].size() == 0) { return -1; } vector<int> currentFrontier; vector<int> dummyValue; getNeighbourFrontierAndScope(adjListGraph, ballRadius, currentNode, currentFrontier, dummyValue); long long ci = 0; for (auto node : currentFrontier) { ci += (adjListGraph[node].size() - 1); } ci *= (adjListGraph[currentNode].size() - 1); /* if (currentNode % 500 == 0) { cout << currentNode << " currentFrontier size :" << currentFrontier.size() << endl; } */ /* if (currentNode == 1715132 && (ci == 0 || ci == 2)) { cout << "currentNode: " << currentNode << " adjListGraph[currentNode].size(): " << adjListGraph[currentNode].size() << "/ "; for (auto node : adjListGraph[currentNode]) { cout << node << " " ; } cout << endl; cout << "ci: " << ci << endl; cout << "currentFrontier: " << endl; for (auto node : currentFrontier) { cout << node << " " << adjListGraph[node].size() << endl; } cout << "dummyValue: " << endl; for (auto node : dummyValue) { cout << node << " node1: "; for (auto node1 : adjListGraph[node]) { cout << node1 << " "; } cout << endl; } cout << endl; } */ return ci; } void deleteNode(vector<vector<int> > &adjListGraph, int node) { /* if (adjListGraph[node].size() == 0) { return; } // not must here */ for (auto neighbour : adjListGraph[node]) { adjListGraph[neighbour].erase(remove(adjListGraph[neighbour].begin(), adjListGraph[neighbour].end(), node), adjListGraph[neighbour].end()); } adjListGraph[node].clear(); } int main(int argc, char* argv[]) { unsigned int ballRadius = 1; unsigned int updateBatch = 1; unsigned int outputNumBatch = 1; string path = ""; string output = ""; if (argc > 4) { path = argv[1]; output = path + "_out"; ballRadius = stoi(argv[2]); updateBatch = stoi(argv[3]); outputNumBatch = stoi(argv[4]); } else { cout << "at least 3 parameters for csv path" << endl; cout << "e.g. 'C:/Users/zhfkt/Documents/Visual Studio 2013/Projects/ComplexCi/Release/karate.txt' 2 500 500" << endl; return 0; } high_resolution_clock::time_point t1 = high_resolution_clock::now(); string modelID = ""; { vector<string> fileName = split(path, '/'); modelID = split(fileName[fileName.size() - 1], '.')[0]; } std::cout << "path: " << path << endl; std::cout << "output: " << output << endl; std::cout << "modelID: " << modelID << endl; std::cout << "ballRadius: " << ballRadius << endl; std::cout << "updateBatch: " << updateBatch << endl; std::cout << "outputNumBatch: " << outputNumBatch << endl; std::cout << "First Read Start" << endl; unordered_set<int> allVex; string eachLine; ifstream is; is.open(path); while (is >> eachLine) { vector<string> csvEachLine = split(eachLine, ','); allVex.insert(stoi(csvEachLine[0])); allVex.insert(stoi(csvEachLine[1])); } is.close(); int totalSize = allVex.size(); std::cout << "First Read End/Second Read Start" << endl; vector<vector<int> > adjListGraph(totalSize); is.open(path); while (is >> eachLine) { vector<string> csvEachLine = split(eachLine, ','); adjListGraph[stoi(csvEachLine[0])].push_back(stoi(csvEachLine[1])); adjListGraph[stoi(csvEachLine[1])].push_back(stoi(csvEachLine[0])); } std::cout << "Second Read End" << endl; //-------------- set<pair<long long, int> > allPQ; //ci/currentNode --- long is 32 bit on the win and long long is 64 bit / and long long can be multiple vector<long long> revereseLoopUpAllPQ(totalSize); cout << "modelID: " << modelID << " First Cal CI" << endl; for (int i = 0; i < adjListGraph.size(); i++) { int currentNode = i; // core_ci long long ci = basicCi(adjListGraph, ballRadius, currentNode); allPQ.insert(make_pair(ci, currentNode)); revereseLoopUpAllPQ[currentNode] = ci; } vector<int> finalOutput; int loopCount = 0; while (true) { cout << "modelID: " << modelID << " loopCount: " << loopCount << " totalSize: " << totalSize << " maxCi: " << allPQ.rbegin()->first << " node: " << allPQ.rbegin()->second << endl; loopCount += updateBatch; vector<int> batchList; unsigned int batchLimiti = 0; pair<long long, int> debugPreviousMax = *(allPQ.rbegin()); for (auto rit = allPQ.rbegin(); batchLimiti < updateBatch && (rit != allPQ.rend()); rit++, batchLimiti++) { batchList.push_back(rit->second); finalOutput.push_back(rit->second); allVex.erase(rit->second); //remove key if (rit->first <= 0) { // ci algorithm ends goto CIEND; } } /* if (loopCount == 600000) { cout << " revereseLoopUpAllPQ[1715132] " << revereseLoopUpAllPQ[1715132] << endl; } */ //cout << "monitor 1" << endl; //int debugCount = 0; unordered_set<int> candidateUpdateNodes; for (int i : batchList) { vector<int> allScopeInBallRadiusPlusOne; vector<int> dummyValue; getNeighbourFrontierAndScope(adjListGraph, ballRadius + 1, i, dummyValue, allScopeInBallRadiusPlusOne); candidateUpdateNodes.insert(allScopeInBallRadiusPlusOne.begin(), allScopeInBallRadiusPlusOne.end()); //cout << "monitor 1_2: " << debugCount++ << " " << batchList.size() << " " << candidateUpdateNodes.size() << endl; } //cout << "monitor 2" << endl; for (int i : batchList) { deleteNode(adjListGraph, i); //candidateUpdateNodesWithCi.insert(make_pair(i, -1));// no need to because self will be included in the candidateUpdateNodes and updated in the below } //cout << "monitor 3" << endl; //debugCount = 0; for (int i : candidateUpdateNodes) { long long updatedCi = basicCi(adjListGraph, ballRadius, i); long long olderCi = revereseLoopUpAllPQ[i]; allPQ.erase(make_pair(olderCi, i)); allPQ.insert(make_pair(updatedCi, i)); revereseLoopUpAllPQ[i] = updatedCi; //cout << "monitor 3_4: " << debugCount++ << " " << candidateUpdateNodes.size() << endl; } //cout << "monitor 4" << endl; /*if ((debugPreviousMax.first) < (allPQ.rbegin()->first)) { cout << "monitor 5: " << debugPreviousMax.first << " " << allPQ.rbegin()->first << endl;; } */ } CIEND: //add left random cout << "Before Random adding the left CI equals zero: " << finalOutput.size() << endl; for (auto leftVex : allVex) { finalOutput.push_back(leftVex); } cout << "After Random adding the left CI equals zero: " << finalOutput.size() << endl; while (true) { if (finalOutput.size() % outputNumBatch == 0) { break; } else { finalOutput.push_back(-1); } } //-------------- std::cout << "Outputing Start.." << endl; ofstream os(output); string output500 = ""; for (unsigned int i = 0; i < finalOutput.size(); i++) { if (i % outputNumBatch == 0) { output500 = modelID; } if (finalOutput[i] != -1) { output500 += (',' + std::to_string(finalOutput[i])); } else { output500 += ','; } if (i % outputNumBatch == (outputNumBatch - 1) || i == (finalOutput.size() - 1)) { os << output500 << endl; //std::cout << "output500: " << output500 << endl; output500.clear(); } } os.close(); std::cout << "Outputing End.." << endl; high_resolution_clock::time_point t2 = high_resolution_clock::now(); auto duration = duration_cast<seconds>(t2 - t1).count(); cout << "duration: " << duration << "s" << endl; system("pause"); return 0; } <commit_msg>Rewrite the BFS process to boost<commit_after>// ComplexCi.cpp : ̨Ӧóڵ㡣 // //#include "stdafx.h" #include <iostream> #include <vector> #include <set> #include <fstream> #include <string> #include <map> #include <unordered_map> #include <unordered_set> #include <sstream> #include <iterator> #include <queue> #include <algorithm> #include <chrono> #include <bitset> using namespace std; using namespace std::chrono; template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } /*void getNeighbourFrontierAndScope(const vector<vector<int> > &adjListGraph, int scope, int currentNode, unordered_set<int> &currentSet, unordered_set<int>& alreadyAccess) { //alreadyAccess.reserve(100000); currentSet.insert(currentNode); alreadyAccess.insert(currentNode); for (int i = 0; i < scope; i++) { unordered_set<int> nextSet; //nextSet.reserve(30000); for (const auto& node : currentSet) { const vector<int>& neighbourNodeList = adjListGraph[node]; for (const auto& eachNeighbour : neighbourNodeList) { if (alreadyAccess.find(eachNeighbour) == alreadyAccess.end()) { nextSet.insert(eachNeighbour); alreadyAccess.insert(eachNeighbour); } } } currentSet = move(nextSet); } }*/ bitset<2000000> alreadyAccessBool; vector<int> bfsQueue; int startIt = 0; int endIt = 1; void getNeighbourFrontierAndScope(const vector<vector<int> > &adjListGraph, int scope, int currentNode) { startIt = 0; endIt = 1; //startIt and endIt will never execeed bfsQueue.size(); //alreadyAccess is between 0 and endIt //fontier is between startIt and endIt bfsQueue[0] = currentNode; alreadyAccessBool[currentNode] = 1; for (int i = 0; i < scope; i++) { int lastEndIt = endIt; while (startIt != lastEndIt) { const vector<int>& neighbourNodeList = adjListGraph[bfsQueue[startIt++]]; for (const auto& eachNeighbour : neighbourNodeList) { if (alreadyAccessBool[eachNeighbour] == 0) { bfsQueue[endIt++] = eachNeighbour; alreadyAccessBool[eachNeighbour] = 1; } } } } for (int i = 0; i < endIt; i++) { alreadyAccessBool.reset(bfsQueue[i]); } } long long basicCi(const vector<vector<int> > &adjListGraph, int ballRadius, int currentNode) { if (adjListGraph[currentNode].size() == 0) { return -1; } getNeighbourFrontierAndScope(adjListGraph, ballRadius, currentNode); long long ci = 0; for (int i = startIt; i < endIt; i++) { ci += (adjListGraph[bfsQueue[i]].size() - 1); } ci *= (adjListGraph[currentNode].size() - 1); /* if (currentNode % 500 == 0) { cout << currentNode << " currentFrontier size :" << currentFrontier.size() << endl; } */ /* if (currentNode == 1715132 && (ci == 0 || ci == 2)) { cout << "currentNode: " << currentNode << " adjListGraph[currentNode].size(): " << adjListGraph[currentNode].size() << "/ "; for (auto node : adjListGraph[currentNode]) { cout << node << " " ; } cout << endl; cout << "ci: " << ci << endl; cout << "currentFrontier: " << endl; for (auto node : currentFrontier) { cout << node << " " << adjListGraph[node].size() << endl; } cout << "dummyValue: " << endl; for (auto node : dummyValue) { cout << node << " node1: "; for (auto node1 : adjListGraph[node]) { cout << node1 << " "; } cout << endl; } cout << endl; } */ return ci; } void deleteNode(vector<vector<int> > &adjListGraph, int node) { /* if (adjListGraph[node].size() == 0) { return; } // not must here */ for (auto neighbour : adjListGraph[node]) { adjListGraph[neighbour].erase(remove(adjListGraph[neighbour].begin(), adjListGraph[neighbour].end(), node), adjListGraph[neighbour].end()); } adjListGraph[node].clear(); } int main(int argc, char* argv[]) { unsigned int ballRadius = 1; unsigned int updateBatch = 1; unsigned int outputNumBatch = 1; string path = ""; string output = ""; if (argc > 4) { path = argv[1]; output = path + "_out"; ballRadius = stoi(argv[2]); updateBatch = stoi(argv[3]); outputNumBatch = stoi(argv[4]); } else { cout << "at least 3 parameters for csv path" << endl; cout << "e.g. 'C:/Users/zhfkt/Documents/Visual Studio 2013/Projects/ComplexCi/Release/karate.txt' 2 500 500" << endl; return 0; } high_resolution_clock::time_point t1 = high_resolution_clock::now(); string modelID = ""; { vector<string> fileName = split(path, '/'); modelID = split(fileName[fileName.size() - 1], '.')[0]; } std::cout << "path: " << path << endl; std::cout << "output: " << output << endl; std::cout << "modelID: " << modelID << endl; std::cout << "ballRadius: " << ballRadius << endl; std::cout << "updateBatch: " << updateBatch << endl; std::cout << "outputNumBatch: " << outputNumBatch << endl; std::cout << "First Read Start" << endl; unordered_set<int> allVex; string eachLine; ifstream is; is.open(path); while (is >> eachLine) { vector<string> csvEachLine = split(eachLine, ','); allVex.insert(stoi(csvEachLine[0])); allVex.insert(stoi(csvEachLine[1])); } is.close(); int totalSize = allVex.size(); std::cout << "First Read End/Second Read Start" << endl; vector<vector<int> > adjListGraph(totalSize); is.open(path); while (is >> eachLine) { vector<string> csvEachLine = split(eachLine, ','); adjListGraph[stoi(csvEachLine[0])].push_back(stoi(csvEachLine[1])); adjListGraph[stoi(csvEachLine[1])].push_back(stoi(csvEachLine[0])); } std::cout << "Second Read End" << endl; bfsQueue.resize(totalSize, -1); //-------------- set<pair<long long, int> > allPQ; //ci/currentNode --- long is 32 bit on the win and long long is 64 bit / and long long can be multiple vector<long long> revereseLoopUpAllPQ(totalSize); cout << "modelID: " << modelID << " First Cal CI" << endl; for (int i = 0; i < adjListGraph.size(); i++) { int currentNode = i; // core_ci long long ci = basicCi(adjListGraph, ballRadius, currentNode); allPQ.insert(make_pair(ci, currentNode)); revereseLoopUpAllPQ[currentNode] = ci; } vector<int> finalOutput; int loopCount = 0; while (true) { cout << "modelID: " << modelID << " loopCount: " << loopCount << " totalSize: " << totalSize << " maxCi: " << allPQ.rbegin()->first << " node: " << allPQ.rbegin()->second << endl; loopCount += updateBatch; vector<int> batchList; unsigned int batchLimiti = 0; pair<long long, int> debugPreviousMax = *(allPQ.rbegin()); for (auto rit = allPQ.rbegin(); batchLimiti < updateBatch && (rit != allPQ.rend()); rit++, batchLimiti++) { batchList.push_back(rit->second); finalOutput.push_back(rit->second); allVex.erase(rit->second); //remove key if (rit->first <= 0) { // ci algorithm ends goto CIEND; } } /* if (loopCount == 600000) { cout << " revereseLoopUpAllPQ[1715132] " << revereseLoopUpAllPQ[1715132] << endl; } */ //cout << "monitor 1" << endl; //int debugCount = 0; unordered_set<int> candidateUpdateNodes; for (int i : batchList) { getNeighbourFrontierAndScope(adjListGraph, ballRadius + 1, i); candidateUpdateNodes.insert(bfsQueue.begin(), bfsQueue.begin() + endIt); //cout << "monitor 1_2: " << debugCount++ << " " << batchList.size() << " " << candidateUpdateNodes.size() << endl; } //cout << "monitor 2" << endl; for (int i : batchList) { deleteNode(adjListGraph, i); //candidateUpdateNodesWithCi.insert(make_pair(i, -1));// no need to because self will be included in the candidateUpdateNodes and updated in the below } //cout << "monitor 3" << endl; //debugCount = 0; for (int i : candidateUpdateNodes) { long long updatedCi = basicCi(adjListGraph, ballRadius, i); long long olderCi = revereseLoopUpAllPQ[i]; allPQ.erase(make_pair(olderCi, i)); allPQ.insert(make_pair(updatedCi, i)); revereseLoopUpAllPQ[i] = updatedCi; //cout << "monitor 3_4: " << debugCount++ << " " << candidateUpdateNodes.size() << endl; } //cout << "monitor 4" << endl; /*if ((debugPreviousMax.first) < (allPQ.rbegin()->first)) { cout << "monitor 5: " << debugPreviousMax.first << " " << allPQ.rbegin()->first << endl;; } */ } CIEND: //add left random cout << "Before Random adding the left CI equals zero: " << finalOutput.size() << endl; for (auto leftVex : allVex) { finalOutput.push_back(leftVex); } cout << "After Random adding the left CI equals zero: " << finalOutput.size() << endl; while (true) { if (finalOutput.size() % outputNumBatch == 0) { break; } else { finalOutput.push_back(-1); } } //-------------- std::cout << "Outputing Start.." << endl; ofstream os(output); string output500 = ""; for (unsigned int i = 0; i < finalOutput.size(); i++) { if (i % outputNumBatch == 0) { output500 = modelID; } if (finalOutput[i] != -1) { output500 += (',' + std::to_string(finalOutput[i])); } else { output500 += ','; } if (i % outputNumBatch == (outputNumBatch - 1) || i == (finalOutput.size() - 1)) { os << output500 << endl; //std::cout << "output500: " << output500 << endl; output500.clear(); } } os.close(); std::cout << "Outputing End.." << endl; high_resolution_clock::time_point t2 = high_resolution_clock::now(); auto duration = duration_cast<seconds>(t2 - t1).count(); cout << "duration: " << duration << "s" << endl; system("pause"); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkAbstractFactory_tpp #define __ctkAbstractFactory_tpp // QT includes #include <QDebug> // CTK includes #include "ctkAbstractFactory.h" //---------------------------------------------------------------------------- // ctkAbstractFactoryItem methods //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactoryItem<BaseClassType>::ctkAbstractFactoryItem() :Instance() { this->Verbose = false; } //---------------------------------------------------------------------------- template<typename BaseClassType> QString ctkAbstractFactoryItem<BaseClassType>::loadErrorString()const { return QString(); } //---------------------------------------------------------------------------- template<typename BaseClassType> BaseClassType* ctkAbstractFactoryItem<BaseClassType>::instantiate() { if (this->Instance) { return this->Instance; } this->Instance = this->instanciator(); return this->Instance; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactoryItem<BaseClassType>::instantiated()const { return (this->Instance != 0); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactoryItem<BaseClassType>::uninstantiate() { if (!this->Instance) { return; } delete this->Instance; // Make sure the pointer is set to 0. Doing so, Will prevent attempt to // delete unextising object if uninstantiate() methods is called multiple times. this->Instance = 0; } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactoryItem<BaseClassType>::setVerbose(bool value) { this->Verbose = value; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactoryItem<BaseClassType>::verbose()const { return this->Verbose; } //---------------------------------------------------------------------------- // ctkAbstractFactory methods //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactory<BaseClassType>::ctkAbstractFactory() { this->Verbose = false; } //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactory<BaseClassType>::~ctkAbstractFactory() { } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::printAdditionalInfo() { qDebug() << "ctkAbstractFactory<BaseClassType> (" << this << ")"; // TODO } //---------------------------------------------------------------------------- template<typename BaseClassType> BaseClassType* ctkAbstractFactory<BaseClassType>::instantiate(const QString& itemKey) { ctkAbstractFactoryItem<BaseClassType>* _item = this->item(itemKey); return (_item ? _item->instantiate() : 0); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::uninstantiate(const QString& itemKey) { ctkAbstractFactoryItem<BaseClassType> * _item = this->item(itemKey); if (!_item) { return; } _item->uninstantiate(); } //---------------------------------------------------------------------------- template<typename BaseClassType> QStringList ctkAbstractFactory<BaseClassType>::keys() const { // Since by construction, we checked if a name was already in the QHash, // there is no need to call 'uniqueKeys' return this->RegisteredItemMap.keys(); } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactory<BaseClassType>::registerItem(const QString& key, const QSharedPointer<ctkAbstractFactoryItem<BaseClassType> > & _item) { // Sanity checks if (!_item || key.isEmpty() || this->item(key)) { return false; } // Attempt to load it if (!_item->load()) { QString errorStr; if (!_item->loadErrorString().isEmpty()) { errorStr = " - " + _item->loadErrorString(); } if (this->verbose()) { qCritical() << "Failed to load object:" << key << errorStr ; } return false; } // Store its reference using a QSharedPointer this->RegisteredItemMap[key] = _item; return true; } //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactoryItem<BaseClassType> * ctkAbstractFactory<BaseClassType>::item(const QString& itemKey)const { ConstIterator iter = this->RegisteredItemMap.find(itemKey); if ( iter == this->RegisteredItemMap.constEnd()) { return 0; } return iter.value().data(); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::setVerbose(bool value) { this->Verbose = value; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactory<BaseClassType>::verbose()const { return this->Verbose; } #endif <commit_msg>ENH: Add verbose to ctkAbstractFactory::registerItem<commit_after>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkAbstractFactory_tpp #define __ctkAbstractFactory_tpp // QT includes #include <QDebug> // CTK includes #include "ctkAbstractFactory.h" //---------------------------------------------------------------------------- // ctkAbstractFactoryItem methods //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactoryItem<BaseClassType>::ctkAbstractFactoryItem() :Instance() { this->Verbose = false; } //---------------------------------------------------------------------------- template<typename BaseClassType> QString ctkAbstractFactoryItem<BaseClassType>::loadErrorString()const { return QString(); } //---------------------------------------------------------------------------- template<typename BaseClassType> BaseClassType* ctkAbstractFactoryItem<BaseClassType>::instantiate() { if (this->Instance) { return this->Instance; } this->Instance = this->instanciator(); return this->Instance; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactoryItem<BaseClassType>::instantiated()const { return (this->Instance != 0); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactoryItem<BaseClassType>::uninstantiate() { if (!this->Instance) { return; } delete this->Instance; // Make sure the pointer is set to 0. Doing so, Will prevent attempt to // delete unextising object if uninstantiate() methods is called multiple times. this->Instance = 0; } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactoryItem<BaseClassType>::setVerbose(bool value) { this->Verbose = value; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactoryItem<BaseClassType>::verbose()const { return this->Verbose; } //---------------------------------------------------------------------------- // ctkAbstractFactory methods //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactory<BaseClassType>::ctkAbstractFactory() { this->Verbose = false; } //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactory<BaseClassType>::~ctkAbstractFactory() { } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::printAdditionalInfo() { qDebug() << "ctkAbstractFactory<BaseClassType> (" << this << ")"; // TODO } //---------------------------------------------------------------------------- template<typename BaseClassType> BaseClassType* ctkAbstractFactory<BaseClassType>::instantiate(const QString& itemKey) { ctkAbstractFactoryItem<BaseClassType>* _item = this->item(itemKey); return (_item ? _item->instantiate() : 0); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::uninstantiate(const QString& itemKey) { ctkAbstractFactoryItem<BaseClassType> * _item = this->item(itemKey); if (!_item) { return; } _item->uninstantiate(); } //---------------------------------------------------------------------------- template<typename BaseClassType> QStringList ctkAbstractFactory<BaseClassType>::keys() const { // Since by construction, we checked if a name was already in the QHash, // there is no need to call 'uniqueKeys' return this->RegisteredItemMap.keys(); } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactory<BaseClassType>::registerItem(const QString& key, const QSharedPointer<ctkAbstractFactoryItem<BaseClassType> > & _item) { // Sanity checks if (!_item || key.isEmpty() || this->item(key)) { if (this->verbose()) { qDebug() << __FUNCTION__ << "key is empty or already exists:" << key << "; item: " << _item; } return false; } // Attempt to load it if (!_item->load()) { QString errorStr; if (!_item->loadErrorString().isEmpty()) { errorStr = " - " + _item->loadErrorString(); } if (this->verbose()) { qCritical() << "Failed to load object:" << key << errorStr ; } return false; } // Store its reference using a QSharedPointer this->RegisteredItemMap[key] = _item; return true; } //---------------------------------------------------------------------------- template<typename BaseClassType> ctkAbstractFactoryItem<BaseClassType> * ctkAbstractFactory<BaseClassType>::item(const QString& itemKey)const { ConstIterator iter = this->RegisteredItemMap.find(itemKey); if ( iter == this->RegisteredItemMap.constEnd()) { return 0; } return iter.value().data(); } //---------------------------------------------------------------------------- template<typename BaseClassType> void ctkAbstractFactory<BaseClassType>::setVerbose(bool value) { this->Verbose = value; } //---------------------------------------------------------------------------- template<typename BaseClassType> bool ctkAbstractFactory<BaseClassType>::verbose()const { return this->Verbose; } #endif <|endoftext|>
<commit_before>// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2002, 2003 // // Test STL montageImages function // #include <Magick++.h> #include <string> #include <iostream> #include <list> #include <vector> using namespace std; using namespace Magick; int main( int /*argc*/, char ** /*argv*/) { // Initialize ImageMagick install location for Windows // InitializeMagick(*argv); InitializeMagick(""); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); // // Test montageImages // list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); vector<Image> montage; MontageFramed montageOpts; // Default montage montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); { Geometry targetGeometry(128, 126 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")" << endl; } } if ( montage[0].columns() != 768 || montage[0].rows() != 504 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 768x504)" << endl; } // Montage with options set montage.clear(); montageOpts.borderColor( "green" ); montageOpts.borderWidth( 1 ); montageOpts.compose( OverCompositeOp ); montageOpts.fileName( "Montage" ); montageOpts.frameGeometry( "6x6+3+3" ); montageOpts.geometry("50x50+2+2>"); montageOpts.gravity( CenterGravity ); montageOpts.strokeColor( "yellow" ); montageOpts.shadow( true ); montageOpts.texture( "granite:" ); montageOpts.tile("2x1"); montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); if ( montage.size() != 3 ) { ++failures; cout << "Line: " << __LINE__ << " Montage images failed, number of montage frames is " << montage.size() << " rather than 3 as expected." << endl; } { Geometry targetGeometry( 66, 70 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")." << endl; } } if ( montage[0].columns() != 136 || montage[0].rows() != 70 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 136x70)" << endl; } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; } <commit_msg>Build fix.<commit_after>// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2002, 2003 // // Test STL montageImages function // #include <Magick++.h> #include <string> #include <iostream> #include <list> #include <vector> using namespace std; using namespace Magick; int main( int /*argc*/, char ** /*argv*/) { // Initialize ImageMagick install location for Windows // InitializeMagick(*argv); InitializeMagick(""); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); // // Test montageImages // list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); vector<Image> montage; MontageFramed montageOpts; // Default montage montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); { Geometry targetGeometry(128, 126 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")" << endl; } } if ( montage[0].columns() != 768 || montage[0].rows() != 504 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 768x504)" << endl; } // Montage with options set montage.clear(); montageOpts.borderColor( "green" ); montageOpts.borderWidth( 1 ); montageOpts.fileName( "Montage" ); montageOpts.frameGeometry( "6x6+3+3" ); montageOpts.geometry("50x50+2+2>"); montageOpts.gravity( CenterGravity ); montageOpts.strokeColor( "yellow" ); montageOpts.shadow( true ); montageOpts.texture( "granite:" ); montageOpts.tile("2x1"); montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); if ( montage.size() != 3 ) { ++failures; cout << "Line: " << __LINE__ << " Montage images failed, number of montage frames is " << montage.size() << " rather than 3 as expected." << endl; } { Geometry targetGeometry( 66, 70 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")." << endl; } } if ( montage[0].columns() != 136 || montage[0].rows() != 70 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 136x70)" << endl; } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; } <|endoftext|>
<commit_before>/** * Copyright (C) 2016 3D Repo Ltd * * 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/>. */ /** * Allows Export functionality from 3D Repo World to asset bundle */ #include "repo_model_export_asset.h" #include "../../../core/model/bson/repo_bson_factory.h" #include "../../../lib/repo_log.h" using namespace repo::manipulator::modelconvertor; const static size_t SRC_MAX_VERTEX_LIMIT = 65535; //Labels for multipart JSON descriptor files const static std::string MP_LABEL_APPEARANCE = "appearance"; const static std::string MP_LABEL_MAT_DIFFUSE = "diffuseColor"; const static std::string MP_LABEL_MAT_EMISSIVE = "emissiveColor"; const static std::string MP_LABEL_MATERIAL = "material"; const static std::string MP_LABEL_MAPPING = "mapping"; const static std::string MP_LABEL_MAT_SHININESS = "shininess"; const static std::string MP_LABEL_MAT_SPECULAR = "specularColor"; const static std::string MP_LABEL_MAT_TRANSPARENCY = "transparency"; const static std::string MP_LABEL_MAX = "max"; const static std::string MP_LABEL_MAX_GEO_COUNT = "maxGeoCount"; const static std::string MP_LABEL_MIN = "min"; const static std::string MP_LABEL_NAME = "name"; const static std::string MP_LABEL_NUM_IDs = "numberOfIDs"; const static std::string MP_LABEL_USAGE = "usage"; const static std::string MP_LABEL_ASSETS = "assets"; const static std::string MP_LABEL_SHARED = "sharedID"; const static std::string MP_LABEL_JSONS = "jsonFiles"; const static std::string MP_LABEL_OFFSET = "offset"; const static std::string MP_LABEL_DATABASE = "database"; const static std::string MP_LABEL_PROJECT = "project"; AssetModelExport::AssetModelExport( const repo::core::model::RepoScene *scene ) : WebModelExport(scene) { //Considering all newly imported models should have a stash graph, we only need to support stash graph? if (convertSuccess) { if (gType == repo::core::model::RepoScene::GraphType::OPTIMIZED) { convertSuccess = generateTreeRepresentation(); } else if (!(convertSuccess = !scene->getAllMeshes(repo::core::model::RepoScene::GraphType::DEFAULT).size())) { repoError << "Scene has no optimised graph and it is not a federation graph. SRC Exporter relies on this."; } } else { repoError << "Unable to export to SRC : Empty scene graph!"; } } AssetModelExport::~AssetModelExport() { } repo_web_buffers_t AssetModelExport::getAllFilesExportedAsBuffer() const { return{ std::unordered_map<std::string, std::vector<uint8_t>>(), getJSONFilesAsBuffer() }; } bool AssetModelExport::generateJSONMapping( const repo::core::model::MeshNode *mesh, const repo::core::model::RepoScene *scene, const std::unordered_map<repo::lib::RepoUUID, std::vector<uint32_t>, repo::lib::RepoUUIDHasher> &splitMapping) { bool success; if (success = mesh) { repo::lib::PropertyTree jsonTree; std::vector<repo_mesh_mapping_t> mappings = mesh->getMeshMapping(); std::sort(mappings.begin(), mappings.end(), [](repo_mesh_mapping_t const& a, repo_mesh_mapping_t const& b) { return a.vertFrom < b.vertFrom; }); size_t mappingLength = mappings.size(); jsonTree.addToTree(MP_LABEL_NUM_IDs, mappingLength); jsonTree.addToTree(MP_LABEL_MAX_GEO_COUNT, mappingLength); std::vector<repo::lib::PropertyTree> mappingTrees; std::string meshUID = mesh->getUniqueID().toString(); //Could get the mesh split function to pass a mapping out so we don't do this again. for (size_t i = 0; i < mappingLength; ++i) { auto mapIt = splitMapping.find(mappings[i].mesh_id); if (mapIt != splitMapping.end()) { for (const uint32_t &subMeshID : mapIt->second) { repo::lib::PropertyTree mappingTree; mappingTree.addToTree(MP_LABEL_NAME, mappings[i].mesh_id.toString()); repo::lib::RepoUUID id(mappings[i].mesh_id.toString()); auto mesh = scene->getNodeByUniqueID(repo::core::model::RepoScene::GraphType::DEFAULT, id); if (mesh) mappingTree.addToTree(MP_LABEL_SHARED, mesh->getSharedID().toString()); mappingTree.addToTree(MP_LABEL_MIN, mappings[i].min); mappingTree.addToTree(MP_LABEL_MAX, mappings[i].max); std::vector<std::string> usageArr = { meshUID + "_" + std::to_string(subMeshID) }; mappingTree.addToTree(MP_LABEL_USAGE, usageArr); mappingTrees.push_back(mappingTree); } } else { repoError << "Failed to find split mapping for id: " << mappings[i].mesh_id; } } jsonTree.addArrayObjects(MP_LABEL_MAPPING, mappingTrees); std::string jsonFileName = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/" + mesh->getUniqueID().toString() + "_unity.json.mpc"; jsonTrees[jsonFileName] = jsonTree; } else { repoError << "Unable to generate JSON file mapping : null pointer to mesh!"; } return success; } bool AssetModelExport::generateTreeRepresentation( ) { bool success; if (success = scene->hasRoot(gType)) { auto meshes = scene->getAllMeshes(gType); std::vector<std::string> assetFiles, jsons; for (const repo::core::model::RepoNode* node : meshes) { auto mesh = dynamic_cast<const repo::core::model::MeshNode*>(node); if (!mesh) { repoError << "Failed to cast a Repo Node of type mesh into a MeshNode(" << node->getUniqueID() << "). Skipping..."; } std::string textureID = scene->getTextureIDForMesh(gType, mesh->getSharedID()); repo::manipulator::modelutility::MeshMapReorganiser *reSplitter = new repo::manipulator::modelutility::MeshMapReorganiser(mesh, SRC_MAX_VERTEX_LIMIT); reorganisedMeshes.push_back(std::make_shared<repo::core::model::MeshNode>(reSplitter->getRemappedMesh())); if (success = !(reorganisedMeshes.back()->isEmpty())) { serialisedFaceBuf.push_back(reSplitter->getSerialisedFaces()); idMapBuf.push_back(reSplitter->getIDMapArrays()); meshMappings.push_back(reSplitter->getMappingsPerSubMesh()); std::unordered_map<repo::lib::RepoUUID, std::vector<uint32_t>, repo::lib::RepoUUIDHasher> splitMapping = reSplitter->getSplitMapping(); std::string fNamePrefix = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/" + mesh->getUniqueID().toString(); assetFiles.push_back(fNamePrefix + ".unity3d"); jsons.push_back(fNamePrefix + "_unity.json.mpc"); success &= generateJSONMapping(mesh, scene, reSplitter->getSplitMapping()); delete reSplitter; } else { repoError << "Failed to generate a remapped mesh for mesh with ID : " << mesh->getUniqueID(); break; } } std::string assetListFile = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/revision/" + scene->getRevisionID().toString() + "/unityAssets.json"; repo::lib::PropertyTree assetListTree; assetListTree.addToTree(MP_LABEL_ASSETS, assetFiles); assetListTree.addToTree(MP_LABEL_JSONS, jsons); assetListTree.addToTree(MP_LABEL_OFFSET, scene->getWorldOffset()); assetListTree.addToTree(MP_LABEL_DATABASE, scene->getDatabaseName()); assetListTree.addToTree(MP_LABEL_PROJECT, scene->getProjectName()); jsonTrees[assetListFile] = assetListTree; } return success; }<commit_msg>ISSUE #189 write min/max as arrays<commit_after>/** * Copyright (C) 2016 3D Repo Ltd * * 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/>. */ /** * Allows Export functionality from 3D Repo World to asset bundle */ #include "repo_model_export_asset.h" #include "../../../core/model/bson/repo_bson_factory.h" #include "../../../lib/repo_log.h" using namespace repo::manipulator::modelconvertor; const static size_t SRC_MAX_VERTEX_LIMIT = 65535; //Labels for multipart JSON descriptor files const static std::string MP_LABEL_APPEARANCE = "appearance"; const static std::string MP_LABEL_MAT_DIFFUSE = "diffuseColor"; const static std::string MP_LABEL_MAT_EMISSIVE = "emissiveColor"; const static std::string MP_LABEL_MATERIAL = "material"; const static std::string MP_LABEL_MAPPING = "mapping"; const static std::string MP_LABEL_MAT_SHININESS = "shininess"; const static std::string MP_LABEL_MAT_SPECULAR = "specularColor"; const static std::string MP_LABEL_MAT_TRANSPARENCY = "transparency"; const static std::string MP_LABEL_MAX = "max"; const static std::string MP_LABEL_MAX_GEO_COUNT = "maxGeoCount"; const static std::string MP_LABEL_MIN = "min"; const static std::string MP_LABEL_NAME = "name"; const static std::string MP_LABEL_NUM_IDs = "numberOfIDs"; const static std::string MP_LABEL_USAGE = "usage"; const static std::string MP_LABEL_ASSETS = "assets"; const static std::string MP_LABEL_SHARED = "sharedID"; const static std::string MP_LABEL_JSONS = "jsonFiles"; const static std::string MP_LABEL_OFFSET = "offset"; const static std::string MP_LABEL_DATABASE = "database"; const static std::string MP_LABEL_PROJECT = "project"; AssetModelExport::AssetModelExport( const repo::core::model::RepoScene *scene ) : WebModelExport(scene) { //Considering all newly imported models should have a stash graph, we only need to support stash graph? if (convertSuccess) { if (gType == repo::core::model::RepoScene::GraphType::OPTIMIZED) { convertSuccess = generateTreeRepresentation(); } else if (!(convertSuccess = !scene->getAllMeshes(repo::core::model::RepoScene::GraphType::DEFAULT).size())) { repoError << "Scene has no optimised graph and it is not a federation graph. SRC Exporter relies on this."; } } else { repoError << "Unable to export to SRC : Empty scene graph!"; } } AssetModelExport::~AssetModelExport() { } repo_web_buffers_t AssetModelExport::getAllFilesExportedAsBuffer() const { return{ std::unordered_map<std::string, std::vector<uint8_t>>(), getJSONFilesAsBuffer() }; } bool AssetModelExport::generateJSONMapping( const repo::core::model::MeshNode *mesh, const repo::core::model::RepoScene *scene, const std::unordered_map<repo::lib::RepoUUID, std::vector<uint32_t>, repo::lib::RepoUUIDHasher> &splitMapping) { bool success; if (success = mesh) { repo::lib::PropertyTree jsonTree; std::vector<repo_mesh_mapping_t> mappings = mesh->getMeshMapping(); std::sort(mappings.begin(), mappings.end(), [](repo_mesh_mapping_t const& a, repo_mesh_mapping_t const& b) { return a.vertFrom < b.vertFrom; }); size_t mappingLength = mappings.size(); jsonTree.addToTree(MP_LABEL_NUM_IDs, mappingLength); jsonTree.addToTree(MP_LABEL_MAX_GEO_COUNT, mappingLength); std::vector<repo::lib::PropertyTree> mappingTrees; std::string meshUID = mesh->getUniqueID().toString(); //Could get the mesh split function to pass a mapping out so we don't do this again. for (size_t i = 0; i < mappingLength; ++i) { auto mapIt = splitMapping.find(mappings[i].mesh_id); if (mapIt != splitMapping.end()) { for (const uint32_t &subMeshID : mapIt->second) { repo::lib::PropertyTree mappingTree; mappingTree.addToTree(MP_LABEL_NAME, mappings[i].mesh_id.toString()); repo::lib::RepoUUID id(mappings[i].mesh_id.toString()); auto mesh = scene->getNodeByUniqueID(repo::core::model::RepoScene::GraphType::DEFAULT, id); if (mesh) mappingTree.addToTree(MP_LABEL_SHARED, mesh->getSharedID().toString()); mappingTree.addToTree(MP_LABEL_MIN, mappings[i].min.toStdVector()); mappingTree.addToTree(MP_LABEL_MAX, mappings[i].max.toStdVector()); std::vector<std::string> usageArr = { meshUID + "_" + std::to_string(subMeshID) }; mappingTree.addToTree(MP_LABEL_USAGE, usageArr); mappingTrees.push_back(mappingTree); } } else { repoError << "Failed to find split mapping for id: " << mappings[i].mesh_id; } } jsonTree.addArrayObjects(MP_LABEL_MAPPING, mappingTrees); std::string jsonFileName = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/" + mesh->getUniqueID().toString() + "_unity.json.mpc"; jsonTrees[jsonFileName] = jsonTree; } else { repoError << "Unable to generate JSON file mapping : null pointer to mesh!"; } return success; } bool AssetModelExport::generateTreeRepresentation( ) { bool success; if (success = scene->hasRoot(gType)) { auto meshes = scene->getAllMeshes(gType); std::vector<std::string> assetFiles, jsons; for (const repo::core::model::RepoNode* node : meshes) { auto mesh = dynamic_cast<const repo::core::model::MeshNode*>(node); if (!mesh) { repoError << "Failed to cast a Repo Node of type mesh into a MeshNode(" << node->getUniqueID() << "). Skipping..."; } std::string textureID = scene->getTextureIDForMesh(gType, mesh->getSharedID()); repo::manipulator::modelutility::MeshMapReorganiser *reSplitter = new repo::manipulator::modelutility::MeshMapReorganiser(mesh, SRC_MAX_VERTEX_LIMIT); reorganisedMeshes.push_back(std::make_shared<repo::core::model::MeshNode>(reSplitter->getRemappedMesh())); if (success = !(reorganisedMeshes.back()->isEmpty())) { serialisedFaceBuf.push_back(reSplitter->getSerialisedFaces()); idMapBuf.push_back(reSplitter->getIDMapArrays()); meshMappings.push_back(reSplitter->getMappingsPerSubMesh()); std::unordered_map<repo::lib::RepoUUID, std::vector<uint32_t>, repo::lib::RepoUUIDHasher> splitMapping = reSplitter->getSplitMapping(); std::string fNamePrefix = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/" + mesh->getUniqueID().toString(); assetFiles.push_back(fNamePrefix + ".unity3d"); jsons.push_back(fNamePrefix + "_unity.json.mpc"); success &= generateJSONMapping(mesh, scene, reSplitter->getSplitMapping()); delete reSplitter; } else { repoError << "Failed to generate a remapped mesh for mesh with ID : " << mesh->getUniqueID(); break; } } std::string assetListFile = "/" + scene->getDatabaseName() + "/" + scene->getProjectName() + "/revision/" + scene->getRevisionID().toString() + "/unityAssets.json"; repo::lib::PropertyTree assetListTree; assetListTree.addToTree(MP_LABEL_ASSETS, assetFiles); assetListTree.addToTree(MP_LABEL_JSONS, jsons); assetListTree.addToTree(MP_LABEL_OFFSET, scene->getWorldOffset()); assetListTree.addToTree(MP_LABEL_DATABASE, scene->getDatabaseName()); assetListTree.addToTree(MP_LABEL_PROJECT, scene->getProjectName()); jsonTrees[assetListFile] = assetListTree; } return success; }<|endoftext|>
<commit_before>/** * Copyright (C) 2015 3D Repo Ltd * * 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/>. */ /** * Allows geometry creation using ifcopenshell */ #include "repo_ifc_utils_geometry.h" #include "../../../core/model/bson/repo_bson_factory.h" #include <boost/filesystem.hpp> using namespace repo::manipulator::modelconvertor; IFCUtilsGeometry::IFCUtilsGeometry(const std::string &file, const ModelImportConfig *settings) : file(file), settings(settings) { } IFCUtilsGeometry::~IFCUtilsGeometry() { } repo_material_t IFCUtilsGeometry::createMaterial( const IfcGeom::Material &material) { repo_material_t matProp; if (material.hasDiffuse()) { auto diffuse = material.diffuse(); matProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] }; } if (material.hasSpecular()) { auto specular = material.specular(); matProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] }; } if (material.hasSpecularity()) { matProp.shininess = material.specularity(); } else { matProp.shininess = NAN; } matProp.shininessStrength = NAN; if (material.hasTransparency()) { matProp.opacity = 1. - material.transparency(); } else { matProp.opacity = 1.; } return matProp; } IfcGeom::IteratorSettings IFCUtilsGeometry::createSettings() { IfcGeom::IteratorSettings itSettings; itSettings.set(IfcGeom::IteratorSettings::WELD_VERTICES, settings->getWieldVertices()); itSettings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, settings->getUseWorldCoords()); itSettings.set(IfcGeom::IteratorSettings::CONVERT_BACK_UNITS, settings->getConvertUnits()); itSettings.set(IfcGeom::IteratorSettings::USE_BREP_DATA, settings->getUseBRepData()); itSettings.set(IfcGeom::IteratorSettings::SEW_SHELLS, settings->getSewShells()); itSettings.set(IfcGeom::IteratorSettings::FASTER_BOOLEANS, settings->getFasterBooleans()); itSettings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, settings->getNoOpeningSubtractions()); itSettings.set(IfcGeom::IteratorSettings::DISABLE_TRIANGULATION, settings->getNoTriangulation()); itSettings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, settings->getUseDefaultMaterials()); itSettings.set(IfcGeom::IteratorSettings::EXCLUDE_SOLIDS_AND_SURFACES, settings->getDisableSolidSurfaces()); itSettings.set(IfcGeom::IteratorSettings::NO_NORMALS, settings->getNoNormals()); itSettings.set(IfcGeom::IteratorSettings::USE_ELEMENT_NAMES, settings->getUseElementNames()); itSettings.set(IfcGeom::IteratorSettings::USE_ELEMENT_GUIDS, settings->getUseElementGuids()); itSettings.set(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES, settings->getUseMaterialNames()); itSettings.set(IfcGeom::IteratorSettings::CENTER_MODEL, settings->getCentreModels()); itSettings.set(IfcGeom::IteratorSettings::GENERATE_UVS, settings->getGenerateUVs()); itSettings.set(IfcGeom::IteratorSettings::APPLY_LAYERSETS, settings->getApplyLayerSets()); return itSettings; } bool IFCUtilsGeometry::generateGeometry(std::string &errMsg) { repoInfo << "Initialising Geometry....." << std::endl; auto itSettings = createSettings(); IfcGeom::Iterator<double> contextIterator(itSettings, file); //auto filter = settings->getFilteringKeywords(); //if (settings->getUseElementsFiltering() && filter.size()) //{ // std::set<std::string> filterSet(filter.begin(), filter.end()); // if (settings->getIsExclusionFilter()) // { // contextIterator.excludeEntities(filterSet); // } // else // { // contextIterator.includeEntities(filterSet); // } //} // repoTrace << "Initialising Geom iterator"; if (contextIterator.initialize()) { repoTrace << "Geom Iterator initialized"; } else { errMsg = "Failed to initialised Geom Iterator"; return false; } std::vector<std::vector<repo_face_t>> allFaces; std::vector<std::vector<double>> allVertices; std::vector<std::vector<double>> allNormals; std::vector<std::vector<double>> allUVs; std::vector<std::string> allIds, allNames, allMaterials; retrieveGeometryFromIterator(contextIterator, itSettings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES), allVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials); //now we have found all meshes, take the minimum bounding box of the scene as offset //and create repo meshes repoTrace << "Finished iterating. number of meshes found: " << allVertices.size(); repoTrace << "Finished iterating. number of materials found: " << materials.size(); std::map<std::string, std::vector<repo::lib::RepoUUID>> materialParent; for (int i = 0; i < allVertices.size(); ++i) { std::vector<repo::lib::RepoVector3D> vertices, normals; std::vector<repo::lib::RepoVector2D> uvs; std::vector<repo_face_t> faces; std::vector<std::vector<float>> boundingBox; for (int j = 0; j < allVertices[i].size(); j += 3) { vertices.push_back({ (float)(allVertices[i][j] - offset[0]), (float)(allVertices[i][j + 1] - offset[1]), (float)(allVertices[i][j + 2] - offset[2]) }); if (allNormals[i].size()) normals.push_back({ (float)allNormals[i][j], (float)allNormals[i][j + 1], (float)allNormals[i][j + 2] }); auto vertex = vertices.back(); if (j == 0) { boundingBox.push_back({ vertex.x, vertex.y, vertex.z }); boundingBox.push_back({ vertex.x, vertex.y, vertex.z }); } else { boundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0]; boundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1]; boundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2]; boundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0]; boundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1]; boundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2]; } } for (int j = 0; j < allUVs[i].size(); j += 2) { uvs.push_back({ (float)allUVs[i][j], (float)allUVs[i][j + 1] }); } std::vector < std::vector<repo::lib::RepoVector2D>> uvChannels; if (uvs.size()) uvChannels.push_back(uvs); auto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels, std::vector<repo_color4d_t>(), std::vector<std::vector<float>>()); if (meshes.find(allIds[i]) == meshes.end()) { meshes[allIds[i]] = std::vector<repo::core::model::MeshNode*>(); } meshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh)); if (allMaterials[i] != "") { if (materialParent.find(allMaterials[i]) == materialParent.end()) { materialParent[allMaterials[i]] = std::vector<repo::lib::RepoUUID>(); } materialParent[allMaterials[i]].push_back(mesh.getSharedID()); } } repoTrace << "Meshes constructed. Wiring materials to parents..."; for (const auto &pair : materialParent) { auto matIt = materials.find(pair.first); if (matIt != materials.end()) { *(matIt->second) = matIt->second->cloneAndAddParent(pair.second); } } return true; } void IFCUtilsGeometry::retrieveGeometryFromIterator( IfcGeom::Iterator<double> &contextIterator, const bool useMaterialNames, std::vector < std::vector<double>> &allVertices, std::vector<std::vector<repo_face_t>> &allFaces, std::vector < std::vector<double>> &allNormals, std::vector < std::vector<double>> &allUVs, std::vector<std::string> &allIds, std::vector<std::string> &allNames, std::vector<std::string> &allMaterials) { repoTrace << "Iterating through Geom Iterator."; do { IfcGeom::Element<double> *ob = contextIterator.get(); auto ob_geo = static_cast<const IfcGeom::TriangulationElement<double>*>(ob); if (ob_geo) { auto faces = ob_geo->geometry().faces(); auto vertices = ob_geo->geometry().verts(); auto normals = ob_geo->geometry().normals(); auto uvs = ob_geo->geometry().uvs(); std::unordered_map<int, std::unordered_map<int, int>> indexMapping; std::unordered_map<int, int> vertexCount; std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs; std::unordered_map<int, std::string> post_materials; std::unordered_map<int, std::vector<repo_face_t>> post_faces; auto matIndIt = ob_geo->geometry().material_ids().begin(); for (int i = 0; i < vertices.size(); i += 3) { for (int j = 0; j < 3; ++j) { int index = j + i; if (offset.size() < j + 1) { offset.push_back(vertices[index]); } else { offset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j]; } } } for (int iface = 0; iface < faces.size(); iface += 3) { auto matInd = *matIndIt; if (indexMapping.find(matInd) == indexMapping.end()) { //new material indexMapping[matInd] = std::unordered_map<int, int>(); vertexCount[matInd] = 0; std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs; std::unordered_map<int, std::vector<repo_face_t>> post_faces; post_vertices[matInd] = std::vector<double>(); post_normals[matInd] = std::vector<double>(); post_uvs[matInd] = std::vector<double>(); post_faces[matInd] = std::vector<repo_face_t>(); auto material = ob_geo->geometry().materials()[matInd]; std::string matName = useMaterialNames ? material.original_name() : material.name(); post_materials[matInd] = matName; if (materials.find(matName) == materials.end()) { //new material, add it to the vector repo_material_t matProp = createMaterial(material); materials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName)); } } repo_face_t face; for (int j = 0; j < 3; ++j) { auto vIndex = faces[iface + j]; if (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end()) { //new index. create a mapping indexMapping[matInd][vIndex] = vertexCount[matInd]++; for (int ivert = 0; ivert < 3; ++ivert) { auto bufferInd = ivert + vIndex * 3; post_vertices[matInd].push_back(vertices[bufferInd]); if (normals.size()) post_normals[matInd].push_back(normals[bufferInd]); if (uvs.size() && ivert < 2) { auto uvbufferInd = ivert + vIndex * 2; post_uvs[matInd].push_back(uvs[uvbufferInd]); } } } face.push_back(indexMapping[matInd][vIndex]); } post_faces[matInd].push_back(face); ++matIndIt; } auto guid = ob_geo->guid(); auto name = ob_geo->name(); for (const auto& pair : post_faces) { auto index = pair.first; allVertices.push_back(post_vertices[index]); allNormals.push_back(post_normals[index]); allFaces.push_back(pair.second); allUVs.push_back(post_uvs[index]); allIds.push_back(guid); allNames.push_back(name); allMaterials.push_back(post_materials[index]); } } if (allIds.size() % 100 == 0) repoInfo << allIds.size() << " meshes created"; } while (contextIterator.next()); }<commit_msg>#170 catch exception on geomiterator initialisation<commit_after>/** * Copyright (C) 2015 3D Repo Ltd * * 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/>. */ /** * Allows geometry creation using ifcopenshell */ #include "repo_ifc_utils_geometry.h" #include "../../../core/model/bson/repo_bson_factory.h" #include <boost/filesystem.hpp> using namespace repo::manipulator::modelconvertor; IFCUtilsGeometry::IFCUtilsGeometry(const std::string &file, const ModelImportConfig *settings) : file(file), settings(settings) { } IFCUtilsGeometry::~IFCUtilsGeometry() { } repo_material_t IFCUtilsGeometry::createMaterial( const IfcGeom::Material &material) { repo_material_t matProp; if (material.hasDiffuse()) { auto diffuse = material.diffuse(); matProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] }; } if (material.hasSpecular()) { auto specular = material.specular(); matProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] }; } if (material.hasSpecularity()) { matProp.shininess = material.specularity(); } else { matProp.shininess = NAN; } matProp.shininessStrength = NAN; if (material.hasTransparency()) { matProp.opacity = 1. - material.transparency(); } else { matProp.opacity = 1.; } return matProp; } IfcGeom::IteratorSettings IFCUtilsGeometry::createSettings() { IfcGeom::IteratorSettings itSettings; itSettings.set(IfcGeom::IteratorSettings::WELD_VERTICES, settings->getWieldVertices()); itSettings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, settings->getUseWorldCoords()); itSettings.set(IfcGeom::IteratorSettings::CONVERT_BACK_UNITS, settings->getConvertUnits()); itSettings.set(IfcGeom::IteratorSettings::USE_BREP_DATA, settings->getUseBRepData()); itSettings.set(IfcGeom::IteratorSettings::SEW_SHELLS, settings->getSewShells()); itSettings.set(IfcGeom::IteratorSettings::FASTER_BOOLEANS, settings->getFasterBooleans()); itSettings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, settings->getNoOpeningSubtractions()); itSettings.set(IfcGeom::IteratorSettings::DISABLE_TRIANGULATION, settings->getNoTriangulation()); itSettings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, settings->getUseDefaultMaterials()); itSettings.set(IfcGeom::IteratorSettings::EXCLUDE_SOLIDS_AND_SURFACES, settings->getDisableSolidSurfaces()); itSettings.set(IfcGeom::IteratorSettings::NO_NORMALS, settings->getNoNormals()); itSettings.set(IfcGeom::IteratorSettings::USE_ELEMENT_NAMES, settings->getUseElementNames()); itSettings.set(IfcGeom::IteratorSettings::USE_ELEMENT_GUIDS, settings->getUseElementGuids()); itSettings.set(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES, settings->getUseMaterialNames()); itSettings.set(IfcGeom::IteratorSettings::CENTER_MODEL, settings->getCentreModels()); itSettings.set(IfcGeom::IteratorSettings::GENERATE_UVS, settings->getGenerateUVs()); itSettings.set(IfcGeom::IteratorSettings::APPLY_LAYERSETS, settings->getApplyLayerSets()); return itSettings; } bool IFCUtilsGeometry::generateGeometry(std::string &errMsg) { repoInfo << "Initialising Geometry....." << std::endl; auto itSettings = createSettings(); IfcGeom::Iterator<double> contextIterator(itSettings, file); //auto filter = settings->getFilteringKeywords(); //if (settings->getUseElementsFiltering() && filter.size()) //{ // std::set<std::string> filterSet(filter.begin(), filter.end()); // if (settings->getIsExclusionFilter()) // { // contextIterator.excludeEntities(filterSet); // } // else // { // contextIterator.includeEntities(filterSet); // } //} // repoTrace << "Initialising Geom iterator"; bool res = false; try{ res = contextIterator.initialize(); } catch (const std::exception &e) { repoError << "Failed to initialise Geom iterator: " << e.what(); } if (res) { repoTrace << "Geom Iterator initialized"; } else { errMsg = "Failed to initialised Geom Iterator"; return false; } std::vector<std::vector<repo_face_t>> allFaces; std::vector<std::vector<double>> allVertices; std::vector<std::vector<double>> allNormals; std::vector<std::vector<double>> allUVs; std::vector<std::string> allIds, allNames, allMaterials; retrieveGeometryFromIterator(contextIterator, itSettings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES), allVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials); //now we have found all meshes, take the minimum bounding box of the scene as offset //and create repo meshes repoTrace << "Finished iterating. number of meshes found: " << allVertices.size(); repoTrace << "Finished iterating. number of materials found: " << materials.size(); std::map<std::string, std::vector<repo::lib::RepoUUID>> materialParent; for (int i = 0; i < allVertices.size(); ++i) { std::vector<repo::lib::RepoVector3D> vertices, normals; std::vector<repo::lib::RepoVector2D> uvs; std::vector<repo_face_t> faces; std::vector<std::vector<float>> boundingBox; for (int j = 0; j < allVertices[i].size(); j += 3) { vertices.push_back({ (float)(allVertices[i][j] - offset[0]), (float)(allVertices[i][j + 1] - offset[1]), (float)(allVertices[i][j + 2] - offset[2]) }); if (allNormals[i].size()) normals.push_back({ (float)allNormals[i][j], (float)allNormals[i][j + 1], (float)allNormals[i][j + 2] }); auto vertex = vertices.back(); if (j == 0) { boundingBox.push_back({ vertex.x, vertex.y, vertex.z }); boundingBox.push_back({ vertex.x, vertex.y, vertex.z }); } else { boundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0]; boundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1]; boundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2]; boundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0]; boundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1]; boundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2]; } } for (int j = 0; j < allUVs[i].size(); j += 2) { uvs.push_back({ (float)allUVs[i][j], (float)allUVs[i][j + 1] }); } std::vector < std::vector<repo::lib::RepoVector2D>> uvChannels; if (uvs.size()) uvChannels.push_back(uvs); auto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels, std::vector<repo_color4d_t>(), std::vector<std::vector<float>>()); if (meshes.find(allIds[i]) == meshes.end()) { meshes[allIds[i]] = std::vector<repo::core::model::MeshNode*>(); } meshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh)); if (allMaterials[i] != "") { if (materialParent.find(allMaterials[i]) == materialParent.end()) { materialParent[allMaterials[i]] = std::vector<repo::lib::RepoUUID>(); } materialParent[allMaterials[i]].push_back(mesh.getSharedID()); } } repoTrace << "Meshes constructed. Wiring materials to parents..."; for (const auto &pair : materialParent) { auto matIt = materials.find(pair.first); if (matIt != materials.end()) { *(matIt->second) = matIt->second->cloneAndAddParent(pair.second); } } return true; } void IFCUtilsGeometry::retrieveGeometryFromIterator( IfcGeom::Iterator<double> &contextIterator, const bool useMaterialNames, std::vector < std::vector<double>> &allVertices, std::vector<std::vector<repo_face_t>> &allFaces, std::vector < std::vector<double>> &allNormals, std::vector < std::vector<double>> &allUVs, std::vector<std::string> &allIds, std::vector<std::string> &allNames, std::vector<std::string> &allMaterials) { repoTrace << "Iterating through Geom Iterator."; do { IfcGeom::Element<double> *ob = contextIterator.get(); auto ob_geo = static_cast<const IfcGeom::TriangulationElement<double>*>(ob); if (ob_geo) { auto faces = ob_geo->geometry().faces(); auto vertices = ob_geo->geometry().verts(); auto normals = ob_geo->geometry().normals(); auto uvs = ob_geo->geometry().uvs(); std::unordered_map<int, std::unordered_map<int, int>> indexMapping; std::unordered_map<int, int> vertexCount; std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs; std::unordered_map<int, std::string> post_materials; std::unordered_map<int, std::vector<repo_face_t>> post_faces; auto matIndIt = ob_geo->geometry().material_ids().begin(); for (int i = 0; i < vertices.size(); i += 3) { for (int j = 0; j < 3; ++j) { int index = j + i; if (offset.size() < j + 1) { offset.push_back(vertices[index]); } else { offset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j]; } } } for (int iface = 0; iface < faces.size(); iface += 3) { auto matInd = *matIndIt; if (indexMapping.find(matInd) == indexMapping.end()) { //new material indexMapping[matInd] = std::unordered_map<int, int>(); vertexCount[matInd] = 0; std::unordered_map<int, std::vector<double>> post_vertices, post_normals, post_uvs; std::unordered_map<int, std::vector<repo_face_t>> post_faces; post_vertices[matInd] = std::vector<double>(); post_normals[matInd] = std::vector<double>(); post_uvs[matInd] = std::vector<double>(); post_faces[matInd] = std::vector<repo_face_t>(); auto material = ob_geo->geometry().materials()[matInd]; std::string matName = useMaterialNames ? material.original_name() : material.name(); post_materials[matInd] = matName; if (materials.find(matName) == materials.end()) { //new material, add it to the vector repo_material_t matProp = createMaterial(material); materials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName)); } } repo_face_t face; for (int j = 0; j < 3; ++j) { auto vIndex = faces[iface + j]; if (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end()) { //new index. create a mapping indexMapping[matInd][vIndex] = vertexCount[matInd]++; for (int ivert = 0; ivert < 3; ++ivert) { auto bufferInd = ivert + vIndex * 3; post_vertices[matInd].push_back(vertices[bufferInd]); if (normals.size()) post_normals[matInd].push_back(normals[bufferInd]); if (uvs.size() && ivert < 2) { auto uvbufferInd = ivert + vIndex * 2; post_uvs[matInd].push_back(uvs[uvbufferInd]); } } } face.push_back(indexMapping[matInd][vIndex]); } post_faces[matInd].push_back(face); ++matIndIt; } auto guid = ob_geo->guid(); auto name = ob_geo->name(); for (const auto& pair : post_faces) { auto index = pair.first; allVertices.push_back(post_vertices[index]); allNormals.push_back(post_normals[index]); allFaces.push_back(pair.second); allUVs.push_back(post_uvs[index]); allIds.push_back(guid); allNames.push_back(name); allMaterials.push_back(post_materials[index]); } } if (allIds.size() % 100 == 0) repoInfo << allIds.size() << " meshes created"; } while (contextIterator.next()); }<|endoftext|>
<commit_before> /************************************************************************** * Copyright(c) 1998-2010, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // Base class for cuts on AOD reconstructed heavy-flavour decay // // Author: A.Dainese, [email protected] ///////////////////////////////////////////////////////////// #include <Riostream.h> #include "AliVEvent.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliVVertex.h" #include "AliESDVertex.h" #include "AliAODVertex.h" #include "AliESDtrack.h" #include "AliAODTrack.h" #include "AliESDtrackCuts.h" #include "AliAODRecoDecayHF.h" #include "AliRDHFCuts.h" ClassImp(AliRDHFCuts) //-------------------------------------------------------------------------- AliRDHFCuts::AliRDHFCuts(const Char_t* name, const Char_t* title) : AliAnalysisCuts(name,title), fMinVtxType(3), fMinVtxContr(1), fMaxVtxRedChi2(1e6), fMinSPDMultiplicity(0), fTriggerMask(0), fTrackCuts(0), fnPtBins(1), fnPtBinLimits(1), fPtBinLimits(0), fnVars(1), fVarNames(0), fnVarsForOpt(0), fVarsForOpt(0), fGlobalIndex(1), fCutsRD(0), fIsUpperCut(0) { // // Default Constructor // } //-------------------------------------------------------------------------- AliRDHFCuts::AliRDHFCuts(const AliRDHFCuts &source) : AliAnalysisCuts(source), fMinVtxType(source.fMinVtxType), fMinVtxContr(source.fMinVtxContr), fMaxVtxRedChi2(source.fMaxVtxRedChi2), fMinSPDMultiplicity(source.fMinSPDMultiplicity), fTriggerMask(source.fTriggerMask), fTrackCuts(0), fnPtBins(source.fnPtBins), fnPtBinLimits(source.fnPtBinLimits), fPtBinLimits(0), fnVars(source.fnVars), fVarNames(0), fnVarsForOpt(source.fnVarsForOpt), fVarsForOpt(0), fGlobalIndex(source.fGlobalIndex), fCutsRD(0), fIsUpperCut(0) { // // Copy constructor // cout<<"Copy constructor"<<endl; if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts()); if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits); if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut); if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD); if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt); PrintAll(); } //-------------------------------------------------------------------------- AliRDHFCuts &AliRDHFCuts::operator=(const AliRDHFCuts &source) { // // assignment operator // if(&source == this) return *this; AliAnalysisCuts::operator=(source); fMinVtxType=source.fMinVtxType; fMinVtxContr=source.fMinVtxContr; fMaxVtxRedChi2=source.fMaxVtxRedChi2; fMinSPDMultiplicity=source.fMinSPDMultiplicity; fTriggerMask=source.fTriggerMask; fnPtBins=source.fnPtBins; fnVars=source.fnVars; fGlobalIndex=source.fGlobalIndex; fnVarsForOpt=source.fnVarsForOpt; if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits); if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut); if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD); if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt); PrintAll(); return *this; } //-------------------------------------------------------------------------- AliRDHFCuts::~AliRDHFCuts() { // // Default Destructor // if(fPtBinLimits) {delete [] fPtBinLimits; fPtBinLimits=0;} if(fVarNames) {delete [] fVarNames; fVarNames=0;} if(fVarsForOpt) {delete [] fVarsForOpt; fVarsForOpt=0;} if(fCutsRD) { delete [] fCutsRD; fCutsRD=0; } if(fIsUpperCut) {delete [] fIsUpperCut; fIsUpperCut=0;} } //--------------------------------------------------------------------------- Bool_t AliRDHFCuts::IsEventSelected(AliVEvent *event) const { // // Event selection // //if(fTriggerMask && event->GetTriggerMask()!=fTriggerMask) return kFALSE; // multiplicity cuts no implemented yet const AliVVertex *vertex = event->GetPrimaryVertex(); if(!vertex) return kFALSE; TString title=vertex->GetTitle(); if(title.Contains("Z") && fMinVtxType>1) return kFALSE; if(title.Contains("3D") && fMinVtxType>2) return kFALSE; if(vertex->GetNContributors()<fMinVtxContr) return kFALSE; return kTRUE; } //--------------------------------------------------------------------------- Bool_t AliRDHFCuts::AreDaughtersSelected(AliAODRecoDecayHF *d) const { // // Daughter tracks selection // if(!fTrackCuts) return kTRUE; Int_t ndaughters = d->GetNDaughters(); AliESDtrack* esdTrack=0; AliAODVertex *vAOD = d->GetPrimaryVtx(); Double_t pos[3],cov[6]; vAOD->GetXYZ(pos); vAOD->GetCovarianceMatrix(cov); const AliESDVertex *vESD = new AliESDVertex(pos,cov,100.,100); Bool_t retval=kTRUE; for(Int_t idg=0; idg<ndaughters; idg++) { AliAODTrack *dgTrack = (AliAODTrack*)d->GetDaughter(idg); if(!dgTrack) retval = kFALSE; //printf("charge %d\n",dgTrack->Charge()); if(dgTrack->Charge()==0) continue; // it's not a track, but a V0 // convert to ESD track here esdTrack=new AliESDtrack(dgTrack); // needed to calculate the impact parameters esdTrack->RelateToVertex(vESD,0.,3.); if(!fTrackCuts->IsSelected(esdTrack)) retval = kFALSE; delete esdTrack; esdTrack=0; } delete vESD; vESD=0; return retval; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetPtBins(Int_t nPtBinLimits,Float_t *ptBinLimits) { // Set the pt bins if(fPtBinLimits) { delete [] fPtBinLimits; fPtBinLimits = NULL; printf("Changing the pt bins\n"); } if(nPtBinLimits != fnPtBins+1){ cout<<"Warning: ptBinLimits dimention "<<nPtBinLimits<<" != nPtBins+1 ("<<fnPtBins+1<<")\nSetting nPtBins to "<<nPtBinLimits-1<<endl; SetNPtBins(nPtBinLimits-1); } fnPtBinLimits = nPtBinLimits; SetGlobalIndex(); cout<<"Changing also Global Index -> "<<fGlobalIndex<<endl; fPtBinLimits = new Float_t[fnPtBinLimits]; for(Int_t ib=0; ib<nPtBinLimits; ib++) fPtBinLimits[ib]=ptBinLimits[ib]; return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetVarNames(Int_t nVars,TString *varNames,Bool_t *isUpperCut){ // Set the variable names if(fVarNames) { delete [] fVarNames; fVarNames = NULL; printf("Changing the variable names\n"); } if(nVars!=fnVars){ printf("Wrong number of variables: it has to be %d\n",fnVars); return; } //fnVars=nVars; fVarNames = new TString[nVars]; fIsUpperCut = new Bool_t[nVars]; for(Int_t iv=0; iv<nVars; iv++) { fVarNames[iv] = varNames[iv]; fIsUpperCut[iv] = isUpperCut[iv]; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetVarsForOpt(Int_t nVars,Bool_t *forOpt) { // Set the variables to be used for cuts optimization if(fVarsForOpt) { delete [] fVarsForOpt; fVarsForOpt = NULL; printf("Changing the variables for cut optimization\n"); } if(nVars==0){//!=fnVars) { printf("%d not accepted as number of variables: it has to be %d\n",nVars,fnVars); return; } fnVarsForOpt = 0; fVarsForOpt = new Bool_t[fnVars]; for(Int_t iv=0; iv<fnVars; iv++) { fVarsForOpt[iv]=forOpt[iv]; if(fVarsForOpt[iv]) fnVarsForOpt++; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetCuts(Int_t nVars,Int_t nPtBins,Float_t **cutsRD) { // // store the cuts // if(nVars!=fnVars) { printf("Wrong number of variables: it has to be %d\n",fnVars); return; } if(nPtBins!=fnPtBins) { printf("Wrong number of pt bins: it has to be %d\n",fnPtBins); return; } if(!fCutsRD) fCutsRD = new Float_t[fGlobalIndex]; for(Int_t iv=0; iv<fnVars; iv++) { for(Int_t ib=0; ib<fnPtBins; ib++) { //check if(GetGlobalIndex(iv,ib)>=fGlobalIndex) { cout<<"Overflow, exit..."<<endl; return; } fCutsRD[GetGlobalIndex(iv,ib)] = cutsRD[iv][ib]; } } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetCuts(Int_t glIndex,Float_t* cutsRDGlob){ // // store the cuts // if(glIndex != fGlobalIndex){ cout<<"Wrong array size: it has to be "<<fGlobalIndex<<endl; return; } if(!fCutsRD) fCutsRD = new Float_t[fGlobalIndex]; for(Int_t iGl=0;iGl<fGlobalIndex;iGl++){ fCutsRD[iGl] = cutsRDGlob[iGl]; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::PrintAll() const { // // print all cuts values // if(fVarNames){ cout<<"Array of variables"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fVarNames[iv]<<"\t"; } cout<<endl; } if(fVarsForOpt){ cout<<"Array of optimization"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fVarsForOpt[iv]<<"\t"; } cout<<endl; } if(fIsUpperCut){ cout<<"Array of upper/lower cut"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fIsUpperCut[iv]<<"\t"; } cout<<endl; } if(fPtBinLimits){ cout<<"Array of ptbin limits"<<endl; for(Int_t ib=0;ib<fnPtBinLimits;ib++){ cout<<fPtBinLimits[ib]<<"\t"; } cout<<endl; } if(fCutsRD){ cout<<"Matrix of cuts"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ for(Int_t ib=0;ib<fnPtBins;ib++){ cout<<"fCutsRD["<<iv<<"]["<<ib<<"] = "<<fCutsRD[GetGlobalIndex(iv,ib)]<<"\t"; } cout<<endl; } cout<<endl; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::GetCuts(Float_t**& cutsRD) const{ // // get the cuts // //cout<<"Give back a "<<fnVars<<"x"<<fnPtBins<<" matrix."<<endl; Int_t iv,ib; if(!cutsRD) { //cout<<"Initialization..."<<endl; cutsRD=new Float_t*[fnVars]; for(iv=0; iv<fnVars; iv++) { cutsRD[iv] = new Float_t[fnPtBins]; } } for(Int_t iGlobal=0; iGlobal<fGlobalIndex; iGlobal++) { GetVarPtIndex(iGlobal,iv,ib); cutsRD[iv][ib] = fCutsRD[iGlobal]; } return; } //--------------------------------------------------------------------------- Int_t AliRDHFCuts::GetGlobalIndex(Int_t iVar,Int_t iPtBin) const{ // // give the global index from variable and pt bin // return iPtBin*fnVars+iVar; } //--------------------------------------------------------------------------- void AliRDHFCuts::GetVarPtIndex(Int_t iGlob, Int_t& iVar, Int_t& iPtBin) const { // //give the index of the variable and of the pt bin from the global index // iPtBin=(Int_t)iGlob/fnVars; iVar=iGlob%fnVars; return; } //--------------------------------------------------------------------------- Int_t AliRDHFCuts::PtBin(Double_t pt) const { // //give the pt bin where the pt lies. // Int_t ptbin=0; for (Int_t i=0;i<fnPtBins;i++){ if(pt<fPtBinLimits[i+1]) { ptbin=i; break; } } return ptbin; } <commit_msg>Fix in operator=<commit_after> /************************************************************************** * Copyright(c) 1998-2010, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // Base class for cuts on AOD reconstructed heavy-flavour decay // // Author: A.Dainese, [email protected] ///////////////////////////////////////////////////////////// #include <Riostream.h> #include "AliVEvent.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliVVertex.h" #include "AliESDVertex.h" #include "AliAODVertex.h" #include "AliESDtrack.h" #include "AliAODTrack.h" #include "AliESDtrackCuts.h" #include "AliAODRecoDecayHF.h" #include "AliRDHFCuts.h" ClassImp(AliRDHFCuts) //-------------------------------------------------------------------------- AliRDHFCuts::AliRDHFCuts(const Char_t* name, const Char_t* title) : AliAnalysisCuts(name,title), fMinVtxType(3), fMinVtxContr(1), fMaxVtxRedChi2(1e6), fMinSPDMultiplicity(0), fTriggerMask(0), fTrackCuts(0), fnPtBins(1), fnPtBinLimits(1), fPtBinLimits(0), fnVars(1), fVarNames(0), fnVarsForOpt(0), fVarsForOpt(0), fGlobalIndex(1), fCutsRD(0), fIsUpperCut(0) { // // Default Constructor // } //-------------------------------------------------------------------------- AliRDHFCuts::AliRDHFCuts(const AliRDHFCuts &source) : AliAnalysisCuts(source), fMinVtxType(source.fMinVtxType), fMinVtxContr(source.fMinVtxContr), fMaxVtxRedChi2(source.fMaxVtxRedChi2), fMinSPDMultiplicity(source.fMinSPDMultiplicity), fTriggerMask(source.fTriggerMask), fTrackCuts(0), fnPtBins(source.fnPtBins), fnPtBinLimits(source.fnPtBinLimits), fPtBinLimits(0), fnVars(source.fnVars), fVarNames(0), fnVarsForOpt(source.fnVarsForOpt), fVarsForOpt(0), fGlobalIndex(source.fGlobalIndex), fCutsRD(0), fIsUpperCut(0) { // // Copy constructor // cout<<"Copy constructor"<<endl; if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts()); if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits); if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut); if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD); if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt); PrintAll(); } //-------------------------------------------------------------------------- AliRDHFCuts &AliRDHFCuts::operator=(const AliRDHFCuts &source) { // // assignment operator // if(&source == this) return *this; AliAnalysisCuts::operator=(source); fMinVtxType=source.fMinVtxType; fMinVtxContr=source.fMinVtxContr; fMaxVtxRedChi2=source.fMaxVtxRedChi2; fMinSPDMultiplicity=source.fMinSPDMultiplicity; fTriggerMask=source.fTriggerMask; fnPtBins=source.fnPtBins; fnVars=source.fnVars; fGlobalIndex=source.fGlobalIndex; fnVarsForOpt=source.fnVarsForOpt; if(source.GetTrackCuts()) AddTrackCuts(source.GetTrackCuts()); if(source.fPtBinLimits) SetPtBins(source.fnPtBinLimits,source.fPtBinLimits); if(source.fVarNames) SetVarNames(source.fnVars,source.fVarNames,source.fIsUpperCut); if(source.fCutsRD) SetCuts(source.fGlobalIndex,source.fCutsRD); if(source.fVarsForOpt) SetVarsForOpt(source.fnVarsForOpt,source.fVarsForOpt); PrintAll(); return *this; } //-------------------------------------------------------------------------- AliRDHFCuts::~AliRDHFCuts() { // // Default Destructor // if(fPtBinLimits) {delete [] fPtBinLimits; fPtBinLimits=0;} if(fVarNames) {delete [] fVarNames; fVarNames=0;} if(fVarsForOpt) {delete [] fVarsForOpt; fVarsForOpt=0;} if(fCutsRD) { delete [] fCutsRD; fCutsRD=0; } if(fIsUpperCut) {delete [] fIsUpperCut; fIsUpperCut=0;} } //--------------------------------------------------------------------------- Bool_t AliRDHFCuts::IsEventSelected(AliVEvent *event) const { // // Event selection // //if(fTriggerMask && event->GetTriggerMask()!=fTriggerMask) return kFALSE; // multiplicity cuts no implemented yet const AliVVertex *vertex = event->GetPrimaryVertex(); if(!vertex) return kFALSE; TString title=vertex->GetTitle(); if(title.Contains("Z") && fMinVtxType>1) return kFALSE; if(title.Contains("3D") && fMinVtxType>2) return kFALSE; if(vertex->GetNContributors()<fMinVtxContr) return kFALSE; return kTRUE; } //--------------------------------------------------------------------------- Bool_t AliRDHFCuts::AreDaughtersSelected(AliAODRecoDecayHF *d) const { // // Daughter tracks selection // if(!fTrackCuts) return kTRUE; Int_t ndaughters = d->GetNDaughters(); AliESDtrack* esdTrack=0; AliAODVertex *vAOD = d->GetPrimaryVtx(); Double_t pos[3],cov[6]; vAOD->GetXYZ(pos); vAOD->GetCovarianceMatrix(cov); const AliESDVertex *vESD = new AliESDVertex(pos,cov,100.,100); Bool_t retval=kTRUE; for(Int_t idg=0; idg<ndaughters; idg++) { AliAODTrack *dgTrack = (AliAODTrack*)d->GetDaughter(idg); if(!dgTrack) retval = kFALSE; //printf("charge %d\n",dgTrack->Charge()); if(dgTrack->Charge()==0) continue; // it's not a track, but a V0 // convert to ESD track here esdTrack=new AliESDtrack(dgTrack); // needed to calculate the impact parameters esdTrack->RelateToVertex(vESD,0.,3.); if(!fTrackCuts->IsSelected(esdTrack)) retval = kFALSE; delete esdTrack; esdTrack=0; } delete vESD; vESD=0; return retval; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetPtBins(Int_t nPtBinLimits,Float_t *ptBinLimits) { // Set the pt bins if(fPtBinLimits) { delete [] fPtBinLimits; fPtBinLimits = NULL; printf("Changing the pt bins\n"); } if(nPtBinLimits != fnPtBins+1){ cout<<"Warning: ptBinLimits dimention "<<nPtBinLimits<<" != nPtBins+1 ("<<fnPtBins+1<<")\nSetting nPtBins to "<<nPtBinLimits-1<<endl; SetNPtBins(nPtBinLimits-1); } fnPtBinLimits = nPtBinLimits; SetGlobalIndex(); cout<<"Changing also Global Index -> "<<fGlobalIndex<<endl; fPtBinLimits = new Float_t[fnPtBinLimits]; for(Int_t ib=0; ib<nPtBinLimits; ib++) fPtBinLimits[ib]=ptBinLimits[ib]; return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetVarNames(Int_t nVars,TString *varNames,Bool_t *isUpperCut){ // Set the variable names if(fVarNames) { delete [] fVarNames; fVarNames = NULL; printf("Changing the variable names\n"); } if(nVars!=fnVars){ printf("Wrong number of variables: it has to be %d\n",fnVars); return; } //fnVars=nVars; fVarNames = new TString[nVars]; fIsUpperCut = new Bool_t[nVars]; for(Int_t iv=0; iv<nVars; iv++) { fVarNames[iv] = varNames[iv]; fIsUpperCut[iv] = isUpperCut[iv]; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetVarsForOpt(Int_t nVars,Bool_t *forOpt) { // Set the variables to be used for cuts optimization if(fVarsForOpt) { delete [] fVarsForOpt; fVarsForOpt = NULL; printf("Changing the variables for cut optimization\n"); } if(nVars==0){//!=fnVars) { printf("%d not accepted as number of variables: it has to be %d\n",nVars,fnVars); return; } fnVarsForOpt = 0; fVarsForOpt = new Bool_t[fnVars]; for(Int_t iv=0; iv<fnVars; iv++) { fVarsForOpt[iv]=forOpt[iv]; if(fVarsForOpt[iv]) fnVarsForOpt++; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetCuts(Int_t nVars,Int_t nPtBins,Float_t **cutsRD) { // // store the cuts // if(nVars!=fnVars) { printf("Wrong number of variables: it has to be %d\n",fnVars); return; } if(nPtBins!=fnPtBins) { printf("Wrong number of pt bins: it has to be %d\n",fnPtBins); return; } if(!fCutsRD) fCutsRD = new Float_t[fGlobalIndex]; for(Int_t iv=0; iv<fnVars; iv++) { for(Int_t ib=0; ib<fnPtBins; ib++) { //check if(GetGlobalIndex(iv,ib)>=fGlobalIndex) { cout<<"Overflow, exit..."<<endl; return; } fCutsRD[GetGlobalIndex(iv,ib)] = cutsRD[iv][ib]; } } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::SetCuts(Int_t glIndex,Float_t* cutsRDGlob){ // // store the cuts // if(glIndex != fGlobalIndex){ cout<<"Wrong array size: it has to be "<<fGlobalIndex<<endl; return; } if(!fCutsRD) fCutsRD = new Float_t[fGlobalIndex]; for(Int_t iGl=0;iGl<fGlobalIndex;iGl++){ fCutsRD[iGl] = cutsRDGlob[iGl]; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::PrintAll() const { // // print all cuts values // if(fVarNames){ cout<<"Array of variables"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fVarNames[iv]<<"\t"; } cout<<endl; } if(fVarsForOpt){ cout<<"Array of optimization"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fVarsForOpt[iv]<<"\t"; } cout<<endl; } if(fIsUpperCut){ cout<<"Array of upper/lower cut"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ cout<<fIsUpperCut[iv]<<"\t"; } cout<<endl; } if(fPtBinLimits){ cout<<"Array of ptbin limits"<<endl; for(Int_t ib=0;ib<fnPtBinLimits;ib++){ cout<<fPtBinLimits[ib]<<"\t"; } cout<<endl; } if(fCutsRD){ cout<<"Matrix of cuts"<<endl; for(Int_t iv=0;iv<fnVars;iv++){ for(Int_t ib=0;ib<fnPtBins;ib++){ cout<<"fCutsRD["<<iv<<"]["<<ib<<"] = "<<fCutsRD[GetGlobalIndex(iv,ib)]<<"\t"; } cout<<endl; } cout<<endl; } return; } //--------------------------------------------------------------------------- void AliRDHFCuts::GetCuts(Float_t**& cutsRD) const{ // // get the cuts // //cout<<"Give back a "<<fnVars<<"x"<<fnPtBins<<" matrix."<<endl; Int_t iv,ib; if(!cutsRD) { //cout<<"Initialization..."<<endl; cutsRD=new Float_t*[fnVars]; for(iv=0; iv<fnVars; iv++) { cutsRD[iv] = new Float_t[fnPtBins]; } } for(Int_t iGlobal=0; iGlobal<fGlobalIndex; iGlobal++) { GetVarPtIndex(iGlobal,iv,ib); cutsRD[iv][ib] = fCutsRD[iGlobal]; } return; } //--------------------------------------------------------------------------- Int_t AliRDHFCuts::GetGlobalIndex(Int_t iVar,Int_t iPtBin) const{ // // give the global index from variable and pt bin // return iPtBin*fnVars+iVar; } //--------------------------------------------------------------------------- void AliRDHFCuts::GetVarPtIndex(Int_t iGlob, Int_t& iVar, Int_t& iPtBin) const { // //give the index of the variable and of the pt bin from the global index // iPtBin=(Int_t)iGlob/fnVars; iVar=iGlob%fnVars; return; } //--------------------------------------------------------------------------- Int_t AliRDHFCuts::PtBin(Double_t pt) const { // //give the pt bin where the pt lies. // Int_t ptbin=0; for (Int_t i=0;i<fnPtBins;i++){ if(pt<fPtBinLimits[i+1]) { ptbin=i; break; } } return ptbin; } <|endoftext|>
<commit_before> #include "stdafx.h" #include "GStreamerCore.h" #include "UnityHelpers.h" #include <IThreadManager.h> #include <gst/app/gstappsink.h> #include <gst/video/video.h> #include <glib-object.h> #include <glib.h> #include <algorithm> #if false #include "CMySrc.h" #include "CMySink.h" #endif #ifdef USE_UNITY_NETWORK #include "CMyUDPSrc.h" #include "CMyUDPSink.h" #include "CMyListener.h" #endif #ifdef __ANDROID__ void gst_android_register_static_plugins(void); /* Call this function to load GIO modules */ void gst_android_load_gio_modules(void); #endif namespace mray { namespace video { GStreamerCore* GStreamerCore::m_instance=0; uint GStreamerCore::m_refCount = 0; static gboolean appsink_plugin_init(GstPlugin * plugin) { gst_element_register(plugin, "appsink", GST_RANK_NONE, GST_TYPE_APP_SINK); return TRUE; } class GstMainLoopThread : public OS::IThreadFunction{ public: GMainLoop *main_loop; GstMainLoopThread() :main_loop(NULL) { } void setup(){ // startThread(); } void execute(OS::IThread*caller, void*arg){ main_loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(main_loop); LogMessage("GST Thread shutdown",ELL_INFO); } }; GStreamerCore::GStreamerCore() { gub_main_loop_thread = 0; gub_main_loop = 0; _Init(); } GStreamerCore::~GStreamerCore() { _StopLoop(); gst_deinit(); } void g_logFunction(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { if(log_level==G_LOG_LEVEL_INFO || log_level==G_LOG_LEVEL_DEBUG) LogMessage(message, ELL_INFO); else if(log_level==G_LOG_LEVEL_WARNING) LogMessage(message, ELL_WARNING); else if(log_level==G_LOG_LEVEL_CRITICAL || log_level==G_LOG_FLAG_FATAL) LogMessage(message, ELL_ERROR); else LogMessage(message, ELL_INFO); } gpointer gst_main_loop_func(gpointer data) { GStreamerCore* core = (GStreamerCore*)data; core->_loopFunction(); return NULL; } void GStreamerCore::_Init() { GError *err = 0; _gst_debug_enabled = false; if (!gst_init_check(0,0, &err)) { LogManager::Instance()->LogMessage("GStreamerCore - Failed to init GStreamer!"); } else { g_log_set_handler(0, G_LOG_LEVEL_WARNING, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_MESSAGE, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_INFO, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_DEBUG, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_CRITICAL, g_logFunction, 0); g_log_set_handler(0, G_LOG_FLAG_FATAL , g_logFunction, 0); g_log_set_default_handler(g_logFunction, 0); #if defined (__ANDROID__) //gst_android_register_static_plugins(); //gst_android_load_gio_modules(); #endif LogManager::Instance()->LogMessage("GStreamerCore - Registering Elements!"); //fclose(stderr); //register plugin path //std::string gst_path = g_getenv("GSTREAMER_1_0_ROOT_X86_64"); //putenv(("GST_PLUGIN_PATH_1_0=" + gst_path + "lib\\gstreamer-1.0" + ";.").c_str()); //add our custom src/sink elements #ifdef USE_UNITY_NETWORK gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "appsink", (char*)"Element application sink", appsink_plugin_init, "0.1", "LGPL", "ofVideoPlayer", "openFrameworks", "http://openframeworks.cc/"); /* gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mysrc", (char*)"Element application src", _GstMySrcClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mysink", (char*)"Element application sink", _GstMySinkClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", "");*/ gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "myudpsrc", (char*)"Element udp src", _GstMyUDPSrcClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "myudpsink", (char*)"Element udp sink", _GstMyUDPSinkClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mylistener", (char*)"Custom listener element", _GstMyListenerClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); #endif LogManager::Instance()->LogMessage("GStreamerCore - GStreamer inited"); } #if GLIB_MINOR_VERSION<32 if (!g_thread_supported()){ g_thread_init(NULL); } #endif gub_main_loop_thread = g_thread_new("GstUnityBridge Main Thread", gst_main_loop_func, this); if (!gub_main_loop_thread) { LogManager::Instance()->LogMessage(std::string("Failed to create GLib main thread: ") + std::string(err ? err->message : "<No error message>")); return; } _StartLoop(); } void GStreamerCore::_loopFunction() { LogManager::Instance()->LogMessage("Entering main loop"); gub_main_loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(gub_main_loop); LogManager::Instance()->LogMessage("Quitting main loop"); } void GStreamerCore::_StartLoop() { /*m_threadFunc = new GstMainLoopThread(); m_mainLoopThread = OS::IThreadManager::getInstance().createThread(m_threadFunc); m_mainLoopThread->start(0);*/ } void GStreamerCore::_StopLoop() { /* if (!m_threadFunc) return; GstMainLoopThread* mainLoop = (GstMainLoopThread*)m_threadFunc; g_main_loop_quit(mainLoop->main_loop); bool running = g_main_loop_is_running(mainLoop->main_loop); g_main_loop_unref(mainLoop->main_loop); delete m_threadFunc; OS::IThreadManager::getInstance().killThread(m_mainLoopThread); delete m_mainLoopThread; m_threadFunc = 0; m_mainLoopThread = 0; */ if (!gub_main_loop) { return; } g_main_loop_quit(gub_main_loop); gub_main_loop = NULL; g_thread_join(gub_main_loop_thread); gub_main_loop_thread = NULL; } void GStreamerCore::Ref() { m_refCount++; if (m_refCount==1) { LogManager::Instance()->LogMessage("Initializing GStreamer"); m_instance = new GStreamerCore(); LogManager::Instance()->LogMessage("Initializing GStreamer - Done"); } } void GStreamerCore::Unref() { if (m_refCount == 0) { LogMessage("GStreamerCore::Unref() - unreferencing GStreamer with no reference! ", ELL_ERROR); return; } //m_refCount--; if (m_refCount == 0) { delete m_instance; m_instance = 0; } } GStreamerCore* GStreamerCore::Instance() { return m_instance; } } } <commit_msg>Fix errors during GStreamer init not being logged<commit_after> #include "stdafx.h" #include "GStreamerCore.h" #include "UnityHelpers.h" #include <IThreadManager.h> #include <gst/app/gstappsink.h> #include <gst/video/video.h> #include <glib-object.h> #include <glib.h> #include <algorithm> #if false #include "CMySrc.h" #include "CMySink.h" #endif #ifdef USE_UNITY_NETWORK #include "CMyUDPSrc.h" #include "CMyUDPSink.h" #include "CMyListener.h" #endif #ifdef __ANDROID__ void gst_android_register_static_plugins(void); /* Call this function to load GIO modules */ void gst_android_load_gio_modules(void); #endif namespace mray { namespace video { GStreamerCore* GStreamerCore::m_instance=0; uint GStreamerCore::m_refCount = 0; static gboolean appsink_plugin_init(GstPlugin * plugin) { gst_element_register(plugin, "appsink", GST_RANK_NONE, GST_TYPE_APP_SINK); return TRUE; } class GstMainLoopThread : public OS::IThreadFunction{ public: GMainLoop *main_loop; GstMainLoopThread() :main_loop(NULL) { } void setup(){ // startThread(); } void execute(OS::IThread*caller, void*arg){ main_loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(main_loop); LogMessage("GST Thread shutdown",ELL_INFO); } }; GStreamerCore::GStreamerCore() { gub_main_loop_thread = 0; gub_main_loop = 0; _Init(); } GStreamerCore::~GStreamerCore() { _StopLoop(); gst_deinit(); } void g_logFunction(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { if(log_level==G_LOG_LEVEL_INFO || log_level==G_LOG_LEVEL_DEBUG) LogMessage(message, ELL_INFO); else if(log_level==G_LOG_LEVEL_WARNING) LogMessage(message, ELL_WARNING); else if(log_level==G_LOG_LEVEL_CRITICAL || log_level==G_LOG_FLAG_FATAL) LogMessage(message, ELL_ERROR); else LogMessage(message, ELL_INFO); } gpointer gst_main_loop_func(gpointer data) { GStreamerCore* core = (GStreamerCore*)data; core->_loopFunction(); return NULL; } void GStreamerCore::_Init() { g_log_set_handler(0, G_LOG_LEVEL_WARNING, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_MESSAGE, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_INFO, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_DEBUG, g_logFunction, 0); g_log_set_handler(0, G_LOG_LEVEL_CRITICAL, g_logFunction, 0); g_log_set_handler(0, G_LOG_FLAG_FATAL , g_logFunction, 0); g_log_set_default_handler(g_logFunction, 0); GError *err = 0; _gst_debug_enabled = false; if (!gst_init_check(0,0, &err)) { LogManager::Instance()->LogMessage("GStreamerCore - Failed to init GStreamer!"); } else { #if defined (__ANDROID__) //gst_android_register_static_plugins(); //gst_android_load_gio_modules(); #endif LogManager::Instance()->LogMessage("GStreamerCore - Registering Elements!"); //fclose(stderr); //register plugin path //std::string gst_path = g_getenv("GSTREAMER_1_0_ROOT_X86_64"); //putenv(("GST_PLUGIN_PATH_1_0=" + gst_path + "lib\\gstreamer-1.0" + ";.").c_str()); //add our custom src/sink elements #ifdef USE_UNITY_NETWORK gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "appsink", (char*)"Element application sink", appsink_plugin_init, "0.1", "LGPL", "ofVideoPlayer", "openFrameworks", "http://openframeworks.cc/"); /* gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mysrc", (char*)"Element application src", _GstMySrcClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mysink", (char*)"Element application sink", _GstMySinkClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", "");*/ gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "myudpsrc", (char*)"Element udp src", _GstMyUDPSrcClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "myudpsink", (char*)"Element udp sink", _GstMyUDPSinkClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "mylistener", (char*)"Custom listener element", _GstMyListenerClass::plugin_init, "0.1", "LGPL", "GstVideoProvider", "mray", ""); #endif LogManager::Instance()->LogMessage("GStreamerCore - GStreamer inited"); } #if GLIB_MINOR_VERSION<32 if (!g_thread_supported()){ g_thread_init(NULL); } #endif gub_main_loop_thread = g_thread_new("GstUnityBridge Main Thread", gst_main_loop_func, this); if (!gub_main_loop_thread) { LogManager::Instance()->LogMessage(std::string("Failed to create GLib main thread: ") + std::string(err ? err->message : "<No error message>")); return; } _StartLoop(); } void GStreamerCore::_loopFunction() { LogManager::Instance()->LogMessage("Entering main loop"); gub_main_loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(gub_main_loop); LogManager::Instance()->LogMessage("Quitting main loop"); } void GStreamerCore::_StartLoop() { /*m_threadFunc = new GstMainLoopThread(); m_mainLoopThread = OS::IThreadManager::getInstance().createThread(m_threadFunc); m_mainLoopThread->start(0);*/ } void GStreamerCore::_StopLoop() { /* if (!m_threadFunc) return; GstMainLoopThread* mainLoop = (GstMainLoopThread*)m_threadFunc; g_main_loop_quit(mainLoop->main_loop); bool running = g_main_loop_is_running(mainLoop->main_loop); g_main_loop_unref(mainLoop->main_loop); delete m_threadFunc; OS::IThreadManager::getInstance().killThread(m_mainLoopThread); delete m_mainLoopThread; m_threadFunc = 0; m_mainLoopThread = 0; */ if (!gub_main_loop) { return; } g_main_loop_quit(gub_main_loop); gub_main_loop = NULL; g_thread_join(gub_main_loop_thread); gub_main_loop_thread = NULL; } void GStreamerCore::Ref() { m_refCount++; if (m_refCount==1) { LogManager::Instance()->LogMessage("Initializing GStreamer"); m_instance = new GStreamerCore(); LogManager::Instance()->LogMessage("Initializing GStreamer - Done"); } } void GStreamerCore::Unref() { if (m_refCount == 0) { LogMessage("GStreamerCore::Unref() - unreferencing GStreamer with no reference! ", ELL_ERROR); return; } //m_refCount--; if (m_refCount == 0) { delete m_instance; m_instance = 0; } } GStreamerCore* GStreamerCore::Instance() { return m_instance; } } } <|endoftext|>
<commit_before> <commit_msg>Removed useless file<commit_after><|endoftext|>
<commit_before>#include "PAK.hpp" #include "DNAMP3.hpp" namespace DataSpec::DNAMP3 { const hecl::FourCC CMPD("CMPD"); template <> void PAK::Enumerate<BigDNA::Read>(athena::io::IStreamReader& reader) { m_header.read(reader); if (m_header.version != 2) Log.report(logvisor::Fatal, fmt("unexpected PAK magic")); reader.seek(8, athena::SeekOrigin::Current); atUint32 strgSz = reader.readUint32Big(); reader.seek(4, athena::SeekOrigin::Current); atUint32 rshdSz = reader.readUint32Big(); reader.seek(44, athena::SeekOrigin::Current); atUint32 dataOffset = 128 + strgSz + rshdSz; atUint64 strgBase = reader.position(); atUint32 nameCount = reader.readUint32Big(); m_nameEntries.clear(); m_nameEntries.reserve(nameCount); for (atUint32 n = 0; n < nameCount; ++n) { m_nameEntries.emplace_back(); m_nameEntries.back().read(reader); } reader.seek(strgBase + strgSz, athena::SeekOrigin::Begin); atUint32 count = reader.readUint32Big(); m_entries.clear(); m_entries.reserve(count); m_firstEntries.clear(); m_firstEntries.reserve(count); std::vector<Entry> entries; entries.reserve(count); for (atUint32 e = 0; e < count; ++e) { entries.emplace_back(); entries.back().read(reader); } for (atUint32 e = 0; e < count; ++e) { Entry& entry = entries[e]; entry.offset += dataOffset; auto search = m_entries.find(entry.id); if (search == m_entries.end()) { m_firstEntries.push_back(entry.id); m_entries[entry.id] = std::move(entry); } else { /* Find next MREA to record which area has dupes */ for (atUint32 e2 = e + 1; e2 < count; ++e2) { Entry& entry2 = entries[e2]; if (entry2.type != FOURCC('MREA')) continue; m_dupeMREAs.insert(entry2.id); break; } } } m_nameMap.clear(); m_nameMap.reserve(nameCount); for (NameEntry& entry : m_nameEntries) m_nameMap[entry.name] = entry.id; } template <> void PAK::Enumerate<BigDNA::Write>(athena::io::IStreamWriter& writer) { m_header.write(writer); DNAFourCC("STRG").write(writer); atUint32 strgSz = 4; for (const NameEntry& entry : m_nameEntries) strgSz += (atUint32)entry.name.size() + 13; atUint32 strgPad = ((strgSz + 63) & ~63) - strgSz; strgSz += strgPad; writer.writeUint32Big(strgSz); DNAFourCC("RSHD").write(writer); atUint32 rshdSz = 4 + 24 * m_entries.size(); atUint32 rshdPad = ((rshdSz + 63) & ~63) - rshdSz; rshdSz += rshdPad; writer.writeUint32Big(rshdSz); atUint32 dataOffset = 128 + strgSz + rshdSz; DNAFourCC("DATA").write(writer); atUint32 dataSz = 0; for (const auto& entry : m_entries) dataSz += (entry.second.size + 63) & ~63; atUint32 dataPad = ((dataSz + 63) & ~63) - dataSz; dataSz += dataPad; writer.writeUint32Big(dataSz); writer.seek(36, athena::SeekOrigin::Current); writer.writeUint32Big((atUint32)m_nameEntries.size()); for (const NameEntry& entry : m_nameEntries) entry.write(writer); writer.seek(strgPad, athena::SeekOrigin::Current); writer.writeUint32Big((atUint32)m_entries.size()); for (const auto& entry : m_entries) { Entry copy = entry.second; copy.offset -= dataOffset; copy.write(writer); } writer.seek(rshdPad, athena::SeekOrigin::Current); } template <> void PAK::Enumerate<BigDNA::BinarySize>(size_t& __isz) { m_header.binarySize(__isz); size_t strgSz = 4; for (const NameEntry& entry : m_nameEntries) strgSz += entry.name.size() + 13; size_t strgPad = ((strgSz + 63) & ~63) - strgSz; size_t rshdSz = 4 + 24 * m_entries.size(); size_t rshdPad = ((rshdSz + 63) & ~63) - rshdSz; __isz += 60; __isz += 4; for (const NameEntry& entry : m_nameEntries) entry.binarySize(__isz); __isz += strgPad; __isz += 4; for (const auto& entry : m_entries) entry.second.binarySize(__isz); __isz += rshdPad; } std::unique_ptr<atUint8[]> PAK::Entry::getBuffer(const nod::Node& pak, atUint64& szOut) const { if (compressed) { std::unique_ptr<nod::IPartReadStream> strm = pak.beginReadStream(offset); struct { hecl::FourCC magic; atUint32 blockCount; } head; strm->read(&head, 8); if (head.magic != CMPD) { Log.report(logvisor::Error, fmt("invalid CMPD block")); return std::unique_ptr<atUint8[]>(); } head.blockCount = hecl::SBig(head.blockCount); struct Block { atUint32 compSz; atUint32 decompSz; }; std::unique_ptr<Block[]> blocks(new Block[head.blockCount]); strm->read(blocks.get(), 8 * head.blockCount); atUint64 maxBlockSz = 0; atUint64 totalDecompSz = 0; for (atUint32 b = 0; b < head.blockCount; ++b) { Block& block = blocks[b]; block.compSz = hecl::SBig(block.compSz) & 0xffffff; block.decompSz = hecl::SBig(block.decompSz); if (block.compSz > maxBlockSz) maxBlockSz = block.compSz; totalDecompSz += block.decompSz; } std::unique_ptr<atUint8[]> compBuf(new atUint8[maxBlockSz]); atUint8* buf = new atUint8[totalDecompSz]; atUint8* bufCur = buf; for (atUint32 b = 0; b < head.blockCount; ++b) { Block& block = blocks[b]; atUint8* compBufCur = compBuf.get(); strm->read(compBufCur, block.compSz); if (block.compSz == block.decompSz) { memcpy(bufCur, compBufCur, block.decompSz); bufCur += block.decompSz; } else { atUint32 rem = block.decompSz; while (rem) { atUint16 chunkSz = hecl::SBig(*(atUint16*)compBufCur); compBufCur += 2; size_t dsz; lzokay::decompress(compBufCur, chunkSz, bufCur, rem, dsz); compBufCur += chunkSz; bufCur += dsz; rem -= dsz; } } } szOut = totalDecompSz; return std::unique_ptr<atUint8[]>(buf); } else { atUint8* buf = new atUint8[size]; pak.beginReadStream(offset)->read(buf, size); szOut = size; return std::unique_ptr<atUint8[]>(buf); } } const PAK::Entry* PAK::lookupEntry(const UniqueID64& id) const { auto result = m_entries.find(id); if (result != m_entries.end()) return &result->second; return nullptr; } const PAK::Entry* PAK::lookupEntry(std::string_view name) const { auto result = m_nameMap.find(name.data()); if (result != m_nameMap.end()) { auto result1 = m_entries.find(result->second); if (result1 != m_entries.end()) return &result1->second; } return nullptr; } std::string PAK::bestEntryName(const nod::Node& pakNode, const Entry& entry, std::string& catalogueName) const { /* Prefer named entries first */ for (const NameEntry& nentry : m_nameEntries) if (nentry.id == entry.id) { catalogueName = nentry.name; return fmt::format(fmt("{}_{}"), nentry.name, entry.id); } /* Otherwise return ID format string */ return fmt::format(fmt("{}_{}"), entry.type, entry.id); } } // namespace DataSpec::DNAMP3 <commit_msg>DNAMP3/PAK: Make use of unique_ptr in getBuffer()<commit_after>#include "PAK.hpp" #include "DNAMP3.hpp" namespace DataSpec::DNAMP3 { const hecl::FourCC CMPD("CMPD"); template <> void PAK::Enumerate<BigDNA::Read>(athena::io::IStreamReader& reader) { m_header.read(reader); if (m_header.version != 2) Log.report(logvisor::Fatal, fmt("unexpected PAK magic")); reader.seek(8, athena::SeekOrigin::Current); atUint32 strgSz = reader.readUint32Big(); reader.seek(4, athena::SeekOrigin::Current); atUint32 rshdSz = reader.readUint32Big(); reader.seek(44, athena::SeekOrigin::Current); atUint32 dataOffset = 128 + strgSz + rshdSz; atUint64 strgBase = reader.position(); atUint32 nameCount = reader.readUint32Big(); m_nameEntries.clear(); m_nameEntries.reserve(nameCount); for (atUint32 n = 0; n < nameCount; ++n) { m_nameEntries.emplace_back(); m_nameEntries.back().read(reader); } reader.seek(strgBase + strgSz, athena::SeekOrigin::Begin); atUint32 count = reader.readUint32Big(); m_entries.clear(); m_entries.reserve(count); m_firstEntries.clear(); m_firstEntries.reserve(count); std::vector<Entry> entries; entries.reserve(count); for (atUint32 e = 0; e < count; ++e) { entries.emplace_back(); entries.back().read(reader); } for (atUint32 e = 0; e < count; ++e) { Entry& entry = entries[e]; entry.offset += dataOffset; auto search = m_entries.find(entry.id); if (search == m_entries.end()) { m_firstEntries.push_back(entry.id); m_entries[entry.id] = std::move(entry); } else { /* Find next MREA to record which area has dupes */ for (atUint32 e2 = e + 1; e2 < count; ++e2) { Entry& entry2 = entries[e2]; if (entry2.type != FOURCC('MREA')) continue; m_dupeMREAs.insert(entry2.id); break; } } } m_nameMap.clear(); m_nameMap.reserve(nameCount); for (NameEntry& entry : m_nameEntries) m_nameMap[entry.name] = entry.id; } template <> void PAK::Enumerate<BigDNA::Write>(athena::io::IStreamWriter& writer) { m_header.write(writer); DNAFourCC("STRG").write(writer); atUint32 strgSz = 4; for (const NameEntry& entry : m_nameEntries) strgSz += (atUint32)entry.name.size() + 13; atUint32 strgPad = ((strgSz + 63) & ~63) - strgSz; strgSz += strgPad; writer.writeUint32Big(strgSz); DNAFourCC("RSHD").write(writer); atUint32 rshdSz = 4 + 24 * m_entries.size(); atUint32 rshdPad = ((rshdSz + 63) & ~63) - rshdSz; rshdSz += rshdPad; writer.writeUint32Big(rshdSz); atUint32 dataOffset = 128 + strgSz + rshdSz; DNAFourCC("DATA").write(writer); atUint32 dataSz = 0; for (const auto& entry : m_entries) dataSz += (entry.second.size + 63) & ~63; atUint32 dataPad = ((dataSz + 63) & ~63) - dataSz; dataSz += dataPad; writer.writeUint32Big(dataSz); writer.seek(36, athena::SeekOrigin::Current); writer.writeUint32Big((atUint32)m_nameEntries.size()); for (const NameEntry& entry : m_nameEntries) entry.write(writer); writer.seek(strgPad, athena::SeekOrigin::Current); writer.writeUint32Big((atUint32)m_entries.size()); for (const auto& entry : m_entries) { Entry copy = entry.second; copy.offset -= dataOffset; copy.write(writer); } writer.seek(rshdPad, athena::SeekOrigin::Current); } template <> void PAK::Enumerate<BigDNA::BinarySize>(size_t& __isz) { m_header.binarySize(__isz); size_t strgSz = 4; for (const NameEntry& entry : m_nameEntries) strgSz += entry.name.size() + 13; size_t strgPad = ((strgSz + 63) & ~63) - strgSz; size_t rshdSz = 4 + 24 * m_entries.size(); size_t rshdPad = ((rshdSz + 63) & ~63) - rshdSz; __isz += 60; __isz += 4; for (const NameEntry& entry : m_nameEntries) entry.binarySize(__isz); __isz += strgPad; __isz += 4; for (const auto& entry : m_entries) entry.second.binarySize(__isz); __isz += rshdPad; } std::unique_ptr<atUint8[]> PAK::Entry::getBuffer(const nod::Node& pak, atUint64& szOut) const { if (compressed) { std::unique_ptr<nod::IPartReadStream> strm = pak.beginReadStream(offset); struct { hecl::FourCC magic; atUint32 blockCount; } head; strm->read(&head, 8); if (head.magic != CMPD) { Log.report(logvisor::Error, fmt("invalid CMPD block")); return nullptr; } head.blockCount = hecl::SBig(head.blockCount); struct Block { atUint32 compSz; atUint32 decompSz; }; std::unique_ptr<Block[]> blocks(new Block[head.blockCount]); strm->read(blocks.get(), 8 * head.blockCount); atUint64 maxBlockSz = 0; atUint64 totalDecompSz = 0; for (atUint32 b = 0; b < head.blockCount; ++b) { Block& block = blocks[b]; block.compSz = hecl::SBig(block.compSz) & 0xffffff; block.decompSz = hecl::SBig(block.decompSz); if (block.compSz > maxBlockSz) maxBlockSz = block.compSz; totalDecompSz += block.decompSz; } std::unique_ptr<atUint8[]> compBuf(new atUint8[maxBlockSz]); std::unique_ptr<atUint8[]> buf{new atUint8[totalDecompSz]}; atUint8* bufCur = buf.get(); for (atUint32 b = 0; b < head.blockCount; ++b) { Block& block = blocks[b]; atUint8* compBufCur = compBuf.get(); strm->read(compBufCur, block.compSz); if (block.compSz == block.decompSz) { memcpy(bufCur, compBufCur, block.decompSz); bufCur += block.decompSz; } else { atUint32 rem = block.decompSz; while (rem) { atUint16 chunkSz = hecl::SBig(*(atUint16*)compBufCur); compBufCur += 2; size_t dsz; lzokay::decompress(compBufCur, chunkSz, bufCur, rem, dsz); compBufCur += chunkSz; bufCur += dsz; rem -= dsz; } } } szOut = totalDecompSz; return buf; } else { std::unique_ptr<atUint8[]> buf{new atUint8[size]}; pak.beginReadStream(offset)->read(buf.get(), size); szOut = size; return buf; } } const PAK::Entry* PAK::lookupEntry(const UniqueID64& id) const { auto result = m_entries.find(id); if (result != m_entries.end()) return &result->second; return nullptr; } const PAK::Entry* PAK::lookupEntry(std::string_view name) const { auto result = m_nameMap.find(name.data()); if (result != m_nameMap.end()) { auto result1 = m_entries.find(result->second); if (result1 != m_entries.end()) return &result1->second; } return nullptr; } std::string PAK::bestEntryName(const nod::Node& pakNode, const Entry& entry, std::string& catalogueName) const { /* Prefer named entries first */ for (const NameEntry& nentry : m_nameEntries) if (nentry.id == entry.id) { catalogueName = nentry.name; return fmt::format(fmt("{}_{}"), nentry.name, entry.id); } /* Otherwise return ID format string */ return fmt::format(fmt("{}_{}"), entry.type, entry.id); } } // namespace DataSpec::DNAMP3 <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" #define W SkIntToScalar(80) #define H SkIntToScalar(60) typedef void (*PaintProc)(SkPaint*); static void identity_paintproc(SkPaint* paint) {} static void gradient_paintproc(SkPaint* paint) { const SkColor colors[] = { SK_ColorGREEN, SK_ColorBLUE }; const SkPoint pts[] = { { 0, 0 }, { W, H } }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode); paint->setShader(s)->unref(); } typedef void (*Proc)(SkCanvas*, const SkPaint&); static void draw_hair(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(0); canvas->drawLine(0, 0, W, H, p); } static void draw_thick(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(H/5); canvas->drawLine(0, 0, W, H, p); } static void draw_rect(SkCanvas* canvas, const SkPaint& paint) { canvas->drawRect(SkRect::MakeWH(W, H), paint); } static void draw_oval(SkCanvas* canvas, const SkPaint& paint) { canvas->drawOval(SkRect::MakeWH(W, H), paint); } static void draw_text(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setTextSize(H/4); canvas->drawText("Hamburge", 8, 0, H*2/3, p); } class SrcModeGM : public skiagm::GM { SkPath fPath; public: SrcModeGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("srcmode"); } virtual SkISize onISize() { return SkISize::Make(640, 760); } virtual void onDraw(SkCanvas* canvas) { canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); SkPaint paint; paint.setColor(0x80FF0000); const Proc procs[] = { draw_hair, draw_thick, draw_rect, draw_oval, draw_text }; const SkXfermode::Mode modes[] = { SkXfermode::kSrcOver_Mode, SkXfermode::kSrc_Mode, SkXfermode::kClear_Mode }; const PaintProc paintProcs[] = { identity_paintproc, gradient_paintproc }; for (int aa = 0; aa <= 1; ++aa) { paint.setAntiAlias(SkToBool(aa)); canvas->save(); for (size_t i = 0; i < SK_ARRAY_COUNT(paintProcs); ++i) { paintProcs[i](&paint); for (size_t x = 0; x < SK_ARRAY_COUNT(modes); ++x) { paint.setXfermodeMode(modes[x]); canvas->save(); for (size_t y = 0; y < SK_ARRAY_COUNT(procs); ++y) { procs[y](canvas, paint); canvas->translate(0, H * 5 / 4); } canvas->restore(); canvas->translate(W * 5 / 4, 0); } } canvas->restore(); canvas->translate(0, (H * 5 / 4) * SK_ARRAY_COUNT(procs)); } } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM(return new SrcModeGM;) <commit_msg>draw offscreen so we can see the alpha-channel we are writing todo: know when to use a gpu-surface<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkSurface.h" #define W SkIntToScalar(80) #define H SkIntToScalar(60) typedef void (*PaintProc)(SkPaint*); static void identity_paintproc(SkPaint* paint) {} static void gradient_paintproc(SkPaint* paint) { const SkColor colors[] = { SK_ColorGREEN, SK_ColorBLUE }; const SkPoint pts[] = { { 0, 0 }, { W, H } }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode); paint->setShader(s)->unref(); } typedef void (*Proc)(SkCanvas*, const SkPaint&); static void draw_hair(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(0); canvas->drawLine(0, 0, W, H, p); } static void draw_thick(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(H/5); canvas->drawLine(0, 0, W, H, p); } static void draw_rect(SkCanvas* canvas, const SkPaint& paint) { canvas->drawRect(SkRect::MakeWH(W, H), paint); } static void draw_oval(SkCanvas* canvas, const SkPaint& paint) { canvas->drawOval(SkRect::MakeWH(W, H), paint); } static void draw_text(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setTextSize(H/4); canvas->drawText("Hamburge", 8, 0, H*2/3, p); } class SrcModeGM : public skiagm::GM { SkPath fPath; public: SrcModeGM() { this->setBGColor(SK_ColorBLACK); } protected: virtual SkString onShortName() { return SkString("srcmode"); } virtual SkISize onISize() { return SkISize::Make(640, 760); } void drawContent(SkCanvas* canvas) { canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); SkPaint paint; paint.setColor(0x80FF0000); const Proc procs[] = { draw_hair, draw_thick, draw_rect, draw_oval, draw_text }; const SkXfermode::Mode modes[] = { SkXfermode::kSrcOver_Mode, SkXfermode::kSrc_Mode, SkXfermode::kClear_Mode }; const PaintProc paintProcs[] = { identity_paintproc, gradient_paintproc }; for (int aa = 0; aa <= 1; ++aa) { paint.setAntiAlias(SkToBool(aa)); canvas->save(); for (size_t i = 0; i < SK_ARRAY_COUNT(paintProcs); ++i) { paintProcs[i](&paint); for (size_t x = 0; x < SK_ARRAY_COUNT(modes); ++x) { paint.setXfermodeMode(modes[x]); canvas->save(); for (size_t y = 0; y < SK_ARRAY_COUNT(procs); ++y) { procs[y](canvas, paint); canvas->translate(0, H * 5 / 4); } canvas->restore(); canvas->translate(W * 5 / 4, 0); } } canvas->restore(); canvas->translate(0, (H * 5 / 4) * SK_ARRAY_COUNT(procs)); } } static SkSurface* compat_surface(SkCanvas* canvas, const SkISize& size) { SkImage::Info info = { size.width(), size.height(), SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType }; return SkSurface::NewRaster(info); } virtual void onDraw(SkCanvas* canvas) { SkAutoTUnref<SkSurface> surf(compat_surface(canvas, this->getISize())); surf->getCanvas()->drawColor(SK_ColorWHITE); this->drawContent(surf->getCanvas()); surf->draw(canvas, 0, 0, NULL); } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM(return new SrcModeGM;) <|endoftext|>
<commit_before>#include "ofApp.h" void ofApp::setup() { femurBone.load("femur.png"); images = { femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone }; angles = { 0, 0, 0, 0, 0, 0, 0, 0 }; anglesMinimum = { -360, -270, -180, -90, -80, -70, -60, -45 }; anglesMaximum = { 360, 270, 180, 90, 80, 70, 60, 45 }; anglesNoiseIncrement = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 }; anglesNoiseOffsets = { ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100) }; anglesNoiseScales = { 2, 2, 2, 2, 2, 2, 2, 2 }; isNewSegment = { false, false, false, false, false, false, false, false }; } void ofApp::update() { // Loop through all of the images! for (std::size_t i = 0; i < images.size(); ++i) { // This is how we move through the Perlin noise. We adjust the offset // just a tiny bit to get the next value in the neighborhood of noise. anglesNoiseOffsets[i] += anglesNoiseIncrement[i]; // ... next we ask for the noise at the current offset. It will be a // value between -1 and 1 for ofSignedNoise. float noiseAtOffset = ofSignedNoise(anglesNoiseOffsets[i]); // ... next we scale the noise by multiplying it by a scaler. noiseAtOffset *= anglesNoiseScales[i]; // Now add some noise to the angle. angles[i] = angles[i] + noiseAtOffset; // Now clamp the angle values to keep them in a reasonable range. angles[i] = ofClamp(angles[i], anglesMinimum[i], anglesMaximum[i]); } } void ofApp::draw() { ofBackground(0); ofSetColor(ofColor::white); ofDrawBitmapString("Press spacebar for debug mode", 20, 20); // Move our canvas (translate) ofPushMatrix(); int x = ofGetMouseX(); int y = ofGetMouseY(); ofTranslate(x, y); // Loop through all o fthe images. for (std::size_t i = 0; i < images.size(); ++i) { // If we want to have different attachment points, we must push (or not // push) a new transoformation matrix. if (isNewSegment[i]) { ofPushMatrix(); } ofRotateZDeg(angles[i]); images[i].draw(-images[i].getWidth() / 2, -images[i].getWidth() / 2); // We draw the debugging here so that it is on top of our image. if (showGrid) { drawGrid(80, 80, 10); ofDrawBitmapString(ofToString("Transform: " + ofToString(i)), 14, 14); } ofTranslate(0, images[i].getHeight()); // If we pushed a new matrix, go ahead and pop it off again. if (isNewSegment[i]) { ofPopMatrix(); } } ofPopMatrix(); } void ofApp::keyPressed(int key) { if (key == ' ') { showGrid = !showGrid; } } void ofApp::drawGrid(float width, float height, float size) { ofPushStyle(); ofNoFill(); ofSetColor(255, 60); for (int x = 0; x < width; x += size) { ofDrawLine(x, 0, x, height); } for (int y = 0; y < height; y += size) { ofDrawLine(0, y, width, y); } ofDrawRectangle(0, 0, width, height); ofSetColor(ofColor::green); ofDrawLine(0, 0, width / 2, 0); ofSetColor(ofColor::red); ofDrawLine(0, 0, 0, height / 2); ofPopStyle(); } <commit_msg>Update flailer.<commit_after>#include "ofApp.h" void ofApp::setup() { femurBone.load("femur.png"); images = { femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone }; angles = { 0, 0, 0, 0, 0, 0, 0, 0 }; anglesMinimum = { -360, -270, -180, -90, -80, -70, -60, -45 }; anglesMaximum = { 360, 270, 180, 90, 80, 70, 60, 45 }; anglesNoiseIncrement = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 }; anglesNoiseOffsets = { ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100) }; anglesNoiseScales = { 2, 2, 2, 2, 2, 2, 2, 2 }; isNewSegment = { false, false, true, false, false, false, true, true }; } void ofApp::update() { // Loop through all of the images! for (std::size_t i = 0; i < images.size(); ++i) { // This is how we move through the Perlin noise. We adjust the offset // just a tiny bit to get the next value in the neighborhood of noise. anglesNoiseOffsets[i] += anglesNoiseIncrement[i]; // ... next we ask for the noise at the current offset. It will be a // value between -1 and 1 for ofSignedNoise. float noiseAtOffset = ofSignedNoise(anglesNoiseOffsets[i]); // ... next we scale the noise by multiplying it by a scaler. noiseAtOffset *= anglesNoiseScales[i]; // Now add some noise to the angle. angles[i] = angles[i] + noiseAtOffset; // Now clamp the angle values to keep them in a reasonable range. angles[i] = ofClamp(angles[i], anglesMinimum[i], anglesMaximum[i]); } } void ofApp::draw() { ofBackground(0); ofSetColor(ofColor::white); ofDrawBitmapString("Press spacebar for debug mode", 20, 20); // Move our canvas (translate) ofPushMatrix(); int x = ofGetMouseX(); int y = ofGetMouseY(); ofTranslate(x, y); // Loop through all o fthe images. for (std::size_t i = 0; i < images.size(); ++i) { // If we want to have different attachment points, we must push (or not // push) a new transoformation matrix. if (isNewSegment[i]) { ofPushMatrix(); } ofRotateZDeg(angles[i]); images[i].draw(-images[i].getWidth() / 2, -images[i].getWidth() / 2); // We draw the debugging here so that it is on top of our image. if (showGrid) { drawGrid(80, 80, 10); ofDrawBitmapString(ofToString("Transform: " + ofToString(i)), 14, 14); } ofTranslate(0, images[i].getHeight()); // If we pushed a new matrix, go ahead and pop it off again. if (isNewSegment[i]) { ofPopMatrix(); } } ofPopMatrix(); } void ofApp::keyPressed(int key) { if (key == ' ') { showGrid = !showGrid; } } void ofApp::drawGrid(float width, float height, float size) { ofPushStyle(); ofNoFill(); ofSetColor(255, 60); for (int x = 0; x < width; x += size) { ofDrawLine(x, 0, x, height); } for (int y = 0; y < height; y += size) { ofDrawLine(0, y, width, y); } ofDrawRectangle(0, 0, width, height); ofSetColor(ofColor::green); ofDrawLine(0, 0, width / 2, 0); ofSetColor(ofColor::red); ofDrawLine(0, 0, 0, height / 2); ofPopStyle(); } <|endoftext|>
<commit_before>//include the engine code #include "../RTEngine/RTEngine.hpp" #include "../RTEngine/PhongMaterial.hpp" #include "../RTEngine/Sphere.hpp" #include "../RTEngine/Plane.hpp" #include "../RTEngine/SphericalLight.hpp" #include <cstdio> #include <png.h> using namespace RealRT; void writeBufferAsPng(std::string fileName, unsigned char *buffer, int width, int height) { std::FILE *fh = std::fopen(fileName.c_str(), "wb"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, fh); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_bytepp rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for(int i = 0; i < height; i++) rowPointers[i] = buffer + (width * i); png_write_image(png_ptr, rowPointers); png_write_end(png_ptr, NULL); std::fclose(fh); } int main(int argc, char **argv) { std::shared_ptr<RTEngine> engine = RTEngine::Instantiate(1280, 1024); Sphere s1(DiffuseRed,{-5.0,0.0,2.0}); Sphere s2(DiffuseGreen,{0.0,4.0,0.0},0.5); Sphere s3(DiffuseGreen,{0.0,2.0,0.0},0.5); Sphere s4(DiffuseGreen,{0.0,0.0,0.0},0.5); Sphere s5(ReflectiveBlue,{5.0,0.0,0.0},1.5); Plane floorobj(Mirror,{0.0,1.0,0.0},3.0); SphericalLight l1(WhiteLight,{-9.5,6.0,0.0},0.1); SphericalLight l2(WhiteLight,{0.0,6.0,-2.0},0.1); SphericalLight l3(WhiteLight,{9.5,6.0,0.0},0.1); engine->AddWorldObject(std::shared_ptr<Shape>(&floorobj)); engine->AddWorldObject(std::shared_ptr<Shape>(&s1)); engine->AddWorldObject(std::shared_ptr<Shape>(&s2)); engine->AddWorldObject(std::shared_ptr<Shape>(&s3)); engine->AddWorldObject(std::shared_ptr<Shape>(&s4)); engine->AddWorldObject(std::shared_ptr<Shape>(&s5)); engine->AddWorldObject(std::shared_ptr<Shape>(&l1)); engine->AddWorldObject(std::shared_ptr<Shape>(&l2)); engine->AddWorldObject(std::shared_ptr<Shape>(&l3)); engine->CalculateScene(); unsigned char *rendered = engine->Screen(); std::string output = "out.png"; if(argc > 1) output = argv[1]; writeBufferAsPng(output, rendered, 1280, 1024); return 0; } <commit_msg>Fixed memory errors and added raw image output<commit_after>//include the engine code #include "../RTEngine/RTEngine.hpp" #include "../RTEngine/PhongMaterial.hpp" #include "../RTEngine/Sphere.hpp" #include "../RTEngine/Plane.hpp" #include "../RTEngine/SphericalLight.hpp" #include <cstdio> #include <fstream> #include <png.h> #include <opencv2/opencv.hpp> using namespace RealRT; const int Width = 2560; const int Height = 1600; void writeBufferAsPng(std::string fileName, unsigned char *buffer, int width, int height) { std::FILE *fh = std::fopen(fileName.c_str(), "wb"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, fh); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_bytepp rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for(int i = 0; i < height; i++) rowPointers[i] = buffer + (width * i * 3); png_write_image(png_ptr, rowPointers); png_write_end(png_ptr, NULL); std::fclose(fh); } void writeBufferAsRaw(std::string fileName, unsigned char *buffer, int width, int height) { std::ofstream img(fileName + ".raw", std::ios::binary); for(int j = 0; j < height; j++) { for(int i = 0; i < width; i++) { img << buffer[((j * width) + i) * 3 + 0] << buffer[((j * width) + i) * 3 + 1] << buffer[((j * width) + i) * 3 + 2]; } } } int main(int argc, char **argv) { std::shared_ptr<RTEngine> engine = RTEngine::Instantiate(Width, Height); std::shared_ptr<Sphere> s1 = std::make_shared<Sphere>(DiffuseRed,Vector3D(-5.0,0.0,2.0)); std::shared_ptr<Sphere> s2 = std::make_shared<Sphere>(DiffuseGreen,Vector3D(0.0,4.0,0.0),0.5); std::shared_ptr<Sphere> s3 = std::make_shared<Sphere>(DiffuseGreen,Vector3D(0.0,2.0,0.0),0.5); std::shared_ptr<Sphere> s4 = std::make_shared<Sphere>(DiffuseGreen,Vector3D(0.0,0.0,0.0),0.5); std::shared_ptr<Sphere> s5 = std::make_shared<Sphere>(ReflectiveBlue,Vector3D(5.0,0.0,0.0),1.5); std::shared_ptr<Plane> floorobj = std::make_shared<Plane>(Mirror,Vector3D(0.0,1.0,0.0),3.0); std::shared_ptr<SphericalLight> l1 = std::make_shared<SphericalLight>(WhiteLight,Vector3D(-9.5,6.0,0.0),0.1); std::shared_ptr<SphericalLight> l2 = std::make_shared<SphericalLight>(WhiteLight,Vector3D(0.0,6.0,-2.0),0.1); std::shared_ptr<SphericalLight> l3 = std::make_shared<SphericalLight>(WhiteLight,Vector3D(9.5,6.0,0.0),0.1); engine->AddWorldObject(floorobj); engine->AddWorldObject(s1); engine->AddWorldObject(s2); engine->AddWorldObject(s3); engine->AddWorldObject(s4); engine->AddWorldObject(s5); engine->AddWorldObject(l1); engine->AddWorldObject(l2); engine->AddWorldObject(l3); engine->CalculateScene(); unsigned char *rendered = engine->Screen(); std::string output = "out.png"; if(argc > 1) output = argv[1]; writeBufferAsPng(output, rendered, Width, Height); return 0; } <|endoftext|>
<commit_before>/* * SessionPresentation.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ // TODO: custom code navigator for presentations // TODO: (docs) custom css mechanisms // TODO: (docs) per-slide transitions / transition speed // TODO: (docs) document rtl // TODO: (docs) columns left and right widths // TODO: (docs) use 'o' for overview // TODO: (docs) new autosize and width/height options #include "SessionPresentation.hpp" #include <boost/bind.hpp> #include <core/Exec.hpp> #include <core/http/Util.hpp> #include <core/FileSerializer.hpp> #include <core/text/TemplateFilter.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "../SessionRPubs.hpp" #include "PresentationLog.hpp" #include "PresentationState.hpp" #include "SlideRequestHandler.hpp" using namespace core; namespace session { namespace modules { namespace presentation { namespace { void showPresentation(const FilePath& filePath) { // initialize state presentation::state::init(filePath); // notify the client ClientEvent event(client_events::kShowPresentationPane, presentation::state::asJson()); module_context::enqueClientEvent(event); } SEXP rs_showPresentation(SEXP fileSEXP) { try { // validate path FilePath filePath(r::sexp::asString(fileSEXP)); if (!filePath.exists()) throw r::exec::RErrorException("File path " + filePath.absolutePath() + " does not exist."); showPresentation(filePath); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } SEXP rs_showPresentationHelpDoc(SEXP helpDocSEXP) { try { // verify a presentation is active if (!presentation::state::isActive()) { throw r::exec::RErrorException( "No presentation is currently active"); } // resolve against presentation directory std::string helpDoc = r::sexp::asString(helpDocSEXP); FilePath helpDocPath = presentation::state::directory().childPath( helpDoc); if (!helpDocPath.exists()) { throw r::exec::RErrorException("Path " + helpDocPath.absolutePath() + " not found."); } // build url and fire event std::string url = "help/presentation/?file="; std::string file = module_context::createAliasedPath(helpDocPath); url += http::util::urlEncode(file, true); ClientEvent event(client_events::kShowHelp, url); module_context::enqueClientEvent(event); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } Error setPresentationSlideIndex(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { int index = 0; Error error = json::readParam(request.params, 0, &index); if (error) return error; presentation::state::setSlideIndex(index); presentation::log().onSlideIndexChanged(index); return Success(); } Error createNewPresentation(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get file path std::string file; Error error = json::readParam(request.params, 0, &file); if (error) return error; FilePath filePath = module_context::resolveAliasedPath(file); // process template std::map<std::string,std::string> vars; vars["name"] = filePath.stem(); core::text::TemplateFilter filter(vars); // read file with template filter FilePath templatePath = session::options().rResourcesPath().complete( "templates/r_presentation.Rpres"); std::string presContents; error = core::readStringFromFile(templatePath, filter, &presContents); if (error) return error; // write file return core::writeStringToFile(filePath, presContents, string_utils::LineEndingNative); } Error showPresentationPane(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string file; Error error = json::readParam(request.params, 0, &file); if (error) return error; FilePath filePath = module_context::resolveAliasedPath(file); if (!filePath.exists()) return core::fileNotFoundError(filePath, ERROR_LOCATION); showPresentation(filePath); return Success(); } Error closePresentationPane(const json::JsonRpcRequest&, json::JsonRpcResponse*) { presentation::state::clear(); return Success(); } Error presentationExecuteCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the code std::string code; Error error = json::readParam(request.params, 0, &code); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // execute within the context of either the tutorial project directory // or presentation directory RestoreCurrentPathScope restorePathScope( module_context::safeCurrentPath()); if (presentation::state::isTutorial() && projects::projectContext().hasProject()) { error = projects::projectContext().directory().makeCurrentPath(); } else { error = presentation::state::directory().makeCurrentPath(); } if (error) return error; // actually execute the code (show error in the console) error = r::exec::executeString(code); if (error) { std::string errMsg = "Error executing code: " + code + "\n"; errMsg += r::endUserErrorMessage(error); module_context::consoleWriteError(errMsg + "\n"); } return Success(); } Error setWorkingDirectory(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { // get the path std::string path; Error error = json::readParam(request.params, 0, &path); if (error) return error; // set current path FilePath filePath = module_context::resolveAliasedPath(path); return filePath.makeCurrentPath(); } Error tutorialFeedback(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the feedback std::string feedback; Error error = json::readParam(request.params, 0, &feedback); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // record the feedback presentation::log().recordFeedback(feedback); return Success(); } Error tutorialQuizResponse(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the params int slideIndex, answer; bool correct; Error error = json::readParams(request.params, &slideIndex, &answer, &correct); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // record the feedback presentation::log().recordQuizResponse(slideIndex, answer, correct); return Success(); } Error createStandalonePresentation(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string pathParam; Error error = json::readParam(request.params, 0, &pathParam); if (error) return error; FilePath targetPath = module_context::resolveAliasedPath(pathParam); std::string errMsg; if (!savePresentationAsStandalone(targetPath, &errMsg)) { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } Error createDesktopViewInBrowserPresentation( const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // save to view in browser path FilePath targetPath = presentation::state::viewInBrowserPath(); std::string errMsg; if (savePresentationAsStandalone(targetPath, &errMsg)) { pResponse->setResult(module_context::createAliasedPath(targetPath)); } else { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } Error createPresentationRpubsSource(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // use a stable location in the presentation directory for the Rpubs // source file so that update works across sessions std::string stem = presentation::state::filePath().stem(); FilePath filePath = presentation::state::directory().childPath( stem + "-rpubs.html"); std::string errMsg; if (savePresentationAsRpubsSource(filePath, &errMsg)) { json::Object resultJson; resultJson["published"] = !rpubs::previousUploadId(filePath).empty(); resultJson["source_file_path"] = module_context::createAliasedPath( filePath); pResponse->setResult(resultJson); } else { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } } // anonymous namespace json::Value presentationStateAsJson() { return presentation::state::asJson(); } Error initialize() { // register rs_showPresentation R_CallMethodDef methodDefShowPresentation; methodDefShowPresentation.name = "rs_showPresentation" ; methodDefShowPresentation.fun = (DL_FUNC) rs_showPresentation; methodDefShowPresentation.numArgs = 1; r::routines::addCallMethod(methodDefShowPresentation); // register rs_showPresentationHelpDoc R_CallMethodDef methodDefShowHelpDoc; methodDefShowHelpDoc.name = "rs_showPresentationHelpDoc" ; methodDefShowHelpDoc.fun = (DL_FUNC) rs_showPresentationHelpDoc; methodDefShowHelpDoc.numArgs = 1; r::routines::addCallMethod(methodDefShowHelpDoc); // initialize presentation log Error error = log().initialize(); if (error) return error; using boost::bind; using namespace session::module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerUriHandler, "/presentation", handlePresentationPaneRequest)) (bind(registerRpcMethod, "create_standalone_presentation", createStandalonePresentation)) (bind(registerRpcMethod, "create_desktop_view_in_browser_presentation", createDesktopViewInBrowserPresentation)) (bind(registerRpcMethod, "create_presentation_rpubs_source", createPresentationRpubsSource)) (bind(registerRpcMethod, "set_presentation_slide_index", setPresentationSlideIndex)) (bind(registerRpcMethod, "create_new_presentation", createNewPresentation)) (bind(registerRpcMethod, "show_presentation_pane", showPresentationPane)) (bind(registerRpcMethod, "close_presentation_pane", closePresentationPane)) (bind(registerRpcMethod, "presentation_execute_code", presentationExecuteCode)) (bind(registerRpcMethod, "set_working_directory", setWorkingDirectory)) (bind(registerRpcMethod, "tutorial_feedback", tutorialFeedback)) (bind(registerRpcMethod, "tutorial_quiz_response", tutorialQuizResponse)) (bind(presentation::state::initialize)) (bind(sourceModuleRFile, "SessionPresentation.R")); return initBlock.execute(); } } // namespace presentation } // namespace modules } // namesapce session <commit_msg>update todo<commit_after>/* * SessionPresentation.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ // TODO: custom code navigator for presentations #include "SessionPresentation.hpp" #include <boost/bind.hpp> #include <core/Exec.hpp> #include <core/http/Util.hpp> #include <core/FileSerializer.hpp> #include <core/text/TemplateFilter.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include <session/projects/SessionProjects.hpp> #include "../SessionRPubs.hpp" #include "PresentationLog.hpp" #include "PresentationState.hpp" #include "SlideRequestHandler.hpp" using namespace core; namespace session { namespace modules { namespace presentation { namespace { void showPresentation(const FilePath& filePath) { // initialize state presentation::state::init(filePath); // notify the client ClientEvent event(client_events::kShowPresentationPane, presentation::state::asJson()); module_context::enqueClientEvent(event); } SEXP rs_showPresentation(SEXP fileSEXP) { try { // validate path FilePath filePath(r::sexp::asString(fileSEXP)); if (!filePath.exists()) throw r::exec::RErrorException("File path " + filePath.absolutePath() + " does not exist."); showPresentation(filePath); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } SEXP rs_showPresentationHelpDoc(SEXP helpDocSEXP) { try { // verify a presentation is active if (!presentation::state::isActive()) { throw r::exec::RErrorException( "No presentation is currently active"); } // resolve against presentation directory std::string helpDoc = r::sexp::asString(helpDocSEXP); FilePath helpDocPath = presentation::state::directory().childPath( helpDoc); if (!helpDocPath.exists()) { throw r::exec::RErrorException("Path " + helpDocPath.absolutePath() + " not found."); } // build url and fire event std::string url = "help/presentation/?file="; std::string file = module_context::createAliasedPath(helpDocPath); url += http::util::urlEncode(file, true); ClientEvent event(client_events::kShowHelp, url); module_context::enqueClientEvent(event); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } Error setPresentationSlideIndex(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { int index = 0; Error error = json::readParam(request.params, 0, &index); if (error) return error; presentation::state::setSlideIndex(index); presentation::log().onSlideIndexChanged(index); return Success(); } Error createNewPresentation(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get file path std::string file; Error error = json::readParam(request.params, 0, &file); if (error) return error; FilePath filePath = module_context::resolveAliasedPath(file); // process template std::map<std::string,std::string> vars; vars["name"] = filePath.stem(); core::text::TemplateFilter filter(vars); // read file with template filter FilePath templatePath = session::options().rResourcesPath().complete( "templates/r_presentation.Rpres"); std::string presContents; error = core::readStringFromFile(templatePath, filter, &presContents); if (error) return error; // write file return core::writeStringToFile(filePath, presContents, string_utils::LineEndingNative); } Error showPresentationPane(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string file; Error error = json::readParam(request.params, 0, &file); if (error) return error; FilePath filePath = module_context::resolveAliasedPath(file); if (!filePath.exists()) return core::fileNotFoundError(filePath, ERROR_LOCATION); showPresentation(filePath); return Success(); } Error closePresentationPane(const json::JsonRpcRequest&, json::JsonRpcResponse*) { presentation::state::clear(); return Success(); } Error presentationExecuteCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the code std::string code; Error error = json::readParam(request.params, 0, &code); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // execute within the context of either the tutorial project directory // or presentation directory RestoreCurrentPathScope restorePathScope( module_context::safeCurrentPath()); if (presentation::state::isTutorial() && projects::projectContext().hasProject()) { error = projects::projectContext().directory().makeCurrentPath(); } else { error = presentation::state::directory().makeCurrentPath(); } if (error) return error; // actually execute the code (show error in the console) error = r::exec::executeString(code); if (error) { std::string errMsg = "Error executing code: " + code + "\n"; errMsg += r::endUserErrorMessage(error); module_context::consoleWriteError(errMsg + "\n"); } return Success(); } Error setWorkingDirectory(const json::JsonRpcRequest& request, json::JsonRpcResponse*) { // get the path std::string path; Error error = json::readParam(request.params, 0, &path); if (error) return error; // set current path FilePath filePath = module_context::resolveAliasedPath(path); return filePath.makeCurrentPath(); } Error tutorialFeedback(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the feedback std::string feedback; Error error = json::readParam(request.params, 0, &feedback); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // record the feedback presentation::log().recordFeedback(feedback); return Success(); } Error tutorialQuizResponse(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get the params int slideIndex, answer; bool correct; Error error = json::readParams(request.params, &slideIndex, &answer, &correct); if (error) return error; // confirm we are active if (!presentation::state::isActive()) { pResponse->setError(json::errc::MethodUnexpected); return Success(); } // record the feedback presentation::log().recordQuizResponse(slideIndex, answer, correct); return Success(); } Error createStandalonePresentation(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string pathParam; Error error = json::readParam(request.params, 0, &pathParam); if (error) return error; FilePath targetPath = module_context::resolveAliasedPath(pathParam); std::string errMsg; if (!savePresentationAsStandalone(targetPath, &errMsg)) { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } Error createDesktopViewInBrowserPresentation( const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // save to view in browser path FilePath targetPath = presentation::state::viewInBrowserPath(); std::string errMsg; if (savePresentationAsStandalone(targetPath, &errMsg)) { pResponse->setResult(module_context::createAliasedPath(targetPath)); } else { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } Error createPresentationRpubsSource(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // use a stable location in the presentation directory for the Rpubs // source file so that update works across sessions std::string stem = presentation::state::filePath().stem(); FilePath filePath = presentation::state::directory().childPath( stem + "-rpubs.html"); std::string errMsg; if (savePresentationAsRpubsSource(filePath, &errMsg)) { json::Object resultJson; resultJson["published"] = !rpubs::previousUploadId(filePath).empty(); resultJson["source_file_path"] = module_context::createAliasedPath( filePath); pResponse->setResult(resultJson); } else { pResponse->setError(systemError(boost::system::errc::io_error, ERROR_LOCATION), json::toJsonString(errMsg)); } return Success(); } } // anonymous namespace json::Value presentationStateAsJson() { return presentation::state::asJson(); } Error initialize() { // register rs_showPresentation R_CallMethodDef methodDefShowPresentation; methodDefShowPresentation.name = "rs_showPresentation" ; methodDefShowPresentation.fun = (DL_FUNC) rs_showPresentation; methodDefShowPresentation.numArgs = 1; r::routines::addCallMethod(methodDefShowPresentation); // register rs_showPresentationHelpDoc R_CallMethodDef methodDefShowHelpDoc; methodDefShowHelpDoc.name = "rs_showPresentationHelpDoc" ; methodDefShowHelpDoc.fun = (DL_FUNC) rs_showPresentationHelpDoc; methodDefShowHelpDoc.numArgs = 1; r::routines::addCallMethod(methodDefShowHelpDoc); // initialize presentation log Error error = log().initialize(); if (error) return error; using boost::bind; using namespace session::module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerUriHandler, "/presentation", handlePresentationPaneRequest)) (bind(registerRpcMethod, "create_standalone_presentation", createStandalonePresentation)) (bind(registerRpcMethod, "create_desktop_view_in_browser_presentation", createDesktopViewInBrowserPresentation)) (bind(registerRpcMethod, "create_presentation_rpubs_source", createPresentationRpubsSource)) (bind(registerRpcMethod, "set_presentation_slide_index", setPresentationSlideIndex)) (bind(registerRpcMethod, "create_new_presentation", createNewPresentation)) (bind(registerRpcMethod, "show_presentation_pane", showPresentationPane)) (bind(registerRpcMethod, "close_presentation_pane", closePresentationPane)) (bind(registerRpcMethod, "presentation_execute_code", presentationExecuteCode)) (bind(registerRpcMethod, "set_working_directory", setWorkingDirectory)) (bind(registerRpcMethod, "tutorial_feedback", tutorialFeedback)) (bind(registerRpcMethod, "tutorial_quiz_response", tutorialQuizResponse)) (bind(presentation::state::initialize)) (bind(sourceModuleRFile, "SessionPresentation.R")); return initBlock.execute(); } } // namespace presentation } // namespace modules } // namesapce session <|endoftext|>
<commit_before>#include "stdafx.h" #include "ScriptWindow.h" #include "Editor.h" void ScriptWindow::Create(EditorComponent* _editor) { editor = _editor; wi::gui::Window::Create(ICON_SCRIPT " Script", wi::gui::Window::WindowControls::COLLAPSE | wi::gui::Window::WindowControls::CLOSE); SetSize(XMFLOAT2(520, 80)); closeButton.SetTooltip("Delete Script"); OnClose([=](wi::gui::EventArgs args) { wi::Archive& archive = editor->AdvanceHistory(); archive << EditorComponent::HISTORYOP_COMPONENT_DATA; editor->RecordEntity(archive, entity); editor->GetCurrentScene().scripts.Remove(entity); editor->RecordEntity(archive, entity); editor->optionsWnd.RefreshEntityTree(); }); float hei = 20; float wid = 100; fileButton.Create("Open File..."); fileButton.SetDescription("File: "); fileButton.SetSize(XMFLOAT2(wid, hei)); fileButton.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; if (script->resource.IsValid()) { script->resource = {}; script->filename = {}; script->script = {}; fileButton.SetText("Open File..."); } else { wi::helper::FileDialogParams params; params.type = wi::helper::FileDialogParams::OPEN; params.description = "Lua Script (*.lua)"; params.extensions = wi::resourcemanager::GetSupportedScriptExtensions(); wi::helper::FileDialog(params, [=](std::string fileName) { wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { script->CreateFromFile(fileName); fileButton.SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } }); AddWidget(&fileButton); playonceCheckBox.Create("Once: "); playonceCheckBox.SetTooltip("Play the script only one time, and stop immediately.\nUseful for having custom update frequency logic in the script."); playonceCheckBox.SetSize(XMFLOAT2(hei, hei)); playonceCheckBox.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; script->SetPlayOnce(args.bValue); }); AddWidget(&playonceCheckBox); playstopButton.Create(""); playstopButton.SetTooltip("Play / Stop script"); playstopButton.SetSize(XMFLOAT2(wid, hei)); playstopButton.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; if (script->IsPlaying()) { script->Stop(); } else { script->Play(); } }); AddWidget(&playstopButton); SetMinimized(true); SetVisible(false); } void ScriptWindow::SetEntity(wi::ecs::Entity entity) { if (this->entity == entity) return; this->entity = entity; wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr) { if (script->resource.IsValid()) { fileButton.SetText(wi::helper::GetFileNameFromPath(script->filename)); } else { fileButton.SetText("Open File..."); } playonceCheckBox.SetCheck(script->IsPlayingOnlyOnce()); } } void ScriptWindow::Update(const wi::Canvas& canvas, float dt) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr) { if (script->IsPlaying()) { playstopButton.SetText(ICON_STOP); } else { playstopButton.SetText(ICON_PLAY); } } wi::gui::Window::Update(canvas, dt); } void ScriptWindow::ResizeLayout() { wi::gui::Window::ResizeLayout(); fileButton.SetPos(XMFLOAT2(60, 4)); fileButton.SetSize(XMFLOAT2(GetSize().x - 65, fileButton.GetSize().y)); wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr && script->resource.IsValid()) { playstopButton.SetVisible(true); playstopButton.SetPos(XMFLOAT2(84, fileButton.GetPos().y + fileButton.GetSize().y + 4)); playstopButton.SetSize(XMFLOAT2(GetSize().x - 90, playstopButton.GetSize().y)); playonceCheckBox.SetVisible(true); playonceCheckBox.SetPos(XMFLOAT2(playstopButton.GetPos().x - playonceCheckBox.GetSize().x - 4, playstopButton.GetPos().y)); } else { playstopButton.SetVisible(false); playonceCheckBox.SetVisible(false); } } <commit_msg>editor: script window file name stuck fix<commit_after>#include "stdafx.h" #include "ScriptWindow.h" #include "Editor.h" void ScriptWindow::Create(EditorComponent* _editor) { editor = _editor; wi::gui::Window::Create(ICON_SCRIPT " Script", wi::gui::Window::WindowControls::COLLAPSE | wi::gui::Window::WindowControls::CLOSE); SetSize(XMFLOAT2(520, 80)); closeButton.SetTooltip("Delete Script"); OnClose([=](wi::gui::EventArgs args) { wi::Archive& archive = editor->AdvanceHistory(); archive << EditorComponent::HISTORYOP_COMPONENT_DATA; editor->RecordEntity(archive, entity); editor->GetCurrentScene().scripts.Remove(entity); editor->RecordEntity(archive, entity); editor->optionsWnd.RefreshEntityTree(); }); float hei = 20; float wid = 100; fileButton.Create("Open File..."); fileButton.SetDescription("File: "); fileButton.SetSize(XMFLOAT2(wid, hei)); fileButton.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; if (script->resource.IsValid()) { script->resource = {}; script->filename = {}; script->script = {}; fileButton.SetText("Open File..."); } else { wi::helper::FileDialogParams params; params.type = wi::helper::FileDialogParams::OPEN; params.description = "Lua Script (*.lua)"; params.extensions = wi::resourcemanager::GetSupportedScriptExtensions(); wi::helper::FileDialog(params, [=](std::string fileName) { wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { script->CreateFromFile(fileName); fileButton.SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } }); AddWidget(&fileButton); playonceCheckBox.Create("Once: "); playonceCheckBox.SetTooltip("Play the script only one time, and stop immediately.\nUseful for having custom update frequency logic in the script."); playonceCheckBox.SetSize(XMFLOAT2(hei, hei)); playonceCheckBox.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; script->SetPlayOnce(args.bValue); }); AddWidget(&playonceCheckBox); playstopButton.Create(""); playstopButton.SetTooltip("Play / Stop script"); playstopButton.SetSize(XMFLOAT2(wid, hei)); playstopButton.OnClick([=](wi::gui::EventArgs args) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script == nullptr) return; if (script->IsPlaying()) { script->Stop(); } else { script->Play(); } }); AddWidget(&playstopButton); SetMinimized(true); SetVisible(false); } void ScriptWindow::SetEntity(wi::ecs::Entity entity) { this->entity = entity; wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr) { if (script->resource.IsValid()) { fileButton.SetText(wi::helper::GetFileNameFromPath(script->filename)); } else { fileButton.SetText("Open File..."); } playonceCheckBox.SetCheck(script->IsPlayingOnlyOnce()); } else { fileButton.SetText("Open File..."); } } void ScriptWindow::Update(const wi::Canvas& canvas, float dt) { wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr) { if (script->IsPlaying()) { playstopButton.SetText(ICON_STOP); } else { playstopButton.SetText(ICON_PLAY); } } wi::gui::Window::Update(canvas, dt); } void ScriptWindow::ResizeLayout() { wi::gui::Window::ResizeLayout(); fileButton.SetPos(XMFLOAT2(60, 4)); fileButton.SetSize(XMFLOAT2(GetSize().x - 65, fileButton.GetSize().y)); wi::scene::Scene& scene = editor->GetCurrentScene(); wi::scene::ScriptComponent* script = scene.scripts.GetComponent(entity); if (script != nullptr && script->resource.IsValid()) { playstopButton.SetVisible(true); playstopButton.SetPos(XMFLOAT2(84, fileButton.GetPos().y + fileButton.GetSize().y + 4)); playstopButton.SetSize(XMFLOAT2(GetSize().x - 90, playstopButton.GetSize().y)); playonceCheckBox.SetVisible(true); playonceCheckBox.SetPos(XMFLOAT2(playstopButton.GetPos().x - playonceCheckBox.GetSize().x - 4, playstopButton.GetPos().y)); } else { playstopButton.SetVisible(false); playonceCheckBox.SetVisible(false); } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 "mextensionhandleview.h" #include "mextensionhandleview_p.h" #include "maction.h" #include "mappletsharedmutex.h" #include "mprogressindicator.h" #include "mmessagebox.h" #include "mlocale.h" #include "mbutton.h" #include "mappletsettingsdialog.h" #include "mappletsettings.h" #include "mscenemanager.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif static void destroySharedXPixmap(QPixmap *qPixmap) { if (qPixmap != NULL) { #ifdef Q_WS_X11 Pixmap xPixmap = qPixmap->handle(); delete qPixmap; if (xPixmap != 0) { XFreePixmap(QX11Info::display(), xPixmap); } #endif } } MExtensionHandleViewPrivate::MExtensionHandleViewPrivate(MExtensionHandle *handle) : controller(handle), handle(handle), pixmapTakenIntoUse(NULL), pixmapToBeTakenIntoUse(NULL), pixmapSizeToBeTakenIntoUse(NULL), progressIndicator(new MProgressIndicator(handle)), q_ptr(NULL) { // The progress indicator is not visible by default progressIndicator->setVisible(false); } MExtensionHandleViewPrivate::~MExtensionHandleViewPrivate() { destroyPixmaps(); } void MExtensionHandleViewPrivate::connectSignals() { Q_Q(MExtensionHandleView); // Listen for pixmap taken into use signals QObject::connect(handle, SIGNAL(pixmapTakenIntoUse(Qt::HANDLE)), q, SLOT(pixmapTakenIntoUse(Qt::HANDLE))); // Listen for scene changed signals QObject::connect(handle, SIGNAL(pixmapModified(QRectF)), q, SLOT(pixmapModified(QRectF))); } void MExtensionHandleViewPrivate::destroyPixmaps() { if (pixmapTakenIntoUse != NULL) { destroySharedXPixmap(pixmapTakenIntoUse); pixmapTakenIntoUse = NULL; } if (pixmapToBeTakenIntoUse != NULL) { destroySharedXPixmap(pixmapToBeTakenIntoUse); pixmapToBeTakenIntoUse = NULL; } } void MExtensionHandleViewPrivate::resetView() { destroyPixmaps(); // Reset the old geometry to force the pixmap ID to be sent to the remote process oldGeometry = QRectF(); } void MExtensionHandleViewPrivate::drawBrokenState() { Q_Q(MExtensionHandleView); q->update(); } QSizeF MExtensionHandleViewPrivate::hostToRemoteCoordinates(const QSizeF &size) const { Q_Q(const MExtensionHandleView); return size / q->model()->scale(); } QSizeF MExtensionHandleViewPrivate::remoteToHostCoordinates(const QSizeF &size) const { Q_Q(const MExtensionHandleView); return size * q->model()->scale(); } void MExtensionHandleViewPrivate::calculateScale() { Q_Q(MExtensionHandleView); // Set a scaling factor if the minimum width is larger than the available width const MExtensionHandleStyleContainer *handleStyle = dynamic_cast<const MExtensionHandleStyleContainer *>(&q->style()); if (handleStyle != NULL) { qreal minimumWidth = q->model()->sizeHints().at(Qt::MinimumSize).width(); qreal availableWidth = (*handleStyle)->forcedMaximumSize().width(); q->model()->setScale(minimumWidth > availableWidth ? availableWidth / minimumWidth : 1); } } void MExtensionHandleViewPrivate::sizeChanged(QSizeF size) { if (pixmapToBeTakenIntoUse == NULL) { // The pixmap to be taken into use has been taken into use. A new one can be allocated allocatePixmapToBeTakenIntoUse(size); } else { // The pixmap to be taken into use has not been taken into use. // The new size should be taken into use when the pixmap has been taken into use. delete pixmapSizeToBeTakenIntoUse; pixmapSizeToBeTakenIntoUse = new QSizeF(size); } } void MExtensionHandleViewPrivate::allocatePixmapToBeTakenIntoUse(QSizeF size) { #ifdef Q_WS_X11 // Allocate a new pixmap to be taken into use QSizeF pixmapSize = size.expandedTo(QSizeF(1, 1)); Pixmap pixmap = XCreatePixmap(QX11Info::display(), QX11Info::appRootWindow(), pixmapSize.width(), pixmapSize.height(), QX11Info::appDepth()); QApplication::syncX(); pixmapToBeTakenIntoUse = new QPixmap(); *pixmapToBeTakenIntoUse = QPixmap::fromX11Pixmap(pixmap, QPixmap::ExplicitlyShared); // Clear the pixmap QPainter painter(pixmapToBeTakenIntoUse); painter.setCompositionMode(QPainter::CompositionMode_Clear); painter.fillRect(pixmapToBeTakenIntoUse->rect(), QColor(0, 0, 0, 0)); // Communicate the new geometry and pixmap handle to be taken into use to the runner handle->sendGeometryMessage(QRectF(QPointF(), pixmapSize), pixmapToBeTakenIntoUse->handle()); #endif } void MExtensionHandleViewPrivate::updateLocalPixmap() { if (!pixmapModifiedRect.isEmpty() && pixmapTakenIntoUse != NULL && !pixmapTakenIntoUse->isNull()) { Q_Q(MExtensionHandleView); // Get the address of the pixmap mutex in shared memory and lock the mutex MAppletSharedMutex *mutex = q->model()->pixmapMutex(); if (mutex != NULL && mutex->tryLock()) { // Mutex locked: copy the changed pixmap area to the local pixmap if (!localPixmap.isNull()) { QPainter painter(&localPixmap); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.drawPixmap(pixmapModifiedRect, *pixmapTakenIntoUse, pixmapModifiedRect); } // Unlock the pixmap mutex mutex->unlock(); // Update the changed region q->update(pixmapModifiedRect); // No modifications pending anymore pixmapModifiedRect = QRectF(); } } } MExtensionHandleView::MExtensionHandleView(MExtensionHandleViewPrivate &dd, MExtensionHandle *handle) : MWidgetView(handle), d_ptr(&dd) { Q_D(MExtensionHandleView); d->q_ptr = this; d->connectSignals(); } MExtensionHandleView::~MExtensionHandleView() { } void MExtensionHandleView::setupModel() { MWidgetView::setupModel(); // Let the view know what's the state of the model QList<const char *> m; m << MExtensionHandleModel::Scale; m << MExtensionHandleModel::CurrentState; m << MExtensionHandleModel::InstallationProgress; updateData(m); } void MExtensionHandleView::updateData(const QList<const char *>& modifications) { Q_D(MExtensionHandleView); MWidgetView::updateData(modifications); const char *member; foreach(member, modifications) { if (member == MExtensionHandleModel::CurrentState) { switch (model()->currentState()) { case MExtensionHandleModel::INSTALLING: d->progressIndicator->setViewType(MProgressIndicator::barType); d->progressIndicator->setRange(0, 100); d->progressIndicator->setVisible(true); d->progressIndicator->setUnknownDuration(false); d->progressIndicator->setValue(model()->installationProgress()); break; case MExtensionHandleModel::BROKEN: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); d->drawBrokenState(); break; case MExtensionHandleModel::STARTING: d->progressIndicator->setVisible(true); d->progressIndicator->setUnknownDuration(true); break; case MExtensionHandleModel::STOPPED: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); break; case MExtensionHandleModel::RUNNING: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); d->resetView(); break; } } else if (member == MExtensionHandleModel::InstallationProgress) { d->progressIndicator->setValue(model()->installationProgress()); } } } void MExtensionHandleView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *) const { Q_D(const MExtensionHandleView); if (!d->localPixmap.isNull()) { // If there are modifications to be copied to the local pixmap try to copy them if (!d->pixmapModifiedRect.isEmpty()) { const_cast<MExtensionHandleViewPrivate *>(d)->updateLocalPixmap(); } bool brokenState = model()->currentState() == MExtensionHandleModel::BROKEN || model()->currentState() == MExtensionHandleModel::STARTING; if (brokenState) { // In broken state use a specific opacity painter->setOpacity(style()->brokenOpacity()); } // Draw the pixmap QRectF source(d->localPixmap.rect()); QRectF destination(QPointF(), d->remoteToHostCoordinates(d->localPixmap.size())); d->drawPixmap(painter, source, destination, brokenState); } if (model()->currentState() == MExtensionHandleModel::BROKEN) { const QPixmap *brokenImage = style()->brokenImage(); if (brokenImage != NULL) { QPoint p(size().width() - brokenImage->width(), 0); p += style()->brokenImageOffset(); painter->setOpacity(1.0f); painter->drawPixmap(p, *brokenImage); } } } void MExtensionHandleView::setGeometry(const QRectF &rect) { Q_D(MExtensionHandleView); // rect is always between minimum and maximum size because the size hints have been // bounded to these limits; calculate scaling factor if even the minimum size won't fit d->calculateScale(); // Get the old size and the new size QSizeF oldSize = d->hostToRemoteCoordinates(d->oldGeometry.size()); QSizeF newSize = d->hostToRemoteCoordinates(rect.size()); // Apply the geometry locally immediately MWidgetView::setGeometry(rect); d->oldGeometry = rect; // Check whether the new size differs from the old size if (newSize != oldSize) { d->sizeChanged(newSize); } // Set the progress indicator position QRectF progressIndicatorRect; progressIndicatorRect.setSize(rect.size() * 0.5f); progressIndicatorRect.moveCenter(rect.center() - rect.topLeft()); d->progressIndicator->setGeometry(progressIndicatorRect); } QRectF MExtensionHandleView::boundingRect() const { Q_D(const MExtensionHandleView); // Use the (downscaled) size as the bounding rectangle return QRectF(QPointF(), d->remoteToHostCoordinates(d->localPixmap.size()).expandedTo(style()->forcedMinimumSize()).boundedTo(style()->forcedMaximumSize())); } void MExtensionHandleView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(MExtensionHandleView); // TODO: this should actually be handled by a mouse click, but at the // moment the base class doesn't contain such method... if (event->button() == Qt::LeftButton) { if (model()->currentState() == MExtensionHandleModel::BROKEN && model()->installationError().isEmpty()) { d->showBrokenDialog(); } else if (model()->currentState() == MExtensionHandleModel::BROKEN && !model()->installationError().isEmpty()) { d->showInstallationFailedDialog(model()->installationError()); } } } void MExtensionHandleView::pixmapTakenIntoUse(Qt::HANDLE) { Q_D(MExtensionHandleView); // Delete the pixmap that was in use destroySharedXPixmap(d->pixmapTakenIntoUse); // Mark the new one as taken into use d->pixmapTakenIntoUse = d->pixmapToBeTakenIntoUse; d->pixmapToBeTakenIntoUse = NULL; d->localPixmap = d->pixmapTakenIntoUse->copy(); if (d->pixmapSizeToBeTakenIntoUse != NULL) { // The pixmap has not been resized to the latest requested size so do it now d->sizeChanged(*d->pixmapSizeToBeTakenIntoUse); // Size taken into use delete d->pixmapSizeToBeTakenIntoUse; d->pixmapSizeToBeTakenIntoUse = NULL; } } QSizeF MExtensionHandleView::sizeHint(Qt::SizeHint which, const QSizeF &) const { Q_D(const MExtensionHandleView); // Return the requested size hint bounded to forced minimum and maximum sizes defined in the style return d->remoteToHostCoordinates(model()->sizeHints().at(which)).expandedTo(style()->forcedMinimumSize()).boundedTo(style()->forcedMaximumSize()); } void MExtensionHandleView::pixmapModified(const QRectF &rect) { Q_D(MExtensionHandleView); // Unite the changed rectangle with the previous changed rectangle d->pixmapModifiedRect = rect.united(d->pixmapModifiedRect); // Update the local pixmap d->updateLocalPixmap(); } <commit_msg>Fixes: NB#242110 - <memleak> Memory leak reported in mextensionhandleview.cpp while running valgrind on libmeegotouch-tests<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 "mextensionhandleview.h" #include "mextensionhandleview_p.h" #include "maction.h" #include "mappletsharedmutex.h" #include "mprogressindicator.h" #include "mmessagebox.h" #include "mlocale.h" #include "mbutton.h" #include "mappletsettingsdialog.h" #include "mappletsettings.h" #include "mscenemanager.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif static void destroySharedXPixmap(QPixmap *qPixmap) { if (qPixmap != NULL) { #ifdef Q_WS_X11 Pixmap xPixmap = qPixmap->handle(); delete qPixmap; if (xPixmap != 0) { XFreePixmap(QX11Info::display(), xPixmap); } #endif } } MExtensionHandleViewPrivate::MExtensionHandleViewPrivate(MExtensionHandle *handle) : controller(handle), handle(handle), pixmapTakenIntoUse(NULL), pixmapToBeTakenIntoUse(NULL), pixmapSizeToBeTakenIntoUse(NULL), progressIndicator(new MProgressIndicator(handle)), q_ptr(NULL) { // The progress indicator is not visible by default progressIndicator->setVisible(false); } MExtensionHandleViewPrivate::~MExtensionHandleViewPrivate() { destroyPixmaps(); } void MExtensionHandleViewPrivate::connectSignals() { Q_Q(MExtensionHandleView); // Listen for pixmap taken into use signals QObject::connect(handle, SIGNAL(pixmapTakenIntoUse(Qt::HANDLE)), q, SLOT(pixmapTakenIntoUse(Qt::HANDLE))); // Listen for scene changed signals QObject::connect(handle, SIGNAL(pixmapModified(QRectF)), q, SLOT(pixmapModified(QRectF))); } void MExtensionHandleViewPrivate::destroyPixmaps() { if (pixmapTakenIntoUse != NULL) { destroySharedXPixmap(pixmapTakenIntoUse); pixmapTakenIntoUse = NULL; } if (pixmapToBeTakenIntoUse != NULL) { destroySharedXPixmap(pixmapToBeTakenIntoUse); pixmapToBeTakenIntoUse = NULL; } } void MExtensionHandleViewPrivate::resetView() { destroyPixmaps(); // Reset the old geometry to force the pixmap ID to be sent to the remote process oldGeometry = QRectF(); } void MExtensionHandleViewPrivate::drawBrokenState() { Q_Q(MExtensionHandleView); q->update(); } QSizeF MExtensionHandleViewPrivate::hostToRemoteCoordinates(const QSizeF &size) const { Q_Q(const MExtensionHandleView); return size / q->model()->scale(); } QSizeF MExtensionHandleViewPrivate::remoteToHostCoordinates(const QSizeF &size) const { Q_Q(const MExtensionHandleView); return size * q->model()->scale(); } void MExtensionHandleViewPrivate::calculateScale() { Q_Q(MExtensionHandleView); // Set a scaling factor if the minimum width is larger than the available width const MExtensionHandleStyleContainer *handleStyle = dynamic_cast<const MExtensionHandleStyleContainer *>(&q->style()); if (handleStyle != NULL) { qreal minimumWidth = q->model()->sizeHints().at(Qt::MinimumSize).width(); qreal availableWidth = (*handleStyle)->forcedMaximumSize().width(); q->model()->setScale(minimumWidth > availableWidth ? availableWidth / minimumWidth : 1); } } void MExtensionHandleViewPrivate::sizeChanged(QSizeF size) { if (pixmapToBeTakenIntoUse == NULL) { // The pixmap to be taken into use has been taken into use. A new one can be allocated allocatePixmapToBeTakenIntoUse(size); } else { // The pixmap to be taken into use has not been taken into use. // The new size should be taken into use when the pixmap has been taken into use. delete pixmapSizeToBeTakenIntoUse; pixmapSizeToBeTakenIntoUse = new QSizeF(size); } } void MExtensionHandleViewPrivate::allocatePixmapToBeTakenIntoUse(QSizeF size) { #ifdef Q_WS_X11 // Allocate a new pixmap to be taken into use QSizeF pixmapSize = size.expandedTo(QSizeF(1, 1)); Pixmap pixmap = XCreatePixmap(QX11Info::display(), QX11Info::appRootWindow(), pixmapSize.width(), pixmapSize.height(), QX11Info::appDepth()); QApplication::syncX(); pixmapToBeTakenIntoUse = new QPixmap(); *pixmapToBeTakenIntoUse = QPixmap::fromX11Pixmap(pixmap, QPixmap::ExplicitlyShared); // Clear the pixmap QPainter painter(pixmapToBeTakenIntoUse); painter.setCompositionMode(QPainter::CompositionMode_Clear); painter.fillRect(pixmapToBeTakenIntoUse->rect(), QColor(0, 0, 0, 0)); // Communicate the new geometry and pixmap handle to be taken into use to the runner handle->sendGeometryMessage(QRectF(QPointF(), pixmapSize), pixmapToBeTakenIntoUse->handle()); #endif } void MExtensionHandleViewPrivate::updateLocalPixmap() { if (!pixmapModifiedRect.isEmpty() && pixmapTakenIntoUse != NULL && !pixmapTakenIntoUse->isNull()) { Q_Q(MExtensionHandleView); // Get the address of the pixmap mutex in shared memory and lock the mutex MAppletSharedMutex *mutex = q->model()->pixmapMutex(); if (mutex != NULL && mutex->tryLock()) { // Mutex locked: copy the changed pixmap area to the local pixmap if (!localPixmap.isNull()) { QPainter painter(&localPixmap); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.drawPixmap(pixmapModifiedRect, *pixmapTakenIntoUse, pixmapModifiedRect); } // Unlock the pixmap mutex mutex->unlock(); // Update the changed region q->update(pixmapModifiedRect); // No modifications pending anymore pixmapModifiedRect = QRectF(); } } } MExtensionHandleView::MExtensionHandleView(MExtensionHandleViewPrivate &dd, MExtensionHandle *handle) : MWidgetView(handle), d_ptr(&dd) { Q_D(MExtensionHandleView); d->q_ptr = this; d->connectSignals(); } MExtensionHandleView::~MExtensionHandleView() { delete d_ptr; } void MExtensionHandleView::setupModel() { MWidgetView::setupModel(); // Let the view know what's the state of the model QList<const char *> m; m << MExtensionHandleModel::Scale; m << MExtensionHandleModel::CurrentState; m << MExtensionHandleModel::InstallationProgress; updateData(m); } void MExtensionHandleView::updateData(const QList<const char *>& modifications) { Q_D(MExtensionHandleView); MWidgetView::updateData(modifications); const char *member; foreach(member, modifications) { if (member == MExtensionHandleModel::CurrentState) { switch (model()->currentState()) { case MExtensionHandleModel::INSTALLING: d->progressIndicator->setViewType(MProgressIndicator::barType); d->progressIndicator->setRange(0, 100); d->progressIndicator->setVisible(true); d->progressIndicator->setUnknownDuration(false); d->progressIndicator->setValue(model()->installationProgress()); break; case MExtensionHandleModel::BROKEN: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); d->drawBrokenState(); break; case MExtensionHandleModel::STARTING: d->progressIndicator->setVisible(true); d->progressIndicator->setUnknownDuration(true); break; case MExtensionHandleModel::STOPPED: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); break; case MExtensionHandleModel::RUNNING: d->progressIndicator->setVisible(false); d->progressIndicator->setUnknownDuration(false); d->resetView(); break; } } else if (member == MExtensionHandleModel::InstallationProgress) { d->progressIndicator->setValue(model()->installationProgress()); } } } void MExtensionHandleView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *) const { Q_D(const MExtensionHandleView); if (!d->localPixmap.isNull()) { // If there are modifications to be copied to the local pixmap try to copy them if (!d->pixmapModifiedRect.isEmpty()) { const_cast<MExtensionHandleViewPrivate *>(d)->updateLocalPixmap(); } bool brokenState = model()->currentState() == MExtensionHandleModel::BROKEN || model()->currentState() == MExtensionHandleModel::STARTING; if (brokenState) { // In broken state use a specific opacity painter->setOpacity(style()->brokenOpacity()); } // Draw the pixmap QRectF source(d->localPixmap.rect()); QRectF destination(QPointF(), d->remoteToHostCoordinates(d->localPixmap.size())); d->drawPixmap(painter, source, destination, brokenState); } if (model()->currentState() == MExtensionHandleModel::BROKEN) { const QPixmap *brokenImage = style()->brokenImage(); if (brokenImage != NULL) { QPoint p(size().width() - brokenImage->width(), 0); p += style()->brokenImageOffset(); painter->setOpacity(1.0f); painter->drawPixmap(p, *brokenImage); } } } void MExtensionHandleView::setGeometry(const QRectF &rect) { Q_D(MExtensionHandleView); // rect is always between minimum and maximum size because the size hints have been // bounded to these limits; calculate scaling factor if even the minimum size won't fit d->calculateScale(); // Get the old size and the new size QSizeF oldSize = d->hostToRemoteCoordinates(d->oldGeometry.size()); QSizeF newSize = d->hostToRemoteCoordinates(rect.size()); // Apply the geometry locally immediately MWidgetView::setGeometry(rect); d->oldGeometry = rect; // Check whether the new size differs from the old size if (newSize != oldSize) { d->sizeChanged(newSize); } // Set the progress indicator position QRectF progressIndicatorRect; progressIndicatorRect.setSize(rect.size() * 0.5f); progressIndicatorRect.moveCenter(rect.center() - rect.topLeft()); d->progressIndicator->setGeometry(progressIndicatorRect); } QRectF MExtensionHandleView::boundingRect() const { Q_D(const MExtensionHandleView); // Use the (downscaled) size as the bounding rectangle return QRectF(QPointF(), d->remoteToHostCoordinates(d->localPixmap.size()).expandedTo(style()->forcedMinimumSize()).boundedTo(style()->forcedMaximumSize())); } void MExtensionHandleView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(MExtensionHandleView); // TODO: this should actually be handled by a mouse click, but at the // moment the base class doesn't contain such method... if (event->button() == Qt::LeftButton) { if (model()->currentState() == MExtensionHandleModel::BROKEN && model()->installationError().isEmpty()) { d->showBrokenDialog(); } else if (model()->currentState() == MExtensionHandleModel::BROKEN && !model()->installationError().isEmpty()) { d->showInstallationFailedDialog(model()->installationError()); } } } void MExtensionHandleView::pixmapTakenIntoUse(Qt::HANDLE) { Q_D(MExtensionHandleView); // Delete the pixmap that was in use destroySharedXPixmap(d->pixmapTakenIntoUse); // Mark the new one as taken into use d->pixmapTakenIntoUse = d->pixmapToBeTakenIntoUse; d->pixmapToBeTakenIntoUse = NULL; d->localPixmap = d->pixmapTakenIntoUse->copy(); if (d->pixmapSizeToBeTakenIntoUse != NULL) { // The pixmap has not been resized to the latest requested size so do it now d->sizeChanged(*d->pixmapSizeToBeTakenIntoUse); // Size taken into use delete d->pixmapSizeToBeTakenIntoUse; d->pixmapSizeToBeTakenIntoUse = NULL; } } QSizeF MExtensionHandleView::sizeHint(Qt::SizeHint which, const QSizeF &) const { Q_D(const MExtensionHandleView); // Return the requested size hint bounded to forced minimum and maximum sizes defined in the style return d->remoteToHostCoordinates(model()->sizeHints().at(which)).expandedTo(style()->forcedMinimumSize()).boundedTo(style()->forcedMaximumSize()); } void MExtensionHandleView::pixmapModified(const QRectF &rect) { Q_D(MExtensionHandleView); // Unite the changed rectangle with the previous changed rectangle d->pixmapModifiedRect = rect.united(d->pixmapModifiedRect); // Update the local pixmap d->updateLocalPixmap(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/pm/p10_qme_sram_access.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_qme_sram_access.C /// @brief Access data to or from the targetted QME's SRAM array. /// // *HWP HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Amit Tendolkar <[email protected]> // *HWP Team : PM // *HWP Consumed by : HS:CRO:SBE /// // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p10_qme_sram_access.H> #include <multicast_group_defs.H> #include "p10_scom_eq.H" using namespace scomt::eq; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t QSAR_AUTO_INCREMENT_BIT = 63; const uint32_t QSCR_SRAM_ACCESS_MODE_BIT = 0; // These really should come from hcd_common RTC 210851 const uint32_t QME_SRAM_SIZE = 64 * 1024; const uint32_t QME_SRAM_BASE_ADDR = 0xFFFF0000; // ----------------------------------------------------------------------------- // Loal Functions // ----------------------------------------------------------------------------- fapi2::ReturnCode qme_sram_read_qsar( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_qme_target) { fapi2::buffer<uint64_t> l_data64; auto l_chip = i_qme_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); auto l_eq_vector = l_chip.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); for (auto& eq : l_eq_vector) { FAPI_TRY(fapi2::getScom(eq, QME_QSAR, l_data64)); FAPI_DBG(" QSAR = 0x%016llX", l_data64); } fapi_try_exit: return fapi2::current_err; } // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- /// See doxygen in header file fapi2::ReturnCode p10_qme_sram_access( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_qme_target, const uint32_t i_start_address, const uint32_t i_length_dword, const qmesram::Op i_operation, uint64_t* io_data, uint32_t& o_dwords_accessed) { fapi2::buffer<uint64_t> l_data64; fapi2::buffer<uint64_t> l_qsar; qmesram::Op l_op; // These are initialized before being used. // Not doing an initial assignment to 0 to save space on the SBE. uint32_t l_norm_address; uint32_t l_words_to_access; // Clear the core selects so that multicast to the QMEs will work uint32_t l_core_select = 0; FAPI_DBG("> p10_qme_sram_access"); fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > l_chip = i_qme_target.getParent< fapi2::TARGET_TYPE_PROC_CHIP >(); fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > l_target = l_chip.getMulticast<fapi2::MULTICAST_AND>(fapi2::MCGROUP_GOOD_EQ, static_cast<fapi2::MulticastCoreSelect>(l_core_select)); // Ensure the address is between 0xFFFF0000 and 0xFFFFFFFF. // No need to check the upper limit, since that will overflow the uint32_t data type. if (i_start_address < 0xFFFF0000) { // Return Error - invalid start address FAPI_DBG("Invalid Start Address 0x%.8X", i_start_address); FAPI_ASSERT(false, fapi2::QME_SRAM_ACCESS_ERROR().set_ADDRESS(i_start_address), "Invalid QME Start address"); } if ((i_start_address & 0x00000007) != 0) { // Return Error - invalid start address alignment FAPI_DBG("Invalid Start Address alignment 0x%.8X", i_start_address); FAPI_ASSERT(false, fapi2::QME_SRAM_ACCESS_ERROR().set_ADDRESS(i_start_address), "Invalid QME Start address alignment"); } // Set the QME SRAM address as defined by 16:28 (64k) l_norm_address = i_start_address & 0x0000FFF8; l_data64.flush<0>().insertFromRight<0, 32>(l_norm_address); FAPI_DBG(" QME Setting address to 0x%016llX", l_data64); FAPI_TRY(fapi2::putScom(l_target, QME_QSAR, l_data64)); // Compute the number of words if ((l_norm_address + i_length_dword * 8) > QME_SRAM_SIZE) { l_words_to_access = (QME_SRAM_SIZE - l_norm_address) / 8; } else { l_words_to_access = i_length_dword; } // o_dwords_accessed will indicate the number of words successfully accessed. // Increment after each access. o_dwords_accessed = 0; // RTC 211508 Get around HW501715 where auto-increment doesn't work if (i_operation == qmesram::GET) { l_op = qmesram::GET_NOAUTOINC; // l_op = qmesram::GET; } else if (i_operation == qmesram::PUT) { l_op = qmesram::PUT_NOAUTOINC; // l_op = qmesram::PUT; } else { l_op = i_operation; } switch (l_op) { case qmesram::GET: // if (l_target.isMulticast()) // { // FAPI_ERR(" ERROR: Multicast GET is not supported"); // fapi2::current_err = fapi2::FAPI2_RC_INVALID_PARAMETER; // goto fapi_try_exit; // } l_data64.flush<0>().setBit<QSCR_SRAM_ACCESS_MODE_BIT>(); FAPI_TRY(fapi2::putScom(l_target, QME_QSCR_WO_OR, l_data64)); FAPI_DBG(" Reading %d words from 0x%.8X through 0x%.8X in autoinc mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSAR, l_data64)); FAPI_DBG(" Get auto Address = 0x%016llX", l_data64); FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSDR, l_data64)); io_data[x] = l_data64(); o_dwords_accessed++; } break; case qmesram::GET_NOAUTOINC: // if (l_target.isMulticast()) // { // FAPI_ERR(" ERROR: Multicast GET is not supported"); // fapi2::current_err = fapi2::FAPI2_RC_INVALID_PARAMETER; // goto fapi_try_exit; // } FAPI_DBG(" Reading %d words from 0x%.8X through 0x%.8X in loop mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSAR, l_data64)); FAPI_DBG(" Get no auto Address = 0x%016llX", l_data64); FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSDR, l_data64)); io_data[x] = l_data64(); o_dwords_accessed++; // l_qsar += 0x0000000800000000; l_qsar += 0x0000001000000000; FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSAR, l_qsar)); } break; case qmesram::PUT: l_data64.flush<0>().setBit<QSCR_SRAM_ACCESS_MODE_BIT>(); FAPI_TRY(fapi2::putScom(l_target, QME_QSCR_WO_OR, l_data64)); FAPI_DBG(" Writing %d words to 0x%.8X through 0x%.8X in autoinc mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(qme_sram_read_qsar(l_target)); l_data64() = io_data[x]; FAPI_TRY(fapi2::putScom(l_target, QME_QSDR, l_data64)); o_dwords_accessed++; } break; case qmesram::PUT_NOAUTOINC: FAPI_DBG(" Writing %d words to 0x%.8X through 0x%.8X in loop mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(qme_sram_read_qsar(l_target)); l_data64() = io_data[x]; FAPI_TRY(fapi2::putScom(l_target, QME_QSDR, l_data64)); o_dwords_accessed++; // l_qsar += 0x0000000800000000; l_qsar += 0x0000001000000000; FAPI_TRY(fapi2::putScom(l_target, QME_QSAR, l_qsar)); } break; } fapi_try_exit: FAPI_DBG("< p10_qme_sram_access"); return fapi2::current_err; } <commit_msg>PM: fix to QME get/putsram functions<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/pm/p10_qme_sram_access.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_qme_sram_access.C /// @brief Access data to or from the targetted QME's SRAM array. /// // *HWP HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Amit Tendolkar <[email protected]> // *HWP Team : PM // *HWP Consumed by : HS:CRO:SBE /// // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p10_qme_sram_access.H> #include <multicast_group_defs.H> #include "p10_scom_eq.H" using namespace scomt::eq; // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- const uint32_t QSAR_AUTO_INCREMENT_BIT = 63; const uint32_t QSCR_SRAM_ACCESS_MODE_BIT = 0; // These really should come from hcd_common RTC 210851 const uint32_t QME_SRAM_SIZE = 64 * 1024; const uint32_t QME_SRAM_BASE_ADDR = 0xFFFF0000; // ----------------------------------------------------------------------------- // Loal Functions // ----------------------------------------------------------------------------- fapi2::ReturnCode qme_sram_read_qsar( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_qme_target) { fapi2::buffer<uint64_t> l_data64; auto l_chip = i_qme_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); auto l_eq_vector = l_chip.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); for (auto& eq : l_eq_vector) { FAPI_TRY(fapi2::getScom(eq, QME_QSAR, l_data64)); FAPI_DBG(" QSAR = 0x%016llX", l_data64); } fapi_try_exit: return fapi2::current_err; } // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- /// See doxygen in header file fapi2::ReturnCode p10_qme_sram_access( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_qme_target, const uint32_t i_start_address, const uint32_t i_length_dword, const qmesram::Op i_operation, uint64_t* io_data, uint32_t& o_dwords_accessed) { fapi2::buffer<uint64_t> l_data64; fapi2::buffer<uint64_t> l_qsar; qmesram::Op l_op; // These are initialized before being used. // Not doing an initial assignment to 0 to save space on the SBE. uint32_t l_norm_address; uint32_t l_words_to_access; FAPI_DBG("> p10_qme_sram_access"); // Ensure the address is between 0xFFFF0000 and 0xFFFFFFFF. // No need to check the upper limit, since that will overflow the uint32_t data type. if (i_start_address < 0xFFFF0000) { // Return Error - invalid start address FAPI_DBG("Invalid Start Address 0x%.8X", i_start_address); FAPI_ASSERT(false, fapi2::QME_SRAM_ACCESS_ERROR().set_ADDRESS(i_start_address), "Invalid QME Start address"); } if ((i_start_address & 0x00000007) != 0) { // Return Error - invalid start address alignment FAPI_DBG("Invalid Start Address alignment 0x%.8X", i_start_address); FAPI_ASSERT(false, fapi2::QME_SRAM_ACCESS_ERROR().set_ADDRESS(i_start_address), "Invalid QME Start address alignment"); } // Set the QME SRAM address as defined by 16:28 (64k) l_norm_address = i_start_address & 0x0000FFF8; l_qsar.flush<0>().insertFromRight<0, 32>(l_norm_address); FAPI_DBG(" QME Setting address to 0x%016llX", l_qsar); FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSAR, l_qsar)); // Compute the number of words if ((l_norm_address + i_length_dword * 8) > QME_SRAM_SIZE) { l_words_to_access = (QME_SRAM_SIZE - l_norm_address) / 8; } else { l_words_to_access = i_length_dword; } // o_dwords_accessed will indicate the number of words successfully accessed. // Increment after each access. o_dwords_accessed = 0; // This switch is here to allow for each switching between auto-increment // and non-autoincrement (NOAUTOINC) modes. if (i_operation == qmesram::GET) { // l_op = qmesram::GET_NOAUTOINC; // only needed for work-arounds l_op = qmesram::GET; } else if (i_operation == qmesram::PUT) { // l_op = qmesram::PUT_NOAUTOINC; // only needed for work-arounds l_op = qmesram::PUT; } else { l_op = i_operation; } switch (l_op) { case qmesram::GET: FAPI_DBG(" Reading %d words from 0x%.8X through 0x%.8X in autoinc mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); l_data64.flush<0>().setBit<QME_QSCR_SRAM_ACCESS_MODE>(); FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSCR_WO_OR, l_data64)); // set autoincrement for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSAR, l_data64)); FAPI_DBG(" Get auto Address = 0x%016llX", l_data64); FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSDR, l_data64)); io_data[x] = l_data64(); o_dwords_accessed++; } break; case qmesram::GET_NOAUTOINC: FAPI_DBG(" Reading %d words from 0x%.8X through 0x%.8X in loop mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); l_data64.flush<0>().setBit<QME_QSCR_SRAM_ACCESS_MODE>(); FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSCR_WO_CLEAR, l_data64)); // clear autoincrement for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSAR, l_data64)); FAPI_DBG(" Get no auto Address = 0x%016llX", l_data64); FAPI_TRY(fapi2::getScom(i_qme_target, QME_QSDR, l_data64)); io_data[x] = l_data64(); o_dwords_accessed++; l_qsar += 0x0000000800000000; FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSAR, l_qsar)); } break; case qmesram::PUT: FAPI_DBG(" Writing %d words to 0x%.8X through 0x%.8X in autoinc mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); l_data64.flush<0>().setBit<QME_QSCR_SRAM_ACCESS_MODE>(); FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSCR_WO_OR, l_data64)); // set autoincrement for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(qme_sram_read_qsar(i_qme_target)); l_data64() = io_data[x]; FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSDR, l_data64)); o_dwords_accessed++; } break; case qmesram::PUT_NOAUTOINC: FAPI_DBG(" Writing %d words to 0x%.8X through 0x%.8X in loop mode", l_words_to_access, l_norm_address, l_norm_address + l_words_to_access * 8); l_data64.flush<0>().setBit<QME_QSCR_SRAM_ACCESS_MODE>(); FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSCR_WO_CLEAR, l_data64)); // clear autoincrement for (uint32_t x = 0; x < l_words_to_access; x++) { FAPI_TRY(qme_sram_read_qsar(i_qme_target)); l_data64() = io_data[x]; FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSDR, l_data64)); o_dwords_accessed++; l_qsar += 0x0000000800000000; FAPI_TRY(fapi2::putScom(i_qme_target, QME_QSAR, l_qsar)); } break; } fapi_try_exit: FAPI_DBG("< p10_qme_sram_access"); return fapi2::current_err; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/manifolds/RealVectorControlManifold.h" #include "ompl/util/Exception.h" #include <cstring> #include <limits> void ompl::control::RealVectorControlUniformSampler::sample(Control *control) { const unsigned int dim = manifold_->getDimension(); const base::RealVectorBounds &bounds = static_cast<const RealVectorControlManifold*>(manifold_)->getBounds(); RealVectorControlManifold::ControlType *rcontrol = static_cast<RealVectorControlManifold::ControlType*>(control); for (unsigned int i = 0 ; i < dim ; ++i) rcontrol->values[i] = rng_.uniformReal(bounds.low[i], bounds.high[i]); } void ompl::control::RealVectorControlManifold::setup(void) { ControlManifold::setup(); bounds_.check(); } void ompl::control::RealVectorControlManifold::setBounds(const base::RealVectorBounds &bounds) { bounds.check(); if (bounds.low.size() != dimension_) throw Exception("Bounds do not match dimension of manifold"); bounds_ = bounds; } unsigned int ompl::control::RealVectorControlManifold::getDimension(void) const { return dimension_; } void ompl::control::RealVectorControlManifold::copyControl(Control *destination, const Control *source) const { memcpy(static_cast<ControlType*>(destination)->values, static_cast<const ControlType*>(source)->values, controlBytes_); } bool ompl::control::RealVectorControlManifold::equalControls(const Control *control1, const Control *control2) const { const double *s1 = static_cast<const ControlType*>(control1)->values; const double *s2 = static_cast<const ControlType*>(control2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); if (fabs(diff) > std::numeric_limits<double>::epsilon() * 2.0) return false; } return true; } ompl::control::ControlSamplerPtr ompl::control::RealVectorControlManifold::allocControlSampler(void) const { return ControlSamplerPtr(new RealVectorControlUniformSampler(this)); } ompl::control::Control* ompl::control::RealVectorControlManifold::allocControl(void) const { ControlType *rcontrol = new ControlType(); rcontrol->values = new double[dimension_]; return rcontrol; } void ompl::control::RealVectorControlManifold::freeControl(Control *control) const { ControlType *rcontrol = static_cast<ControlType*>(control); delete[] rcontrol->values; delete rcontrol; } void ompl::control::RealVectorControlManifold::nullControl(Control *control) const { ControlType *rcontrol = static_cast<ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) { if (bounds_.low[i] <= 0.0 && bounds_.high[i] >= 0.0) rcontrol->values[i] = 0.0; else rcontrol->values[i] = bounds_.low[i]; } } void ompl::control::RealVectorControlManifold::copyToReals(const Control *control, std::vector<double> &reals) const { reals.reserve(reals.size() + dimension_); const ControlType *rcontrol = static_cast<const ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) reals.push_back(rcontrol->values[i]); } unsigned int ompl::control::RealVectorControlManifold::copyFromReals(Control *control, const std::vector<double> &reals) const { ControlType *rcontrol = static_cast<ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) rcontrol->values[i] = reals[i]; return dimension_; } void ompl::control::RealVectorControlManifold::printControl(const Control *control, std::ostream &out) const { out << "RealVectorControl ["; if (control) { const ControlType *rcontrol = static_cast<const ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) { out << rcontrol->values[i]; if (i + 1 < dimension_) out << ' '; } } else out << "NULL"; out << ']' << std::endl; } void ompl::control::RealVectorControlManifold::printSettings(std::ostream &out) const { out << "Real vector control manifold '" << name_ << "' with bounds: " << std::endl; out << " - min: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.low[i] << " "; out << std::endl; out << " - max: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.high[i] << " "; out << std::endl; } <commit_msg>one more message about incorrect bounds<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/manifolds/RealVectorControlManifold.h" #include "ompl/util/Exception.h" #include <boost/lexical_cast.hpp> #include <cstring> #include <limits> void ompl::control::RealVectorControlUniformSampler::sample(Control *control) { const unsigned int dim = manifold_->getDimension(); const base::RealVectorBounds &bounds = static_cast<const RealVectorControlManifold*>(manifold_)->getBounds(); RealVectorControlManifold::ControlType *rcontrol = static_cast<RealVectorControlManifold::ControlType*>(control); for (unsigned int i = 0 ; i < dim ; ++i) rcontrol->values[i] = rng_.uniformReal(bounds.low[i], bounds.high[i]); } void ompl::control::RealVectorControlManifold::setup(void) { ControlManifold::setup(); bounds_.check(); } void ompl::control::RealVectorControlManifold::setBounds(const base::RealVectorBounds &bounds) { bounds.check(); if (bounds.low.size() != dimension_) throw Exception("Bounds do not match dimension of manifold: expected dimension " + boost::lexical_cast<std::string>(dimension_) + " but got dimension " + boost::lexical_cast<std::string>(bounds.low.size())); bounds_ = bounds; } unsigned int ompl::control::RealVectorControlManifold::getDimension(void) const { return dimension_; } void ompl::control::RealVectorControlManifold::copyControl(Control *destination, const Control *source) const { memcpy(static_cast<ControlType*>(destination)->values, static_cast<const ControlType*>(source)->values, controlBytes_); } bool ompl::control::RealVectorControlManifold::equalControls(const Control *control1, const Control *control2) const { const double *s1 = static_cast<const ControlType*>(control1)->values; const double *s2 = static_cast<const ControlType*>(control2)->values; for (unsigned int i = 0 ; i < dimension_ ; ++i) { double diff = (*s1++) - (*s2++); if (fabs(diff) > std::numeric_limits<double>::epsilon() * 2.0) return false; } return true; } ompl::control::ControlSamplerPtr ompl::control::RealVectorControlManifold::allocControlSampler(void) const { return ControlSamplerPtr(new RealVectorControlUniformSampler(this)); } ompl::control::Control* ompl::control::RealVectorControlManifold::allocControl(void) const { ControlType *rcontrol = new ControlType(); rcontrol->values = new double[dimension_]; return rcontrol; } void ompl::control::RealVectorControlManifold::freeControl(Control *control) const { ControlType *rcontrol = static_cast<ControlType*>(control); delete[] rcontrol->values; delete rcontrol; } void ompl::control::RealVectorControlManifold::nullControl(Control *control) const { ControlType *rcontrol = static_cast<ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) { if (bounds_.low[i] <= 0.0 && bounds_.high[i] >= 0.0) rcontrol->values[i] = 0.0; else rcontrol->values[i] = bounds_.low[i]; } } void ompl::control::RealVectorControlManifold::copyToReals(const Control *control, std::vector<double> &reals) const { reals.reserve(reals.size() + dimension_); const ControlType *rcontrol = static_cast<const ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) reals.push_back(rcontrol->values[i]); } unsigned int ompl::control::RealVectorControlManifold::copyFromReals(Control *control, const std::vector<double> &reals) const { ControlType *rcontrol = static_cast<ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) rcontrol->values[i] = reals[i]; return dimension_; } void ompl::control::RealVectorControlManifold::printControl(const Control *control, std::ostream &out) const { out << "RealVectorControl ["; if (control) { const ControlType *rcontrol = static_cast<const ControlType*>(control); for (unsigned int i = 0 ; i < dimension_ ; ++i) { out << rcontrol->values[i]; if (i + 1 < dimension_) out << ' '; } } else out << "NULL"; out << ']' << std::endl; } void ompl::control::RealVectorControlManifold::printSettings(std::ostream &out) const { out << "Real vector control manifold '" << name_ << "' with bounds: " << std::endl; out << " - min: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.low[i] << " "; out << std::endl; out << " - max: "; for (unsigned int i = 0 ; i < dimension_ ; ++i) out << bounds_.high[i] << " "; out << std::endl; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the config.tests of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandintegration.h" #include "qwaylanddisplay.h" #include "qwaylandinputcontext.h" #include "qwaylandshmbackingstore.h" #include "qwaylandshmwindow.h" #include "qwaylandnativeinterface.h" #include "qwaylandclipboard.h" #include "qwaylanddnd.h" #include "qwaylandwindowmanagerintegration.h" #include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h" #include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h> #include <QtPlatformSupport/private/qgenericunixthemes_p.h> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qwindowsysteminterface.h> #include <qpa/qplatformcursor.h> #include <QtGui/QSurfaceFormat> #include <QtGui/QOpenGLContext> #include <qpa/qplatforminputcontextfactory_p.h> #include <qpa/qplatformaccessibility.h> #include <qpa/qplatforminputcontext.h> #ifdef QT_WAYLAND_GL_SUPPORT #include "qwaylandglintegration.h" #endif QT_BEGIN_NAMESPACE class GenericWaylandTheme: public QGenericUnixTheme { public: static QStringList themeNames() { QStringList result; if (QGuiApplication::desktopSettingsAware()) { const QByteArray desktopEnvironment = QGuiApplicationPrivate::platformIntegration()->services()->desktopEnvironment(); // Ignore X11 desktop environments if (!desktopEnvironment.isEmpty() && desktopEnvironment != QByteArrayLiteral("UNKNOWN") && desktopEnvironment != QByteArrayLiteral("KDE") && desktopEnvironment != QByteArrayLiteral("GNOME") && desktopEnvironment != QByteArrayLiteral("UNITY") && desktopEnvironment != QByteArrayLiteral("MATE") && desktopEnvironment != QByteArrayLiteral("XFCE") && desktopEnvironment != QByteArrayLiteral("LXDE")) result.push_back(desktopEnvironment.toLower()); } if (result.isEmpty()) result.push_back(QLatin1String(QGenericUnixTheme::name)); return result; } }; QWaylandIntegration::QWaylandIntegration() : mFontDb(new QGenericUnixFontDatabase()) , mNativeInterface(new QWaylandNativeInterface(this)) #ifndef QT_NO_ACCESSIBILITY , mAccessibility(new QPlatformAccessibility()) #else , mAccessibility(0) #endif { mDisplay = new QWaylandDisplay(); mClipboard = new QWaylandClipboard(mDisplay); mDrag = new QWaylandDrag(mDisplay); foreach (QPlatformScreen *screen, mDisplay->screens()) screenAdded(screen); mInputContext.reset(new QWaylandInputContext(mDisplay)); } QWaylandIntegration::~QWaylandIntegration() { delete mDrag; delete mClipboard; #ifndef QT_NO_ACCESSIBILITY delete mAccessibility; #endif delete mNativeInterface; delete mDisplay; } QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const { return mNativeInterface; } bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const { switch (cap) { case ThreadedPixmaps: return true; case OpenGL: #ifdef QT_WAYLAND_GL_SUPPORT return true; #else return false; #endif case ThreadedOpenGL: #ifdef QT_WAYLAND_GL_SUPPORT return mDisplay->eglIntegration()->supportsThreadedOpenGL(); #else return false; #endif case BufferQueueingOpenGL: return true; default: return QPlatformIntegration::hasCapability(cap); } } QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const { #ifdef QT_WAYLAND_GL_SUPPORT if (window->surfaceType() == QWindow::OpenGLSurface) return mDisplay->eglIntegration()->createEglWindow(window); #endif return new QWaylandShmWindow(window); } QPlatformOpenGLContext *QWaylandIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const { #ifdef QT_WAYLAND_GL_SUPPORT return mDisplay->eglIntegration()->createPlatformOpenGLContext(context->format(), context->shareHandle()); #else Q_UNUSED(context); return 0; #endif } QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const { return new QWaylandShmBackingStore(window); } QAbstractEventDispatcher *QWaylandIntegration::createEventDispatcher() const { return createUnixEventDispatcher(); } void QWaylandIntegration::initialize() { QAbstractEventDispatcher *dispatcher = QGuiApplicationPrivate::eventDispatcher; QObject::connect(dispatcher, SIGNAL(aboutToBlock()), mDisplay, SLOT(flushRequests())); } QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const { return mFontDb; } QPlatformClipboard *QWaylandIntegration::clipboard() const { return mClipboard; } QPlatformDrag *QWaylandIntegration::drag() const { return mDrag; } QPlatformInputContext *QWaylandIntegration::inputContext() const { return mInputContext.data(); } QVariant QWaylandIntegration::styleHint(StyleHint hint) const { if (hint == ShowIsFullScreen && mDisplay->windowManagerIntegration()) return mDisplay->windowManagerIntegration()->showIsFullScreen(); return QPlatformIntegration::styleHint(hint); } QPlatformAccessibility *QWaylandIntegration::accessibility() const { return mAccessibility; } QPlatformServices *QWaylandIntegration::services() const { return mDisplay->windowManagerIntegration(); } QWaylandDisplay *QWaylandIntegration::display() const { return mDisplay; } QStringList QWaylandIntegration::themeNames() const { return GenericWaylandTheme::themeNames(); } QPlatformTheme *QWaylandIntegration::createPlatformTheme(const QString &name) const { return GenericWaylandTheme::createUnixTheme(name); } QT_END_NAMESPACE <commit_msg>Wayland supports multiple windows.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the config.tests of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandintegration.h" #include "qwaylanddisplay.h" #include "qwaylandinputcontext.h" #include "qwaylandshmbackingstore.h" #include "qwaylandshmwindow.h" #include "qwaylandnativeinterface.h" #include "qwaylandclipboard.h" #include "qwaylanddnd.h" #include "qwaylandwindowmanagerintegration.h" #include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h" #include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h> #include <QtPlatformSupport/private/qgenericunixthemes_p.h> #include <QtGui/private/qguiapplication_p.h> #include <qpa/qwindowsysteminterface.h> #include <qpa/qplatformcursor.h> #include <QtGui/QSurfaceFormat> #include <QtGui/QOpenGLContext> #include <qpa/qplatforminputcontextfactory_p.h> #include <qpa/qplatformaccessibility.h> #include <qpa/qplatforminputcontext.h> #ifdef QT_WAYLAND_GL_SUPPORT #include "qwaylandglintegration.h" #endif QT_BEGIN_NAMESPACE class GenericWaylandTheme: public QGenericUnixTheme { public: static QStringList themeNames() { QStringList result; if (QGuiApplication::desktopSettingsAware()) { const QByteArray desktopEnvironment = QGuiApplicationPrivate::platformIntegration()->services()->desktopEnvironment(); // Ignore X11 desktop environments if (!desktopEnvironment.isEmpty() && desktopEnvironment != QByteArrayLiteral("UNKNOWN") && desktopEnvironment != QByteArrayLiteral("KDE") && desktopEnvironment != QByteArrayLiteral("GNOME") && desktopEnvironment != QByteArrayLiteral("UNITY") && desktopEnvironment != QByteArrayLiteral("MATE") && desktopEnvironment != QByteArrayLiteral("XFCE") && desktopEnvironment != QByteArrayLiteral("LXDE")) result.push_back(desktopEnvironment.toLower()); } if (result.isEmpty()) result.push_back(QLatin1String(QGenericUnixTheme::name)); return result; } }; QWaylandIntegration::QWaylandIntegration() : mFontDb(new QGenericUnixFontDatabase()) , mNativeInterface(new QWaylandNativeInterface(this)) #ifndef QT_NO_ACCESSIBILITY , mAccessibility(new QPlatformAccessibility()) #else , mAccessibility(0) #endif { mDisplay = new QWaylandDisplay(); mClipboard = new QWaylandClipboard(mDisplay); mDrag = new QWaylandDrag(mDisplay); foreach (QPlatformScreen *screen, mDisplay->screens()) screenAdded(screen); mInputContext.reset(new QWaylandInputContext(mDisplay)); } QWaylandIntegration::~QWaylandIntegration() { delete mDrag; delete mClipboard; #ifndef QT_NO_ACCESSIBILITY delete mAccessibility; #endif delete mNativeInterface; delete mDisplay; } QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const { return mNativeInterface; } bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const { switch (cap) { case ThreadedPixmaps: return true; case OpenGL: #ifdef QT_WAYLAND_GL_SUPPORT return true; #else return false; #endif case ThreadedOpenGL: #ifdef QT_WAYLAND_GL_SUPPORT return mDisplay->eglIntegration()->supportsThreadedOpenGL(); #else return false; #endif case BufferQueueingOpenGL: return true; case MultipleWindows: case NonFullScreenWindows: return true; default: return QPlatformIntegration::hasCapability(cap); } } QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const { #ifdef QT_WAYLAND_GL_SUPPORT if (window->surfaceType() == QWindow::OpenGLSurface) return mDisplay->eglIntegration()->createEglWindow(window); #endif return new QWaylandShmWindow(window); } QPlatformOpenGLContext *QWaylandIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const { #ifdef QT_WAYLAND_GL_SUPPORT return mDisplay->eglIntegration()->createPlatformOpenGLContext(context->format(), context->shareHandle()); #else Q_UNUSED(context); return 0; #endif } QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const { return new QWaylandShmBackingStore(window); } QAbstractEventDispatcher *QWaylandIntegration::createEventDispatcher() const { return createUnixEventDispatcher(); } void QWaylandIntegration::initialize() { QAbstractEventDispatcher *dispatcher = QGuiApplicationPrivate::eventDispatcher; QObject::connect(dispatcher, SIGNAL(aboutToBlock()), mDisplay, SLOT(flushRequests())); } QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const { return mFontDb; } QPlatformClipboard *QWaylandIntegration::clipboard() const { return mClipboard; } QPlatformDrag *QWaylandIntegration::drag() const { return mDrag; } QPlatformInputContext *QWaylandIntegration::inputContext() const { return mInputContext.data(); } QVariant QWaylandIntegration::styleHint(StyleHint hint) const { if (hint == ShowIsFullScreen && mDisplay->windowManagerIntegration()) return mDisplay->windowManagerIntegration()->showIsFullScreen(); return QPlatformIntegration::styleHint(hint); } QPlatformAccessibility *QWaylandIntegration::accessibility() const { return mAccessibility; } QPlatformServices *QWaylandIntegration::services() const { return mDisplay->windowManagerIntegration(); } QWaylandDisplay *QWaylandIntegration::display() const { return mDisplay; } QStringList QWaylandIntegration::themeNames() const { return GenericWaylandTheme::themeNames(); } QPlatformTheme *QWaylandIntegration::createPlatformTheme(const QString &name) const { return GenericWaylandTheme::createUnixTheme(name); } QT_END_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_popup_view.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/autofill/test_autofill_external_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/test/browser_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::AtLeast; using testing::_; namespace { class MockAutofillExternalDelegate : public TestAutofillExternalDelegate { public: MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {} ~MockAutofillExternalDelegate() {} virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index) OVERRIDE {} }; class TestAutofillPopupView : public AutofillPopupView { public: explicit TestAutofillPopupView( content::WebContents* web_contents, AutofillExternalDelegate* autofill_external_delegate) : AutofillPopupView(web_contents, autofill_external_delegate) {} virtual ~TestAutofillPopupView() {} MOCK_METHOD0(Hide, void()); MOCK_METHOD1(InvalidateRow, void(size_t)); void SetSelectedLine(size_t selected_line) { AutofillPopupView::SetSelectedLine(selected_line); } protected: virtual void ShowInternal() OVERRIDE {} virtual void HideInternal() OVERRIDE {} }; } // namespace class AutofillPopupViewBrowserTest : public InProcessBrowserTest { public: AutofillPopupViewBrowserTest() {} virtual ~AutofillPopupViewBrowserTest() {} virtual void SetUpOnMainThread() OVERRIDE { web_contents_ = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents_ != NULL); autofill_popup_view_.reset(new TestAutofillPopupView( web_contents_, &autofill_external_delegate_)); } protected: content::WebContents* web_contents_; scoped_ptr<TestAutofillPopupView> autofill_popup_view_; MockAutofillExternalDelegate autofill_external_delegate_; }; IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, SwitchTabAndHideAutofillPopup) { EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1)); ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_WEB_CONTENTS_HIDDEN, content::Source<content::WebContents>(web_contents_)); browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL), content::PAGE_TRANSITION_START_PAGE); observer.Wait(); // The mock verifies that the call was made. } IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, FLAKY_TestPageNavigationHidingAutofillPopup) { EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1)); ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<content::NavigationController>( &(web_contents_->GetController()))); browser()->OpenURL(content::OpenURLParams( GURL(chrome::kAboutBlankURL), content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false)); browser()->OpenURL(content::OpenURLParams( GURL(chrome::kChromeUICrashURL), content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false)); observer.Wait(); // The mock verifies that the call was made. } IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, SetSelectedAutofillLineAndCallInvalidate) { std::vector<string16> autofill_values; autofill_values.push_back(string16()); std::vector<int> autofill_ids; autofill_ids.push_back(0); autofill_popup_view_->Show( autofill_values, autofill_values, autofill_values, autofill_ids, 0); // Make sure that when a new line is selected, it is invalidated so it can // be updated to show it is selected. int selected_line = 0; EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)); autofill_popup_view_->SetSelectedLine(selected_line); // Ensure that the row isn't invalidated if it didn't change. EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0); autofill_popup_view_->SetSelectedLine(selected_line); // Change back to no selection. EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)); autofill_popup_view_->SetSelectedLine(-1); } <commit_msg>Fix Flaky TestPageNavigateHidingAutofillPopup<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_popup_view.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/autofill/test_autofill_external_delegate.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/test/browser_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::AtLeast; using testing::_; namespace { class MockAutofillExternalDelegate : public TestAutofillExternalDelegate { public: MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {} ~MockAutofillExternalDelegate() {} virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index) OVERRIDE {} }; class TestAutofillPopupView : public AutofillPopupView { public: explicit TestAutofillPopupView( content::WebContents* web_contents, AutofillExternalDelegate* autofill_external_delegate) : AutofillPopupView(web_contents, autofill_external_delegate) {} virtual ~TestAutofillPopupView() {} MOCK_METHOD0(Hide, void()); MOCK_METHOD1(InvalidateRow, void(size_t)); void SetSelectedLine(size_t selected_line) { AutofillPopupView::SetSelectedLine(selected_line); } protected: virtual void ShowInternal() OVERRIDE {} virtual void HideInternal() OVERRIDE {} }; } // namespace class AutofillPopupViewBrowserTest : public InProcessBrowserTest { public: AutofillPopupViewBrowserTest() {} virtual ~AutofillPopupViewBrowserTest() {} virtual void SetUpOnMainThread() OVERRIDE { web_contents_ = browser()->GetSelectedWebContents(); ASSERT_TRUE(web_contents_ != NULL); autofill_popup_view_.reset(new TestAutofillPopupView( web_contents_, &autofill_external_delegate_)); } protected: content::WebContents* web_contents_; scoped_ptr<TestAutofillPopupView> autofill_popup_view_; MockAutofillExternalDelegate autofill_external_delegate_; }; IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, SwitchTabAndHideAutofillPopup) { EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1)); ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_WEB_CONTENTS_HIDDEN, content::Source<content::WebContents>(web_contents_)); browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL), content::PAGE_TRANSITION_START_PAGE); observer.Wait(); // The mock verifies that the call was made. } IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, FLAKY_TestPageNavigationHidingAutofillPopup) { EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1)); ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<content::NavigationController>( &(web_contents_->GetController()))); browser()->OpenURL(content::OpenURLParams( GURL(chrome::kAboutBlankURL), content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false)); browser()->OpenURL(content::OpenURLParams( GURL(chrome::kChromeUIAboutURL), content::Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false)); observer.Wait(); // The mock verifies that the call was made. } IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest, SetSelectedAutofillLineAndCallInvalidate) { std::vector<string16> autofill_values; autofill_values.push_back(string16()); std::vector<int> autofill_ids; autofill_ids.push_back(0); autofill_popup_view_->Show( autofill_values, autofill_values, autofill_values, autofill_ids, 0); // Make sure that when a new line is selected, it is invalidated so it can // be updated to show it is selected. int selected_line = 0; EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)); autofill_popup_view_->SetSelectedLine(selected_line); // Ensure that the row isn't invalidated if it didn't change. EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0); autofill_popup_view_->SetSelectedLine(selected_line); // Change back to no selection. EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)); autofill_popup_view_->SetSelectedLine(-1); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/protector/base_setting_change.h" #include "chrome/browser/protector/histograms.h" #include "chrome/browser/protector/protector.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_prepopulate_data.h" #include "chrome/browser/search_engines/template_url_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/template_url_service_observer.h" #include "chrome/browser/webdata/keyword_table.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/url_constants.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "googleurl/src/gurl.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" namespace protector { namespace { // Maximum length of the search engine name to be displayed. const size_t kMaxDisplayedNameLength = 10; // Matches TemplateURL with all fields set from the prepopulated data equal // to fields in another TemplateURL. class TemplateURLIsSame { public: // Creates a matcher based on |other|. explicit TemplateURLIsSame(const TemplateURL* other) : other_(other) { } // Returns true if both |other| and |url| are NULL or have same field values. bool operator()(const TemplateURL* url) { if (url == other_ ) return true; if (!url || !other_) return false; return url->short_name() == other_->short_name() && AreKeywordsSame(url, other_) && TemplateURLRef::SameUrlRefs(url->url(), other_->url()) && TemplateURLRef::SameUrlRefs(url->suggestions_url(), other_->suggestions_url()) && TemplateURLRef::SameUrlRefs(url->instant_url(), other_->instant_url()) && url->GetFaviconURL() == other_->GetFaviconURL() && url->safe_for_autoreplace() == other_->safe_for_autoreplace() && url->show_in_default_list() == other_->show_in_default_list() && url->input_encodings() == other_->input_encodings() && url->prepopulate_id() == other_->prepopulate_id(); } private: // Returns true if both |url1| and |url2| have autogenerated keywords // or if their keywords are identical. bool AreKeywordsSame(const TemplateURL* url1, const TemplateURL* url2) { return (url1->autogenerate_keyword() && url2->autogenerate_keyword()) || url1->keyword() == url2->keyword(); } const TemplateURL* other_; }; } // namespace // Default search engine change tracked by Protector. class DefaultSearchProviderChange : public BaseSettingChange, public TemplateURLServiceObserver, public content::NotificationObserver { public: DefaultSearchProviderChange(const TemplateURL* new_search_provider, TemplateURL* backup_search_provider); // BaseSettingChange overrides: virtual bool Init(Protector* protector) OVERRIDE; virtual void Apply() OVERRIDE; virtual void Discard() OVERRIDE; virtual void Timeout() OVERRIDE; virtual void OnBeforeRemoved() OVERRIDE; virtual int GetBadgeIconID() const OVERRIDE; virtual int GetMenuItemIconID() const OVERRIDE; virtual int GetBubbleIconID() const OVERRIDE; virtual string16 GetBubbleTitle() const OVERRIDE; virtual string16 GetBubbleMessage() const OVERRIDE; virtual string16 GetApplyButtonText() const OVERRIDE; virtual string16 GetDiscardButtonText() const OVERRIDE; private: virtual ~DefaultSearchProviderChange(); // TemplateURLServiceObserver overrides: virtual void OnTemplateURLServiceChanged() OVERRIDE; // content::NotificationObserver overrides: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Sets the default search provider to |*search_provider|. If a matching // TemplateURL already exists, it is reused and |*search_provider| is reset. // Otherwise, adds |*search_provider| to keywords and releases it. // In both cases, |*search_provider| is NULL after this call. // Returns the new default search provider (either |*search_provider| or the // reused TemplateURL). const TemplateURL* SetDefaultSearchProvider( scoped_ptr<TemplateURL>* search_provider); // Opens the Search engine settings page in a new tab. void OpenSearchEngineSettings(); // Returns the TemplateURLService instance for the Profile this change is // related to. TemplateURLService* GetTemplateURLService(); // Stops observing the TemplateURLService changes. void StopObservingTemplateURLService(); // Histogram ID of the new search provider. int new_histogram_id_; // Indicates that the default search was restored to the prepopulated default // search engines. bool is_fallback_; // Indicates that the the prepopulated default search is the same as // |new_search_provider_|. bool fallback_is_new_; // ID of |new_search_provider_|. TemplateURLID new_id_; // The default search at the moment the change was detected. Will be used to // restore the new default search back if Apply is called. Will be set to // |NULL| if removed from the TemplateURLService. const TemplateURL* new_search_provider_; // Default search provider set by Init for the period until user makes a // choice and either Apply or Discard is performed. Never is |NULL| during // that period since the change will dismiss itself if this provider gets // deleted or stops being the default. const TemplateURL* default_search_provider_; // Stores backup of the default search until it becomes owned by the // TemplateURLService or deleted. scoped_ptr<TemplateURL> backup_search_provider_; content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(DefaultSearchProviderChange); }; DefaultSearchProviderChange::DefaultSearchProviderChange( const TemplateURL* new_search_provider, TemplateURL* backup_search_provider) : new_histogram_id_(GetSearchProviderHistogramID(new_search_provider)), is_fallback_(false), fallback_is_new_(false), new_search_provider_(new_search_provider), default_search_provider_(NULL), backup_search_provider_(backup_search_provider) { } DefaultSearchProviderChange::~DefaultSearchProviderChange() { } bool DefaultSearchProviderChange::Init(Protector* protector) { if (!BaseSettingChange::Init(protector)) return false; if (backup_search_provider_.get()) { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderHijacked, new_histogram_id_, kProtectorMaxSearchProviderID); } else { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderCorrupt, new_histogram_id_, kProtectorMaxSearchProviderID); // Fallback to a prepopulated default search provider, ignoring any // overrides in Prefs. backup_search_provider_.reset( TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(NULL)); is_fallback_ = true; VLOG(1) << "Fallback search provider: " << backup_search_provider_->short_name(); } default_search_provider_ = SetDefaultSearchProvider(&backup_search_provider_); DCHECK(default_search_provider_); // |backup_search_provider_| should be |NULL| since now. DCHECK(!backup_search_provider_.get()); if (is_fallback_ && default_search_provider_ == new_search_provider_) fallback_is_new_ = true; int restored_histogram_id = GetSearchProviderHistogramID(default_search_provider_); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderRestored, restored_histogram_id, kProtectorMaxSearchProviderID); if (is_fallback_) { VLOG(1) << "Fallback to search provider: " << default_search_provider_->short_name(); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderFallback, restored_histogram_id, kProtectorMaxSearchProviderID); } // Listen for the default search provider changes. GetTemplateURLService()->AddObserver(this); if (new_search_provider_) { // Listen for removal of |new_search_provider_|. new_id_ = new_search_provider_->id(); registrar_.Add( this, chrome::NOTIFICATION_TEMPLATE_URL_REMOVED, content::Source<Profile>(protector->profile()->GetOriginalProfile())); } return true; } void DefaultSearchProviderChange::Apply() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderApplied, new_histogram_id_, kProtectorMaxSearchProviderID); StopObservingTemplateURLService(); if (new_search_provider_) { GetTemplateURLService()->SetDefaultSearchProvider(new_search_provider_); } else { // Open settings page in case the new setting is invalid. OpenSearchEngineSettings(); } } void DefaultSearchProviderChange::Discard() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderDiscarded, new_histogram_id_, kProtectorMaxSearchProviderID); StopObservingTemplateURLService(); if (is_fallback_) { // Open settings page in case the old setting is invalid. OpenSearchEngineSettings(); } // Nothing to do otherwise since we have already set the search engine // to |old_id_| in |Init|. } void DefaultSearchProviderChange::Timeout() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderTimeout, new_histogram_id_, kProtectorMaxSearchProviderID); } void DefaultSearchProviderChange::OnBeforeRemoved() { StopObservingTemplateURLService(); } int DefaultSearchProviderChange::GetBadgeIconID() const { return IDR_SEARCH_ENGINE_CHANGE_BADGE; } int DefaultSearchProviderChange::GetMenuItemIconID() const { return IDR_SEARCH_ENGINE_CHANGE_MENU; } int DefaultSearchProviderChange::GetBubbleIconID() const { return IDR_SEARCH_ENGINE_CHANGE_ALERT; } string16 DefaultSearchProviderChange::GetBubbleTitle() const { return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_TITLE); } string16 DefaultSearchProviderChange::GetBubbleMessage() const { if (!is_fallback_) { return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_MESSAGE); } else { return l10n_util::GetStringFUTF16( IDS_SEARCH_ENGINE_CHANGE_NO_BACKUP_MESSAGE, default_search_provider_->short_name()); } } string16 DefaultSearchProviderChange::GetApplyButtonText() const { if (new_search_provider_) { // If backup search engine is lost and fallback was made to the current // search provider then there is no need to show this button. if (fallback_is_new_) return string16(); string16 name = new_search_provider_->short_name(); if (name.length() > kMaxDisplayedNameLength) return l10n_util::GetStringUTF16(IDS_CHANGE_SEARCH_ENGINE_NO_NAME); else return l10n_util::GetStringFUTF16(IDS_CHANGE_SEARCH_ENGINE, name); } else if (!is_fallback_) { // New setting is lost, offer to go to settings. return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE); } else { // Both settings are lost: don't show this button. return string16(); } } string16 DefaultSearchProviderChange::GetDiscardButtonText() const { if (!is_fallback_) { string16 name = default_search_provider_->short_name(); if (name.length() > kMaxDisplayedNameLength) return l10n_util::GetStringUTF16(IDS_KEEP_SETTING); else return l10n_util::GetStringFUTF16(IDS_KEEP_SEARCH_ENGINE, name); } else { // Old setting is lost, offer to go to settings. return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE); } } void DefaultSearchProviderChange::OnTemplateURLServiceChanged() { TemplateURLService* url_service = GetTemplateURLService(); if (url_service->GetDefaultSearchProvider() != default_search_provider_) { VLOG(1) << "Default search provider has been changed by user"; default_search_provider_ = NULL; url_service->RemoveObserver(this); // This will delete the Protector instance and |this|. protector()->DismissChange(); } } void DefaultSearchProviderChange::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_TEMPLATE_URL_REMOVED); TemplateURLID id = *content::Details<TemplateURLID>(details).ptr(); if (id == new_id_) new_search_provider_ = NULL; registrar_.Remove(this, type, source); // TODO(ivankr): should the change be dismissed as well? Probably not, // since this may happend due to Sync or whatever. In that case, if user // clicks on 'Change to...', the Search engine settings page will be opened. } const TemplateURL* DefaultSearchProviderChange::SetDefaultSearchProvider( scoped_ptr<TemplateURL>* search_provider) { TemplateURLService* url_service = GetTemplateURLService(); TemplateURLService::TemplateURLVector urls = url_service->GetTemplateURLs(); const TemplateURL* new_default_provider = NULL; // Check if this provider already exists and add it otherwise. TemplateURLService::TemplateURLVector::const_iterator i = find_if(urls.begin(), urls.end(), TemplateURLIsSame(search_provider->get())); if (i != urls.end()) { VLOG(1) << "Provider already exists"; new_default_provider = *i; search_provider->reset(); } else { VLOG(1) << "No match, adding new provider"; new_default_provider = search_provider->get(); url_service->Add(search_provider->release()); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderMissing, GetSearchProviderHistogramID(new_default_provider), kProtectorMaxSearchProviderID); } // TODO(ivankr): handle keyword conflicts with existing providers. DCHECK(new_default_provider); VLOG(1) << "Default search provider set to: " << new_default_provider->short_name(); url_service->SetDefaultSearchProvider(new_default_provider); return new_default_provider; } void DefaultSearchProviderChange::OpenSearchEngineSettings() { protector()->OpenTab( GURL(std::string(chrome::kChromeUISettingsURL) + chrome::kSearchEnginesSubPage)); } TemplateURLService* DefaultSearchProviderChange::GetTemplateURLService() { TemplateURLService* url_service = TemplateURLServiceFactory::GetForProfile(protector()->profile()); DCHECK(url_service); return url_service; } void DefaultSearchProviderChange::StopObservingTemplateURLService() { GetTemplateURLService()->RemoveObserver(this); } BaseSettingChange* CreateDefaultSearchProviderChange( const TemplateURL* actual, TemplateURL* backup) { return new DefaultSearchProviderChange(actual, backup); } } // namespace protector <commit_msg>Add missing std namespace for find_if() in default_search_provider_change.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/protector/base_setting_change.h" #include "chrome/browser/protector/histograms.h" #include "chrome/browser/protector/protector.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_prepopulate_data.h" #include "chrome/browser/search_engines/template_url_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/template_url_service_observer.h" #include "chrome/browser/webdata/keyword_table.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/url_constants.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "googleurl/src/gurl.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" namespace protector { namespace { // Maximum length of the search engine name to be displayed. const size_t kMaxDisplayedNameLength = 10; // Matches TemplateURL with all fields set from the prepopulated data equal // to fields in another TemplateURL. class TemplateURLIsSame { public: // Creates a matcher based on |other|. explicit TemplateURLIsSame(const TemplateURL* other) : other_(other) { } // Returns true if both |other| and |url| are NULL or have same field values. bool operator()(const TemplateURL* url) { if (url == other_ ) return true; if (!url || !other_) return false; return url->short_name() == other_->short_name() && AreKeywordsSame(url, other_) && TemplateURLRef::SameUrlRefs(url->url(), other_->url()) && TemplateURLRef::SameUrlRefs(url->suggestions_url(), other_->suggestions_url()) && TemplateURLRef::SameUrlRefs(url->instant_url(), other_->instant_url()) && url->GetFaviconURL() == other_->GetFaviconURL() && url->safe_for_autoreplace() == other_->safe_for_autoreplace() && url->show_in_default_list() == other_->show_in_default_list() && url->input_encodings() == other_->input_encodings() && url->prepopulate_id() == other_->prepopulate_id(); } private: // Returns true if both |url1| and |url2| have autogenerated keywords // or if their keywords are identical. bool AreKeywordsSame(const TemplateURL* url1, const TemplateURL* url2) { return (url1->autogenerate_keyword() && url2->autogenerate_keyword()) || url1->keyword() == url2->keyword(); } const TemplateURL* other_; }; } // namespace // Default search engine change tracked by Protector. class DefaultSearchProviderChange : public BaseSettingChange, public TemplateURLServiceObserver, public content::NotificationObserver { public: DefaultSearchProviderChange(const TemplateURL* new_search_provider, TemplateURL* backup_search_provider); // BaseSettingChange overrides: virtual bool Init(Protector* protector) OVERRIDE; virtual void Apply() OVERRIDE; virtual void Discard() OVERRIDE; virtual void Timeout() OVERRIDE; virtual void OnBeforeRemoved() OVERRIDE; virtual int GetBadgeIconID() const OVERRIDE; virtual int GetMenuItemIconID() const OVERRIDE; virtual int GetBubbleIconID() const OVERRIDE; virtual string16 GetBubbleTitle() const OVERRIDE; virtual string16 GetBubbleMessage() const OVERRIDE; virtual string16 GetApplyButtonText() const OVERRIDE; virtual string16 GetDiscardButtonText() const OVERRIDE; private: virtual ~DefaultSearchProviderChange(); // TemplateURLServiceObserver overrides: virtual void OnTemplateURLServiceChanged() OVERRIDE; // content::NotificationObserver overrides: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Sets the default search provider to |*search_provider|. If a matching // TemplateURL already exists, it is reused and |*search_provider| is reset. // Otherwise, adds |*search_provider| to keywords and releases it. // In both cases, |*search_provider| is NULL after this call. // Returns the new default search provider (either |*search_provider| or the // reused TemplateURL). const TemplateURL* SetDefaultSearchProvider( scoped_ptr<TemplateURL>* search_provider); // Opens the Search engine settings page in a new tab. void OpenSearchEngineSettings(); // Returns the TemplateURLService instance for the Profile this change is // related to. TemplateURLService* GetTemplateURLService(); // Stops observing the TemplateURLService changes. void StopObservingTemplateURLService(); // Histogram ID of the new search provider. int new_histogram_id_; // Indicates that the default search was restored to the prepopulated default // search engines. bool is_fallback_; // Indicates that the the prepopulated default search is the same as // |new_search_provider_|. bool fallback_is_new_; // ID of |new_search_provider_|. TemplateURLID new_id_; // The default search at the moment the change was detected. Will be used to // restore the new default search back if Apply is called. Will be set to // |NULL| if removed from the TemplateURLService. const TemplateURL* new_search_provider_; // Default search provider set by Init for the period until user makes a // choice and either Apply or Discard is performed. Never is |NULL| during // that period since the change will dismiss itself if this provider gets // deleted or stops being the default. const TemplateURL* default_search_provider_; // Stores backup of the default search until it becomes owned by the // TemplateURLService or deleted. scoped_ptr<TemplateURL> backup_search_provider_; content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(DefaultSearchProviderChange); }; DefaultSearchProviderChange::DefaultSearchProviderChange( const TemplateURL* new_search_provider, TemplateURL* backup_search_provider) : new_histogram_id_(GetSearchProviderHistogramID(new_search_provider)), is_fallback_(false), fallback_is_new_(false), new_search_provider_(new_search_provider), default_search_provider_(NULL), backup_search_provider_(backup_search_provider) { } DefaultSearchProviderChange::~DefaultSearchProviderChange() { } bool DefaultSearchProviderChange::Init(Protector* protector) { if (!BaseSettingChange::Init(protector)) return false; if (backup_search_provider_.get()) { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderHijacked, new_histogram_id_, kProtectorMaxSearchProviderID); } else { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderCorrupt, new_histogram_id_, kProtectorMaxSearchProviderID); // Fallback to a prepopulated default search provider, ignoring any // overrides in Prefs. backup_search_provider_.reset( TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(NULL)); is_fallback_ = true; VLOG(1) << "Fallback search provider: " << backup_search_provider_->short_name(); } default_search_provider_ = SetDefaultSearchProvider(&backup_search_provider_); DCHECK(default_search_provider_); // |backup_search_provider_| should be |NULL| since now. DCHECK(!backup_search_provider_.get()); if (is_fallback_ && default_search_provider_ == new_search_provider_) fallback_is_new_ = true; int restored_histogram_id = GetSearchProviderHistogramID(default_search_provider_); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderRestored, restored_histogram_id, kProtectorMaxSearchProviderID); if (is_fallback_) { VLOG(1) << "Fallback to search provider: " << default_search_provider_->short_name(); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderFallback, restored_histogram_id, kProtectorMaxSearchProviderID); } // Listen for the default search provider changes. GetTemplateURLService()->AddObserver(this); if (new_search_provider_) { // Listen for removal of |new_search_provider_|. new_id_ = new_search_provider_->id(); registrar_.Add( this, chrome::NOTIFICATION_TEMPLATE_URL_REMOVED, content::Source<Profile>(protector->profile()->GetOriginalProfile())); } return true; } void DefaultSearchProviderChange::Apply() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderApplied, new_histogram_id_, kProtectorMaxSearchProviderID); StopObservingTemplateURLService(); if (new_search_provider_) { GetTemplateURLService()->SetDefaultSearchProvider(new_search_provider_); } else { // Open settings page in case the new setting is invalid. OpenSearchEngineSettings(); } } void DefaultSearchProviderChange::Discard() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderDiscarded, new_histogram_id_, kProtectorMaxSearchProviderID); StopObservingTemplateURLService(); if (is_fallback_) { // Open settings page in case the old setting is invalid. OpenSearchEngineSettings(); } // Nothing to do otherwise since we have already set the search engine // to |old_id_| in |Init|. } void DefaultSearchProviderChange::Timeout() { UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderTimeout, new_histogram_id_, kProtectorMaxSearchProviderID); } void DefaultSearchProviderChange::OnBeforeRemoved() { StopObservingTemplateURLService(); } int DefaultSearchProviderChange::GetBadgeIconID() const { return IDR_SEARCH_ENGINE_CHANGE_BADGE; } int DefaultSearchProviderChange::GetMenuItemIconID() const { return IDR_SEARCH_ENGINE_CHANGE_MENU; } int DefaultSearchProviderChange::GetBubbleIconID() const { return IDR_SEARCH_ENGINE_CHANGE_ALERT; } string16 DefaultSearchProviderChange::GetBubbleTitle() const { return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_TITLE); } string16 DefaultSearchProviderChange::GetBubbleMessage() const { if (!is_fallback_) { return l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_CHANGE_MESSAGE); } else { return l10n_util::GetStringFUTF16( IDS_SEARCH_ENGINE_CHANGE_NO_BACKUP_MESSAGE, default_search_provider_->short_name()); } } string16 DefaultSearchProviderChange::GetApplyButtonText() const { if (new_search_provider_) { // If backup search engine is lost and fallback was made to the current // search provider then there is no need to show this button. if (fallback_is_new_) return string16(); string16 name = new_search_provider_->short_name(); if (name.length() > kMaxDisplayedNameLength) return l10n_util::GetStringUTF16(IDS_CHANGE_SEARCH_ENGINE_NO_NAME); else return l10n_util::GetStringFUTF16(IDS_CHANGE_SEARCH_ENGINE, name); } else if (!is_fallback_) { // New setting is lost, offer to go to settings. return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE); } else { // Both settings are lost: don't show this button. return string16(); } } string16 DefaultSearchProviderChange::GetDiscardButtonText() const { if (!is_fallback_) { string16 name = default_search_provider_->short_name(); if (name.length() > kMaxDisplayedNameLength) return l10n_util::GetStringUTF16(IDS_KEEP_SETTING); else return l10n_util::GetStringFUTF16(IDS_KEEP_SEARCH_ENGINE, name); } else { // Old setting is lost, offer to go to settings. return l10n_util::GetStringUTF16(IDS_SELECT_SEARCH_ENGINE); } } void DefaultSearchProviderChange::OnTemplateURLServiceChanged() { TemplateURLService* url_service = GetTemplateURLService(); if (url_service->GetDefaultSearchProvider() != default_search_provider_) { VLOG(1) << "Default search provider has been changed by user"; default_search_provider_ = NULL; url_service->RemoveObserver(this); // This will delete the Protector instance and |this|. protector()->DismissChange(); } } void DefaultSearchProviderChange::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_TEMPLATE_URL_REMOVED); TemplateURLID id = *content::Details<TemplateURLID>(details).ptr(); if (id == new_id_) new_search_provider_ = NULL; registrar_.Remove(this, type, source); // TODO(ivankr): should the change be dismissed as well? Probably not, // since this may happend due to Sync or whatever. In that case, if user // clicks on 'Change to...', the Search engine settings page will be opened. } const TemplateURL* DefaultSearchProviderChange::SetDefaultSearchProvider( scoped_ptr<TemplateURL>* search_provider) { TemplateURLService* url_service = GetTemplateURLService(); TemplateURLService::TemplateURLVector urls = url_service->GetTemplateURLs(); const TemplateURL* new_default_provider = NULL; // Check if this provider already exists and add it otherwise. TemplateURLService::TemplateURLVector::const_iterator i = std::find_if(urls.begin(), urls.end(), TemplateURLIsSame(search_provider->get())); if (i != urls.end()) { VLOG(1) << "Provider already exists"; new_default_provider = *i; search_provider->reset(); } else { VLOG(1) << "No match, adding new provider"; new_default_provider = search_provider->get(); url_service->Add(search_provider->release()); UMA_HISTOGRAM_ENUMERATION( kProtectorHistogramSearchProviderMissing, GetSearchProviderHistogramID(new_default_provider), kProtectorMaxSearchProviderID); } // TODO(ivankr): handle keyword conflicts with existing providers. DCHECK(new_default_provider); VLOG(1) << "Default search provider set to: " << new_default_provider->short_name(); url_service->SetDefaultSearchProvider(new_default_provider); return new_default_provider; } void DefaultSearchProviderChange::OpenSearchEngineSettings() { protector()->OpenTab( GURL(std::string(chrome::kChromeUISettingsURL) + chrome::kSearchEnginesSubPage)); } TemplateURLService* DefaultSearchProviderChange::GetTemplateURLService() { TemplateURLService* url_service = TemplateURLServiceFactory::GetForProfile(protector()->profile()); DCHECK(url_service); return url_service; } void DefaultSearchProviderChange::StopObservingTemplateURLService() { GetTemplateURLService()->RemoveObserver(this); } BaseSettingChange* CreateDefaultSearchProviderChange( const TemplateURL* actual, TemplateURL* backup) { return new DefaultSearchProviderChange(actual, backup); } } // namespace protector <|endoftext|>
<commit_before>/* * Keyman is copyright (C) SIL International. MIT License. * * Keyman Core - Debugger API unit tests */ #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <iterator> #include <string> #include "../../../src/kmx/kmx_xstring.h" #include "../test_assert.h" using namespace km::kbp::kmx; using namespace std; void test_incxstr() { PKMX_WCHAR p; // pointer input to incxstr() PKMX_WCHAR q; // pointer output to incxstr() // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- NULL, SURROGATE PAIRS, NON_UC_SENTINEL, ONE CHARACTER --------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for empty string ------------------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR) u"\0"; q = incxstr(p); assert(q == p); // --- Test for character --------------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR) u"\U00001234"; q = incxstr(p); assert(q == p+1); // --- Test for surrogate pair ---------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR) u"\U0001F609"; q = incxstr(p); assert(q == p+2); // --- Test for one <control> ----------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U00000012"; q = incxstr(p); assert(q == p + 1); // --- Test for FFFF only ------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF"; q = incxstr(p); assert(q == p + 1); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL WITHOUT \0 ---------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + CODE_ANY ---------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000001\U00000001"; q = incxstr(p); assert(q == p + 3); // // --- Test for FFFF +CODE_NOTANY ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000012\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_INDEX -------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_USE ---------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000005\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_DEADKEY ------------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF CODE_EXTENDED -------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000010"; q = incxstr(p); assert(q == p + 9); // --- Test for FFFF +CODE_CLEARCONTEXT ------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U0000000E\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_CALL ---------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000F\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_CONTEXTEX --------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000011\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_IFOPT ------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 5); // --- Test for FFFF +CODE_IFSYSTEMSTORE ------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000017\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 5); // --- Test for FFFF +CODE_SETOPT ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000013\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_SETSYSTEMRESTORE --------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000018\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_RESETOPT ----------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000016\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_SAVEOPT ----------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000015\U00000001"; q = incxstr(p); assert(q == p + 3 ); // --- Test for FFFF +default ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004"; q = incxstr(p); assert(q == p + 2); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL WITH \0 AT DIFFERENT POSITIONS -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + control (earlier p+1) with \0 after first position --------------- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\0\U00000008\U00000001"; q = incxstr(p); assert(q == p+1); // --- Test for FFFF +control (earlier p+1) with \0 after second position --------- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\0\U00000001"; q = incxstr(p); assert(q == p+2); // --- Test for FFFF +control (earlier p+1) with \0 after third position ----- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001\0"; q = incxstr(p); assert(q == p+3) // --- Test for FFFF +control (earlier p+2) with \0 after fourth position ----- unit test failed with old version of incxstr() ---- p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000001\U00000001\0"; q = incxstr(p); assert(q == p+4); // --- Test for FFFF +control (earlier p+3) with \0 after fifth position ----- unit test failed with old version of incxstr() --------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000001\U00000001\U00000001\0"; q = incxstr(p); assert(q == p+5); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 6. position ----- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\0\U00000005\U00000006\U00000007\U00000010"; q = incxstr(p); assert(q == p + 6); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 7. position ----- unit test failed with old version of incxstr() p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\0\U00000006\U00000007\U00000010"; q = incxstr(p); assert(q == p + 7); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 8. position ----- unit test failed with old version of incxstr() ---------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\0\U00000007\U00000010"; q = incxstr(p); assert(q == p + 8); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 9. position ----- unit test failed with old version of incxstr() --- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\0\U00000010"; q = incxstr(p); assert(q == p + 9); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 10. position ----- unit test failed with old version of incxstr() ----------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\U00000010\0"; q = incxstr(p); assert(q == p + 10); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL, INCOMPLETE & UNUSUAL SEQUENCES-------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + \0 -------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\0"; q = incxstr(p); assert(q == p + 1); // --- Test for FFFF +one character ------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000062"; q = incxstr(p); assert(q == p + 2); // --- Test for FFFF +one <control> ----------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004"; q = incxstr(p); assert(q == p + 2); // --- Test for FFFF + one <control> + character ------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004\U00000062"; q = incxstr(p); assert(q == p + 2); } constexpr const auto help_str = "\ debug_api [--color] <SOURCE_PATH>|--print-sizeof\n\ \n\ --color Force color output\n\ --print-sizeof Emit structure sizes for interop debug\n\ SOURCE_PATH Path where debug_api.cpp is found; kmx files are\n\ located relative to this path.\n"; int error_args() { std::cerr << "debug_api: Invalid arguments." << std::endl; std::cout << help_str; return 1; } int main(int argc, char *argv []) { // TODO: choose/create a keyboard which has some rules // Global setup //std::string path(argv[1]); auto arg_color = argc > 1 && std::string(argv[1]) == "--color"; console_color::enabled = console_color::isaterminal() || arg_color; test_incxstr(); return 0; } <commit_msg>Update common/core/desktop/tests/unit/kmnkbd/test_kmx_xstring.cpp<commit_after>/* * Keyman is copyright (C) SIL International. MIT License. * * Keyman Core - Debugger API unit tests */ #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <iterator> #include <string> #include "../../../src/kmx/kmx_xstring.h" #include "../test_assert.h" using namespace km::kbp::kmx; using namespace std; void test_incxstr() { PKMX_WCHAR p; // pointer input to incxstr() PKMX_WCHAR q; // pointer output to incxstr() // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- NULL, SURROGATE PAIRS, NON_UC_SENTINEL, ONE CHARACTER --------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for empty string ------------------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR) u"\0"; q = incxstr(p); assert(q == p); // --- Test for character --------------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR) u"\U00001234"; q = incxstr(p); assert(q == p+1); // --- Test for surrogate pair ---------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR) u"\U0001F609"; q = incxstr(p); assert(q == p+2); // --- Test for one <control> ----------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U00000012"; q = incxstr(p); assert(q == p + 1); // --- Test for FFFF only ------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF"; q = incxstr(p); assert(q == p + 1); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL WITHOUT \0 ---------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + CODE_ANY ---------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000001\U00000001"; q = incxstr(p); assert(q == p + 3); // // --- Test for FFFF +CODE_NOTANY ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000012\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_INDEX -------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_USE ---------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000005\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_DEADKEY ------------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF CODE_EXTENDED -------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000010"; q = incxstr(p); assert(q == p + 9); // --- Test for FFFF +CODE_CLEARCONTEXT ------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U0000000E\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_CALL ---------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000F\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_CONTEXTEX --------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000011\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_IFOPT ------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 5); // --- Test for FFFF +CODE_IFSYSTEMSTORE ------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000017\U00000002\U00000002\U00000001"; q = incxstr(p); assert(q == p + 5); // --- Test for FFFF +CODE_SETOPT ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000013\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_SETSYSTEMRESTORE --------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000018\U00000002\U00000001"; q = incxstr(p); assert(q == p + 4); // --- Test for FFFF +CODE_RESETOPT ----------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000016\U00000001"; q = incxstr(p); assert(q == p + 3); // --- Test for FFFF +CODE_SAVEOPT ----------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000015\U00000001"; q = incxstr(p); assert(q == p + 3 ); // --- Test for FFFF +default ---------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004"; q = incxstr(p); assert(q == p + 2); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL WITH \0 AT DIFFERENT POSITIONS -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + control (earlier p+1) with \0 after first position --------------- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\0\U00000008\U00000001"; q = incxstr(p); assert(q == p+1); // --- Test for FFFF +control (earlier p+1) with \0 after second position --------- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\0\U00000001"; q = incxstr(p); assert(q == p+2); // --- Test for FFFF +control (earlier p+1) with \0 after third position ----- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001\0"; q = incxstr(p); assert(q == p+3) // --- Test for FFFF +control (earlier p+2) with \0 after fourth position ----- unit test failed with old version of incxstr() ---- p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000001\U00000001\0"; q = incxstr(p); assert(q == p+4); // --- Test for FFFF +control (earlier p+3) with \0 after fifth position ----- unit test failed with old version of incxstr() --------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000001\U00000001\U00000001\0"; q = incxstr(p); assert(q == p+5); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 6. position ----- unit test failed with old version of incxstr() ----- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\0\U00000005\U00000006\U00000007\U00000010"; q = incxstr(p); assert(q == p + 6); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 7. position ----- unit test failed with old version of incxstr() p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\0\U00000006\U00000007\U00000010"; q = incxstr(p); assert(q == p + 7); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 8. position ----- unit test failed with old version of incxstr() ---------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\0\U00000007\U00000010"; q = incxstr(p); assert(q == p + 8); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 9. position ----- unit test failed with old version of incxstr() --- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\0\U00000010"; q = incxstr(p); assert(q == p + 9); // --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 10. position ----- unit test failed with old version of incxstr() ----------- p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\U00000010\0"; q = incxstr(p); assert(q == p + 10); // -------------------------------------------------------------------------------------------------------------------------------------------------- // ---- UC_SENTINEL, INCOMPLETE & UNUSUAL SEQUENCES-------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------------------------------------- // --- Test for FFFF + \0 -------------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\0"; q = incxstr(p); assert(q == p + 1); // --- Test for FFFF +one character ------------------------------------------------------------------------------------------------------------ p = (PKMX_WCHAR)u"\U0000FFFF\U00000062"; q = incxstr(p); assert(q == p + 2); // --- Test for FFFF +one <control> ----------------------------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004"; q = incxstr(p); assert(q == p + 2); // --- Test for FFFF + one <control> + character ------------------------------------------------------------------------------------------- p = (PKMX_WCHAR)u"\U0000FFFF\U00000004\U00000062"; q = incxstr(p); assert(q == p + 2); } constexpr const auto help_str = "\ test_kmx_xstring [--color]\n\ \n\ --color Force color output\n"; int error_args() { std::cerr << "debug_api: Invalid arguments." << std::endl; std::cout << help_str; return 1; } int main(int argc, char *argv []) { // TODO: choose/create a keyboard which has some rules // Global setup //std::string path(argv[1]); auto arg_color = argc > 1 && std::string(argv[1]) == "--color"; console_color::enabled = console_color::isaterminal() || arg_color; test_incxstr(); return 0; } <|endoftext|>
<commit_before>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "mlir/Conversion/TosaToArith/TosaToArith.h" #include "mlir/Conversion/TosaToLinalg/TosaToLinalg.h" #include "mlir/Conversion/TosaToSCF/TosaToSCF.h" #include "mlir/Conversion/TosaToTensor/TosaToTensor.h" #include "mlir/Dialect/Tosa/Transforms/Passes.h" #include "mlir/Pass/PassOptions.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { void registerTOSAConversionPassPipeline() { PassPipelineRegistration<> tosa( "iree-tosa-input-transformation-pipeline", "Runs the TOSA IREE flow dialect transformation pipeline", [](OpPassManager &passManager) { buildTOSAInputConversionPassPipeline(passManager); }); } // Prepare TOSA for use as an input to the Flow dialect. void buildTOSAInputConversionPassPipeline(OpPassManager &passManager) { // Currently we don't handle SCF ops well and have to convert them all to CFG. // In the future it would be nice if we could have all of flow be both scf // and cfg compatible. passManager.addNestedPass<func::FuncOp>(tosa::createTosaToSCF()); passManager.addNestedPass<func::FuncOp>(createTopLevelSCFToCFGPass()); // We also don't handle calls well on the old codepath; until we remove the // use of the CFG we can continue inlining. passManager.addPass(mlir::createInlinerPass()); passManager.addNestedPass<func::FuncOp>( tosa::createTosaMakeBroadcastablePass()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToArith()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToTensor()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); tosa::addTosaToLinalgPasses(passManager); // Sometimes we generate more TOSA operations during the lowering to linalg. passManager.addNestedPass<func::FuncOp>(tosa::createTosaToArith()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToTensor()); passManager.addNestedPass<func::FuncOp>( IREE::Flow::createStripSignednessPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); passManager.addNestedPass<func::FuncOp>( createLinalgQuantizedMatmulToMatmulPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); //---------------------------------------------------------------------------- // Entry dialect cleanup //---------------------------------------------------------------------------- passManager.addPass(createVerifyCompilerTOSAInputLegality()); } namespace { #define GEN_PASS_REGISTRATION #include "iree/compiler/InputConversion/TOSA/Passes.h.inc" // IWYU pragma: export } // namespace void registerTOSAConversionPasses() { // Generated. registerPasses(); // Pipelines. registerTOSAConversionPassPipeline(); } } // namespace iree_compiler } // namespace mlir <commit_msg>Enable quantized conv decomposition (#10852)<commit_after>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/InputConversion/TOSA/Passes.h" #include "iree/compiler/Dialect/Flow/Transforms/Passes.h" #include "iree/compiler/InputConversion/Common/Passes.h" #include "mlir/Conversion/TosaToArith/TosaToArith.h" #include "mlir/Conversion/TosaToLinalg/TosaToLinalg.h" #include "mlir/Conversion/TosaToSCF/TosaToSCF.h" #include "mlir/Conversion/TosaToTensor/TosaToTensor.h" #include "mlir/Dialect/Tosa/Transforms/Passes.h" #include "mlir/Pass/PassOptions.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { void registerTOSAConversionPassPipeline() { PassPipelineRegistration<> tosa( "iree-tosa-input-transformation-pipeline", "Runs the TOSA IREE flow dialect transformation pipeline", [](OpPassManager &passManager) { buildTOSAInputConversionPassPipeline(passManager); }); } // Prepare TOSA for use as an input to the Flow dialect. void buildTOSAInputConversionPassPipeline(OpPassManager &passManager) { // Currently we don't handle SCF ops well and have to convert them all to CFG. // In the future it would be nice if we could have all of flow be both scf // and cfg compatible. passManager.addNestedPass<func::FuncOp>(tosa::createTosaToSCF()); passManager.addNestedPass<func::FuncOp>(createTopLevelSCFToCFGPass()); // We also don't handle calls well on the old codepath; until we remove the // use of the CFG we can continue inlining. passManager.addPass(mlir::createInlinerPass()); passManager.addNestedPass<func::FuncOp>( tosa::createTosaMakeBroadcastablePass()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToArith()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToTensor()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); tosa::addTosaToLinalgPasses(passManager); // Sometimes we generate more TOSA operations during the lowering to linalg. passManager.addNestedPass<func::FuncOp>(tosa::createTosaToArith()); passManager.addNestedPass<func::FuncOp>(tosa::createTosaToTensor()); passManager.addNestedPass<func::FuncOp>( IREE::Flow::createStripSignednessPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); passManager.addNestedPass<func::FuncOp>( createLinalgQuantizedMatmulToMatmulPass()); passManager.addNestedPass<func::FuncOp>( createLinalgQuantizedConvToConvPass()); passManager.addNestedPass<func::FuncOp>(mlir::createCanonicalizerPass()); //---------------------------------------------------------------------------- // Entry dialect cleanup //---------------------------------------------------------------------------- passManager.addPass(createVerifyCompilerTOSAInputLegality()); } namespace { #define GEN_PASS_REGISTRATION #include "iree/compiler/InputConversion/TOSA/Passes.h.inc" // IWYU pragma: export } // namespace void registerTOSAConversionPasses() { // Generated. registerPasses(); // Pipelines. registerTOSAConversionPassPipeline(); } } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>/* Copyright (C) 2008-2015 The Communi Project You may use this file under the terms of BSD license as follows: 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 holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcNetwork* network = d.model->network(); QStringList caps = network->requestedCapabilities(); caps += "batch"; caps += "server-time"; caps += "echo-message"; caps += "znc.in/batch"; caps += "znc.in/playback"; caps += "znc.in/server-time"; caps += "znc.in/echo-message"; caps += "znc.in/server-time-iso"; network->setRequestedCapabilities(caps); IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { if (message->connection()->isConnected()) d.timestamp = qMax(d.timestamp, message->timeStamp()); if (message->type() == IrcMessage::Batch) { IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message); if (batch->batch() == "znc.in/playback") { IrcBuffer* buffer = d.model->add(batch->parameters().value(2)); foreach (IrcMessage* msg, batch->messages()) { msg->setFlags(msg->flags() | IrcMessage::Playback); if (msg->type() == IrcMessage::Private) processMessage(static_cast<IrcPrivateMessage*>(msg)); } buffer->receiveMessage(batch); } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::processMessage(IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); message->setPrefix(prefix); if (content.startsWith("joined")) { message->setTag("intent", "JOIN"); message->setParameters(QStringList() << message->target()); } else if (content.startsWith("parted")) { message->setTag("intent", "PART"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << message->target() << reason); } else if (content.startsWith("quit")) { message->setTag("intent", "QUIT"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << reason); } else if (content.startsWith("is")) { message->setTag("intent", "NICK"); const QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << tokens.last()); } else if (content.startsWith("set")) { message->setTag("intent", "MODE"); QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); message->setParameters(QStringList() << message->target() << mode << user); } else if (content.startsWith("changed")) { message->setTag("intent", "TOPIC"); const QString topic = content.mid(content.indexOf(":") + 2); message->setParameters(QStringList() << message->target() << topic); } else if (content.startsWith("kicked")) { message->setTag("intent", "KICK"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << message->target() << tokens.value(1) << reason); } } } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)); cmd->setParent(this); connection->sendCommand(cmd); } } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <commit_msg>Revert "ZncManager: don't filter out batch messages"<commit_after>/* Copyright (C) 2008-2015 The Communi Project You may use this file under the terms of BSD license as follows: 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 holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcNetwork* network = d.model->network(); QStringList caps = network->requestedCapabilities(); caps += "batch"; caps += "server-time"; caps += "echo-message"; caps += "znc.in/batch"; caps += "znc.in/playback"; caps += "znc.in/server-time"; caps += "znc.in/echo-message"; caps += "znc.in/server-time-iso"; network->setRequestedCapabilities(caps); IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { if (message->connection()->isConnected()) d.timestamp = qMax(d.timestamp, message->timeStamp()); if (message->type() == IrcMessage::Batch) { IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message); if (batch->batch() == "znc.in/playback") { IrcBuffer* buffer = d.model->add(batch->parameters().value(2)); foreach (IrcMessage* msg, batch->messages()) { msg->setFlags(msg->flags() | IrcMessage::Playback); if (msg->type() == IrcMessage::Private) processMessage(static_cast<IrcPrivateMessage*>(msg)); } buffer->receiveMessage(batch); return true; } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::processMessage(IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); message->setPrefix(prefix); if (content.startsWith("joined")) { message->setTag("intent", "JOIN"); message->setParameters(QStringList() << message->target()); } else if (content.startsWith("parted")) { message->setTag("intent", "PART"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << message->target() << reason); } else if (content.startsWith("quit")) { message->setTag("intent", "QUIT"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << reason); } else if (content.startsWith("is")) { message->setTag("intent", "NICK"); const QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << tokens.last()); } else if (content.startsWith("set")) { message->setTag("intent", "MODE"); QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); message->setParameters(QStringList() << message->target() << mode << user); } else if (content.startsWith("changed")) { message->setTag("intent", "TOPIC"); const QString topic = content.mid(content.indexOf(":") + 2); message->setParameters(QStringList() << message->target() << topic); } else if (content.startsWith("kicked")) { message->setTag("intent", "KICK"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << message->target() << tokens.value(1) << reason); } } } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)); cmd->setParent(this); connection->sendCommand(cmd); } } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <|endoftext|>
<commit_before>/* Copyright (C) 2008-2014 The Communi Project You may use this file under the terms of BSD license as follows: 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 holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.buffer = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { bool playback = false; if (message->tags().contains("time")) { QDateTime timestamp = message->tags().value("time").toDateTime(); if (timestamp.isValid()) { message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime)); playback = timestamp < d.timestamp; d.timestamp = qMax(timestamp, d.timestamp); } } if (!playback && d.buffer) { emit playbackEnd(d.buffer); d.buffer = 0; } if (message->type() == IrcMessage::Private) { IrcPrivateMessage* msg = static_cast<IrcPrivateMessage*>(message); IrcBuffer* buffer = d.model->find(msg->target()); if (buffer) { if (d.buffer != buffer) { if (d.buffer) { emit playbackEnd(d.buffer); d.buffer = 0; } if (playback) { emit playbackBegin(buffer); d.buffer = buffer; } } return processMessage(buffer, msg); } } return IgnoreManager::instance()->messageFilter(message); } bool ZncManager::processMessage(IrcBuffer* buffer, IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); IrcMessage* tmp = 0; if (content.startsWith("joined")) { tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection()); } else if (content.startsWith("parted")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection()); } else if (content.startsWith("quit")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection()); } else if (content.startsWith("is")) { const QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection()); } else if (content.startsWith("set")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection()); } else if (content.startsWith("changed")) { const QString topic = content.mid(content.indexOf(":") + 2); tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection()); } else if (content.startsWith("kicked")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection()); } if (tmp) { tmp->setTags(message->tags()); tmp->setTimeStamp(message->timeStamp()); buffer->receiveMessage(tmp); tmp->deleteLater(); return true; } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); connection->sendCommand(IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0))); } } void ZncManager::requestCapabilities() { QStringList request; QStringList available = d.model->network()->availableCapabilities(); if (available.contains("znc.in/playback")) request << "znc.in/playback"; if (available.contains("server-time")) request << "server-time"; else if (available.contains("znc.in/server-time-iso")) request << "znc.in/server-time-iso"; else if (available.contains("znc.in/server-time")) request << "znc.in/server-time"; if (!request.isEmpty()) d.model->network()->requestCapabilities(request); } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <commit_msg>ZNC: request self-message capability<commit_after>/* Copyright (C) 2008-2014 The Communi Project You may use this file under the terms of BSD license as follows: 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 holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.buffer = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { bool playback = false; if (message->tags().contains("time")) { QDateTime timestamp = message->tags().value("time").toDateTime(); if (timestamp.isValid()) { message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime)); playback = timestamp < d.timestamp; d.timestamp = qMax(timestamp, d.timestamp); } } if (!playback && d.buffer) { emit playbackEnd(d.buffer); d.buffer = 0; } if (message->type() == IrcMessage::Private) { IrcPrivateMessage* msg = static_cast<IrcPrivateMessage*>(message); IrcBuffer* buffer = d.model->find(msg->target()); if (buffer) { if (d.buffer != buffer) { if (d.buffer) { emit playbackEnd(d.buffer); d.buffer = 0; } if (playback) { emit playbackBegin(buffer); d.buffer = buffer; } } return processMessage(buffer, msg); } } return IgnoreManager::instance()->messageFilter(message); } bool ZncManager::processMessage(IrcBuffer* buffer, IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); IrcMessage* tmp = 0; if (content.startsWith("joined")) { tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection()); } else if (content.startsWith("parted")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection()); } else if (content.startsWith("quit")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection()); } else if (content.startsWith("is")) { const QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection()); } else if (content.startsWith("set")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection()); } else if (content.startsWith("changed")) { const QString topic = content.mid(content.indexOf(":") + 2); tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection()); } else if (content.startsWith("kicked")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection()); } if (tmp) { tmp->setTags(message->tags()); tmp->setTimeStamp(message->timeStamp()); buffer->receiveMessage(tmp); tmp->deleteLater(); return true; } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); connection->sendCommand(IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0))); } } void ZncManager::requestCapabilities() { QStringList request; QStringList available = d.model->network()->availableCapabilities(); if (available.contains("self-message")) request << "self-message"; if (available.contains("znc.in/playback")) request << "znc.in/playback"; if (available.contains("server-time")) request << "server-time"; else if (available.contains("znc.in/server-time-iso")) request << "znc.in/server-time-iso"; else if (available.contains("znc.in/server-time")) request << "znc.in/server-time"; if (!request.isEmpty()) d.model->network()->requestCapabilities(request); } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "AppMenu.h" #include "LSession.h" #include <LuminaOS.h> AppMenu::AppMenu(QWidget* parent) : QMenu(parent){ appstorelink = LOS::AppStoreShortcut(); //Default application "store" to display (AppCafe in PC-BSD) controlpanellink = LOS::ControlPanelShortcut(); //Default control panel APPS.clear(); watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(watcherUpdate()) ); //QTimer::singleShot(200, this, SLOT(start()) ); //Now start filling the menu start(); //do the initial run during session init so things are responsive immediately. connect(QApplication::instance(), SIGNAL(LocaleChanged()), this, SLOT(watcherUpdate()) ); connect(QApplication::instance(), SIGNAL(IconThemeChanged()), this, SLOT(watcherUpdate()) ); } AppMenu::~AppMenu(){ } QHash<QString, QList<XDGDesktop> >* AppMenu::currentAppHash(){ return &APPS; } //=========== // PRIVATE //=========== void AppMenu::updateAppList(){ //Make sure the title/icon are updated as well (in case of locale/icon change) this->setTitle(tr("Applications")); this->setIcon( LXDG::findIcon("system-run","") ); //Now update the lists this->clear(); APPS.clear(); QList<XDGDesktop> allfiles = LXDG::systemDesktopFiles(); APPS = LXDG::sortDesktopCats(allfiles); APPS.insert("All", LXDG::sortDesktopNames(allfiles)); lastHashUpdate = QDateTime::currentDateTime(); //Now fill the menu bool ok; //for checking inputs //Add link to the file manager this->addAction( LXDG::findIcon("user-home", ""), tr("Browse Files"), this, SLOT(launchFileManager()) ); //--Look for the app store XDGDesktop store = LXDG::loadDesktopFile(appstorelink, ok); if(ok){ this->addAction( LXDG::findIcon(store.icon, ""), tr("Install Applications"), this, SLOT(launchStore()) ); } //--Look for the control panel store = LXDG::loadDesktopFile(controlpanellink, ok); if(ok){ this->addAction( LXDG::findIcon(store.icon, ""), tr("Control Panel"), this, SLOT(launchControlPanel()) ); } this->addSeparator(); //--Now create the sub-menus QStringList cats = APPS.keys(); cats.sort(); //make sure they are alphabetical for(int i=0; i<cats.length(); i++){ //Make sure they are translated and have the right icons QString name, icon; if(cats[i]=="All"){continue; } //skip this listing for the menu else if(cats[i] == "Multimedia"){ name = tr("Multimedia"); icon = "applications-multimedia"; } else if(cats[i] == "Development"){ name = tr("Development"); icon = "applications-development"; } else if(cats[i] == "Education"){ name = tr("Education"); icon = "applications-education"; } else if(cats[i] == "Game"){ name = tr("Games"); icon = "applications-games"; } else if(cats[i] == "Graphics"){ name = tr("Graphics"); icon = "applications-graphics"; } else if(cats[i] == "Network"){ name = tr("Network"); icon = "applications-internet"; } else if(cats[i] == "Office"){ name = tr("Office"); icon = "applications-office"; } else if(cats[i] == "Science"){ name = tr("Science"); icon = "applications-science"; } else if(cats[i] == "Settings"){ name = tr("Settings"); icon = "preferences-system"; } else if(cats[i] == "System"){ name = tr("System"); icon = "applications-system"; } else if(cats[i] == "Utility"){ name = tr("Utility"); icon = "applications-utilities"; } else if(cats[i] == "Wine"){ name = tr("Wine"); icon = "wine"; } else{ name = tr("Unsorted"); icon = "applications-other"; } QMenu *menu = new QMenu(name, this); menu->setIcon(LXDG::findIcon(icon,"")); connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(launchApp(QAction*)) ); QList<XDGDesktop> appL = APPS.value(cats[i]); for( int a=0; a<appL.length(); a++){ if(appL[a].actions.isEmpty()){ //Just a single entry point - no extra actions QAction *act = new QAction(LXDG::findIcon(appL[a].icon, ""), appL[a].name, this); act->setToolTip(appL[a].comment); act->setWhatsThis(appL[a].filePath); menu->addAction(act); }else{ //This app has additional actions - make this a sub menu // - first the main menu/action QMenu *submenu = new QMenu(appL[a].name, this); submenu->setIcon( LXDG::findIcon(appL[a].icon,"") ); //This is the normal behavior - not a special sub-action (although it needs to be at the top of the new menu) QAction *act = new QAction(LXDG::findIcon(appL[a].icon, ""), appL[a].name, this); act->setToolTip(appL[a].comment); act->setWhatsThis(appL[a].filePath); submenu->addAction(act); //Now add entries for every sub-action listed for(int sa=0; sa<appL[a].actions.length(); sa++){ QAction *sact = new QAction(LXDG::findIcon(appL[a].actions[sa].icon, appL[a].icon), appL[a].actions[sa].name, this); sact->setToolTip(appL[a].comment); sact->setWhatsThis("-action \""+appL[a].actions[sa].ID+"\" \""+appL[a].filePath+"\""); submenu->addAction(sact); } menu->addMenu(submenu); } } this->addMenu(menu); } emit AppMenuUpdated(); } //================= // PRIVATE SLOTS //================= void AppMenu::start(){ //Setup the watcher watcher->addPaths(LXDG::systemApplicationDirs()); //Now fill the menu the first time updateAppList(); } void AppMenu::watcherUpdate(){ updateAppList(); //Update the menu listings } void AppMenu::launchStore(){ LSession::LaunchApplication("lumina-open \""+appstorelink+"\""); } void AppMenu::launchControlPanel(){ LSession::LaunchApplication("lumina-open \""+controlpanellink+"\""); } void AppMenu::launchFileManager(){ QString fm = "lumina-open \""+QDir::homePath()+"\""; LSession::LaunchApplication(fm); } void AppMenu::launchApp(QAction *act){ QString appFile = act->whatsThis(); if(appFile.startsWith("-action")){ LSession::LaunchApplication("lumina-open "+appFile); //already has quotes put in place properly }else{ LSession::LaunchApplication("lumina-open \""+appFile+"\""); } } <commit_msg>Remove the "Browse Files" link from the application menu (does not fit well here - use other links instead).<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "AppMenu.h" #include "LSession.h" #include <LuminaOS.h> AppMenu::AppMenu(QWidget* parent) : QMenu(parent){ appstorelink = LOS::AppStoreShortcut(); //Default application "store" to display (AppCafe in PC-BSD) controlpanellink = LOS::ControlPanelShortcut(); //Default control panel APPS.clear(); watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(watcherUpdate()) ); //QTimer::singleShot(200, this, SLOT(start()) ); //Now start filling the menu start(); //do the initial run during session init so things are responsive immediately. connect(QApplication::instance(), SIGNAL(LocaleChanged()), this, SLOT(watcherUpdate()) ); connect(QApplication::instance(), SIGNAL(IconThemeChanged()), this, SLOT(watcherUpdate()) ); } AppMenu::~AppMenu(){ } QHash<QString, QList<XDGDesktop> >* AppMenu::currentAppHash(){ return &APPS; } //=========== // PRIVATE //=========== void AppMenu::updateAppList(){ //Make sure the title/icon are updated as well (in case of locale/icon change) this->setTitle(tr("Applications")); this->setIcon( LXDG::findIcon("system-run","") ); //Now update the lists this->clear(); APPS.clear(); QList<XDGDesktop> allfiles = LXDG::systemDesktopFiles(); APPS = LXDG::sortDesktopCats(allfiles); APPS.insert("All", LXDG::sortDesktopNames(allfiles)); lastHashUpdate = QDateTime::currentDateTime(); //Now fill the menu bool ok; //for checking inputs //Add link to the file manager //this->addAction( LXDG::findIcon("user-home", ""), tr("Browse Files"), this, SLOT(launchFileManager()) ); //--Look for the app store XDGDesktop store = LXDG::loadDesktopFile(appstorelink, ok); if(ok){ this->addAction( LXDG::findIcon(store.icon, ""), tr("Install Applications"), this, SLOT(launchStore()) ); } //--Look for the control panel store = LXDG::loadDesktopFile(controlpanellink, ok); if(ok){ this->addAction( LXDG::findIcon(store.icon, ""), tr("Control Panel"), this, SLOT(launchControlPanel()) ); } this->addSeparator(); //--Now create the sub-menus QStringList cats = APPS.keys(); cats.sort(); //make sure they are alphabetical for(int i=0; i<cats.length(); i++){ //Make sure they are translated and have the right icons QString name, icon; if(cats[i]=="All"){continue; } //skip this listing for the menu else if(cats[i] == "Multimedia"){ name = tr("Multimedia"); icon = "applications-multimedia"; } else if(cats[i] == "Development"){ name = tr("Development"); icon = "applications-development"; } else if(cats[i] == "Education"){ name = tr("Education"); icon = "applications-education"; } else if(cats[i] == "Game"){ name = tr("Games"); icon = "applications-games"; } else if(cats[i] == "Graphics"){ name = tr("Graphics"); icon = "applications-graphics"; } else if(cats[i] == "Network"){ name = tr("Network"); icon = "applications-internet"; } else if(cats[i] == "Office"){ name = tr("Office"); icon = "applications-office"; } else if(cats[i] == "Science"){ name = tr("Science"); icon = "applications-science"; } else if(cats[i] == "Settings"){ name = tr("Settings"); icon = "preferences-system"; } else if(cats[i] == "System"){ name = tr("System"); icon = "applications-system"; } else if(cats[i] == "Utility"){ name = tr("Utility"); icon = "applications-utilities"; } else if(cats[i] == "Wine"){ name = tr("Wine"); icon = "wine"; } else{ name = tr("Unsorted"); icon = "applications-other"; } QMenu *menu = new QMenu(name, this); menu->setIcon(LXDG::findIcon(icon,"")); connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(launchApp(QAction*)) ); QList<XDGDesktop> appL = APPS.value(cats[i]); for( int a=0; a<appL.length(); a++){ if(appL[a].actions.isEmpty()){ //Just a single entry point - no extra actions QAction *act = new QAction(LXDG::findIcon(appL[a].icon, ""), appL[a].name, this); act->setToolTip(appL[a].comment); act->setWhatsThis(appL[a].filePath); menu->addAction(act); }else{ //This app has additional actions - make this a sub menu // - first the main menu/action QMenu *submenu = new QMenu(appL[a].name, this); submenu->setIcon( LXDG::findIcon(appL[a].icon,"") ); //This is the normal behavior - not a special sub-action (although it needs to be at the top of the new menu) QAction *act = new QAction(LXDG::findIcon(appL[a].icon, ""), appL[a].name, this); act->setToolTip(appL[a].comment); act->setWhatsThis(appL[a].filePath); submenu->addAction(act); //Now add entries for every sub-action listed for(int sa=0; sa<appL[a].actions.length(); sa++){ QAction *sact = new QAction(LXDG::findIcon(appL[a].actions[sa].icon, appL[a].icon), appL[a].actions[sa].name, this); sact->setToolTip(appL[a].comment); sact->setWhatsThis("-action \""+appL[a].actions[sa].ID+"\" \""+appL[a].filePath+"\""); submenu->addAction(sact); } menu->addMenu(submenu); } } this->addMenu(menu); } emit AppMenuUpdated(); } //================= // PRIVATE SLOTS //================= void AppMenu::start(){ //Setup the watcher watcher->addPaths(LXDG::systemApplicationDirs()); //Now fill the menu the first time updateAppList(); } void AppMenu::watcherUpdate(){ updateAppList(); //Update the menu listings } void AppMenu::launchStore(){ LSession::LaunchApplication("lumina-open \""+appstorelink+"\""); } void AppMenu::launchControlPanel(){ LSession::LaunchApplication("lumina-open \""+controlpanellink+"\""); } void AppMenu::launchFileManager(){ QString fm = "lumina-open \""+QDir::homePath()+"\""; LSession::LaunchApplication(fm); } void AppMenu::launchApp(QAction *act){ QString appFile = act->whatsThis(); if(appFile.startsWith("-action")){ LSession::LaunchApplication("lumina-open "+appFile); //already has quotes put in place properly }else{ LSession::LaunchApplication("lumina-open \""+appFile+"\""); } } <|endoftext|>
<commit_before>#include "blockstream.h" #define MASK_5BIT 0x000001F #define MASK_10BIT 0x00003FF #define MASK_16BIT 0x000FFFF #define MASK_26BIT 0x3FFFFFF #define MASK_28BIT 0xFFFFFFF namespace redsea { uint16_t syndrome(int vec) { uint16_t synd_reg = 0x000; int bit,l; for (int k=25; k>=0; k--) { bit = (vec & (1 << k)); l = (synd_reg & 0x200); // Store lefmost bit of register synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x) synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x) } return synd_reg; } BlockStream::BlockStream() : has_sync_for_(5), group_data_(4), has_block_(5), bitcount_(0), left_to_read_(0), bit_stream_(), wideblock_(0), block_has_errors_(50) { offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4}; block_for_offset_ = {0, 1, 2, 2, 3}; error_lookup_ = { {0x200, 0b1000000000000000}, {0x300, 0b1100000000000000}, {0x180, 0b0110000000000000}, {0x0c0, 0b0011000000000000}, {0x060, 0b0001100000000000}, {0x030, 0b0000110000000000}, {0x018, 0b0000011000000000}, {0x00c, 0b0000001100000000}, {0x006, 0b0000000110000000}, {0x003, 0b0000000011000000}, {0x2dd, 0b0000000001100000}, {0x3b2, 0b0000000000110000}, {0x1d9, 0b0000000000011000}, {0x230, 0b0000000000001100}, {0x118, 0b0000000000000110}, {0x08c, 0b0000000000000011}, {0x046, 0b0000000000000001} }; } void BlockStream::uncorrectable() { printf(":offset %d not received\n",expected_offset_); int data_length = 0; // TODO: return partial group /*if (has_block_[A]) { data_length = 1; if (has_block_[B]) { data_length = 2; if (has_block_[C] || has_block_[CI]) { data_length = 3; } } }*/ block_has_errors_[block_counter_ % block_has_errors_.size()] = true; int erroneous_blocks = 0; for (bool e : block_has_errors_) { if (e) erroneous_blocks ++; } // Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2) if (is_in_sync_ && erroneous_blocks > 45) { is_in_sync_ = false; for (int i=0; i<block_has_errors_.size(); i++) block_has_errors_[i] = false; pi_ = 0x0000; printf(":too many errors, sync lost\n"); } for (int o=A; o<=D; o++) has_block_[o] = false; } std::vector<uint16_t> BlockStream::getNextGroup() { has_whole_group_ = false; while (!has_whole_group_ && !isEOF()) { // Compensate for clock slip corrections bitcount_ += 26 - left_to_read_; // Read from radio for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) { wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit(); } left_to_read_ = 26; wideblock_ &= MASK_28BIT; int block = (wideblock_ >> 1) & MASK_26BIT; // Find the offsets for which the syndrome is zero bool has_sync_for_any = false; for (int o=A; o<=D; o++) { has_sync_for_[o] = (syndrome(block ^ offset_word_[o]) == 0x000); has_sync_for_any |= has_sync_for_[o]; } // Acquire sync if (!is_in_sync_) { if (has_sync_for_any) { for (int o=A; o<=D; o++) { if (has_sync_for_[o]) { int dist = bitcount_ - prevbitcount_; if (dist % 26 == 0 && dist <= 156 && (block_for_offset_[prevsync_] + dist/26) % 4 == block_for_offset_[o]) { is_in_sync_ = true; expected_offset_ = o; printf(":sync!\n"); } else { prevbitcount_ = bitcount_; prevsync_ = o; } } } } } // Synchronous decoding if (is_in_sync_) { block_counter_ ++; uint16_t message = block >> 10; if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) { expected_offset_ = CI; } if ( !has_sync_for_[expected_offset_]) { // If message is a correct PI, error was probably in check bits if (expected_offset_ == A && message == pi_ && pi_ != 0) { has_sync_for_[A] = true; printf(":ignoring error in check bits\n"); } else if (expected_offset_ == C && message == pi_ && pi_ != 0) { has_sync_for_[CI] = true; printf(":ignoring error in check bits\n"); // Detect & correct clock slips (Section C.1.2) } else if (expected_offset_ == A && pi_ != 0 && ((wideblock_ >> 12) & MASK_16BIT) == pi_) { message = pi_; wideblock_ >>= 1; has_sync_for_[A] = true; printf(":clock slip corrected\n"); } else if (expected_offset_ == A && pi_ != 0 && ((wideblock_ >> 10) & MASK_16BIT) == pi_) { message = pi_; wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit(); has_sync_for_[A] = true; left_to_read_ = 25; printf(":clock slip corrected\n"); // Detect & correct burst errors (Section B.2.2) } else { uint16_t synd_reg = syndrome(block ^ offset_word_[expected_offset_]); if (pi_ != 0 && expected_offset_ == A) { printf(":expecting PI%04x, got %04x, xor %d, syndrome %03x\n", pi_, block>>10, pi_ ^ (block>>10), synd_reg); } if (error_lookup_.find(synd_reg) != error_lookup_.end()) { message = (block >> 10) ^ error_lookup_[synd_reg]; has_sync_for_[expected_offset_] = true; printf(":error corrected block %d using vector %04x for syndrome %03x\n", expected_offset_, error_lookup_[synd_reg], synd_reg); } } // Still no sync pulse if ( !has_sync_for_[expected_offset_]) { uncorrectable(); } } // Error-free block received if (has_sync_for_[expected_offset_]) { group_data_[block_for_offset_[expected_offset_]] = message; has_block_[expected_offset_] = true; if (expected_offset_ == A) { pi_ = message; } // Complete group received if (has_block_[A] && has_block_[B] && (has_block_[C] || has_block_[CI]) && has_block_[D]) { has_whole_group_ = true; } } expected_offset_ = (expected_offset_ == C ? D : (expected_offset_ + 1) % 5); if (expected_offset_ == A) { for (int o=A; o<=D; o++) has_block_[o] = false; } } } return group_data_; } bool BlockStream::isEOF() const { return bit_stream_.isEOF(); } } // namespace redsea <commit_msg>suppress integer warning<commit_after>#include "blockstream.h" #define MASK_5BIT 0x000001F #define MASK_10BIT 0x00003FF #define MASK_16BIT 0x000FFFF #define MASK_26BIT 0x3FFFFFF #define MASK_28BIT 0xFFFFFFF namespace redsea { uint16_t syndrome(int vec) { uint16_t synd_reg = 0x000; int bit,l; for (int k=25; k>=0; k--) { bit = (vec & (1 << k)); l = (synd_reg & 0x200); // Store lefmost bit of register synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x) synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x) } return synd_reg; } BlockStream::BlockStream() : has_sync_for_(5), group_data_(4), has_block_(5), bitcount_(0), left_to_read_(0), bit_stream_(), wideblock_(0), block_has_errors_(50) { offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4}; block_for_offset_ = {0, 1, 2, 2, 3}; error_lookup_ = { {0x200, 0b1000000000000000}, {0x300, 0b1100000000000000}, {0x180, 0b0110000000000000}, {0x0c0, 0b0011000000000000}, {0x060, 0b0001100000000000}, {0x030, 0b0000110000000000}, {0x018, 0b0000011000000000}, {0x00c, 0b0000001100000000}, {0x006, 0b0000000110000000}, {0x003, 0b0000000011000000}, {0x2dd, 0b0000000001100000}, {0x3b2, 0b0000000000110000}, {0x1d9, 0b0000000000011000}, {0x230, 0b0000000000001100}, {0x118, 0b0000000000000110}, {0x08c, 0b0000000000000011}, {0x046, 0b0000000000000001} }; } void BlockStream::uncorrectable() { printf(":offset %d not received\n",expected_offset_); int data_length = 0; // TODO: return partial group /*if (has_block_[A]) { data_length = 1; if (has_block_[B]) { data_length = 2; if (has_block_[C] || has_block_[CI]) { data_length = 3; } } }*/ block_has_errors_[block_counter_ % block_has_errors_.size()] = true; int erroneous_blocks = 0; for (bool e : block_has_errors_) { if (e) erroneous_blocks ++; } // Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2) if (is_in_sync_ && erroneous_blocks > 45) { is_in_sync_ = false; for (int i=0; i<(int)block_has_errors_.size(); i++) block_has_errors_[i] = false; pi_ = 0x0000; printf(":too many errors, sync lost\n"); } for (int o=A; o<=D; o++) has_block_[o] = false; } std::vector<uint16_t> BlockStream::getNextGroup() { has_whole_group_ = false; while (!has_whole_group_ && !isEOF()) { // Compensate for clock slip corrections bitcount_ += 26 - left_to_read_; // Read from radio for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) { wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit(); } left_to_read_ = 26; wideblock_ &= MASK_28BIT; int block = (wideblock_ >> 1) & MASK_26BIT; // Find the offsets for which the syndrome is zero bool has_sync_for_any = false; for (int o=A; o<=D; o++) { has_sync_for_[o] = (syndrome(block ^ offset_word_[o]) == 0x000); has_sync_for_any |= has_sync_for_[o]; } // Acquire sync if (!is_in_sync_) { if (has_sync_for_any) { for (int o=A; o<=D; o++) { if (has_sync_for_[o]) { int dist = bitcount_ - prevbitcount_; if (dist % 26 == 0 && dist <= 156 && (block_for_offset_[prevsync_] + dist/26) % 4 == block_for_offset_[o]) { is_in_sync_ = true; expected_offset_ = o; printf(":sync!\n"); } else { prevbitcount_ = bitcount_; prevsync_ = o; } } } } } // Synchronous decoding if (is_in_sync_) { block_counter_ ++; uint16_t message = block >> 10; if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) { expected_offset_ = CI; } if ( !has_sync_for_[expected_offset_]) { // If message is a correct PI, error was probably in check bits if (expected_offset_ == A && message == pi_ && pi_ != 0) { has_sync_for_[A] = true; printf(":ignoring error in check bits\n"); } else if (expected_offset_ == C && message == pi_ && pi_ != 0) { has_sync_for_[CI] = true; printf(":ignoring error in check bits\n"); // Detect & correct clock slips (Section C.1.2) } else if (expected_offset_ == A && pi_ != 0 && ((wideblock_ >> 12) & MASK_16BIT) == pi_) { message = pi_; wideblock_ >>= 1; has_sync_for_[A] = true; printf(":clock slip corrected\n"); } else if (expected_offset_ == A && pi_ != 0 && ((wideblock_ >> 10) & MASK_16BIT) == pi_) { message = pi_; wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit(); has_sync_for_[A] = true; left_to_read_ = 25; printf(":clock slip corrected\n"); // Detect & correct burst errors (Section B.2.2) } else { uint16_t synd_reg = syndrome(block ^ offset_word_[expected_offset_]); if (pi_ != 0 && expected_offset_ == A) { printf(":expecting PI%04x, got %04x, xor %d, syndrome %03x\n", pi_, block>>10, pi_ ^ (block>>10), synd_reg); } if (error_lookup_.find(synd_reg) != error_lookup_.end()) { message = (block >> 10) ^ error_lookup_[synd_reg]; has_sync_for_[expected_offset_] = true; printf(":error corrected block %d using vector %04x for syndrome %03x\n", expected_offset_, error_lookup_[synd_reg], synd_reg); } } // Still no sync pulse if ( !has_sync_for_[expected_offset_]) { uncorrectable(); } } // Error-free block received if (has_sync_for_[expected_offset_]) { group_data_[block_for_offset_[expected_offset_]] = message; has_block_[expected_offset_] = true; if (expected_offset_ == A) { pi_ = message; } // Complete group received if (has_block_[A] && has_block_[B] && (has_block_[C] || has_block_[CI]) && has_block_[D]) { has_whole_group_ = true; } } expected_offset_ = (expected_offset_ == C ? D : (expected_offset_ + 1) % 5); if (expected_offset_ == A) { for (int o=A; o<=D; o++) has_block_[o] = false; } } } return group_data_; } bool BlockStream::isEOF() const { return bit_stream_.isEOF(); } } // namespace redsea <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP # define LUABIND_FORMAT_SIGNATURE_081014_HPP #include <luabind/config.hpp> #include <luabind/lua_include.hpp> #include <luabind/typeid.hpp> #include <luabind/detail/meta.hpp> namespace luabind { namespace adl { class object; class argument; template <class Base> struct table; } // namespace adl using adl::object; using adl::argument; using adl::table; namespace detail { LUABIND_API std::string get_class_name(lua_State* L, type_id const& i); template <class T, class Enable = void> struct type_to_string { static void get(lua_State* L) { lua_pushstring(L, get_class_name(L, typeid(T)).c_str()); } }; template <class T> struct type_to_string<T*> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "*"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T&> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "&"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T const> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, " const"); lua_concat(L, 2); } }; # define LUABIND_TYPE_TO_STRING(x) \ template <> \ struct type_to_string<x> \ { \ static void get(lua_State* L) \ { \ lua_pushstring(L, #x); \ } \ }; # define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(unsigned x) LUABIND_INTEGRAL_TYPE_TO_STRING(char) LUABIND_INTEGRAL_TYPE_TO_STRING(short) LUABIND_INTEGRAL_TYPE_TO_STRING(int) LUABIND_INTEGRAL_TYPE_TO_STRING(long) LUABIND_TYPE_TO_STRING(void) LUABIND_TYPE_TO_STRING(bool) LUABIND_TYPE_TO_STRING(std::string) LUABIND_TYPE_TO_STRING(lua_State) LUABIND_TYPE_TO_STRING(luabind::object) LUABIND_TYPE_TO_STRING(luabind::argument) # undef LUABIND_INTEGRAL_TYPE_TO_STRING # undef LUABIND_TYPE_TO_STRING template <class Base> struct type_to_string<table<Base> > { static void get(lua_State* L) { lua_pushstring(L, "table"); } }; inline void format_signature_aux(lua_State*, bool, meta::type_list< >) {} template <class Signature> void format_signature_aux(lua_State* L, bool first, Signature) { if(!first) lua_pushstring(L, ","); type_to_string<typename meta::front<Signature>::type>::get(L); format_signature_aux(L, false, typename meta::pop_front<Signature>::type()); } template <class Signature> void format_signature(lua_State* L, char const* function, Signature) { using first = typename meta::front<Signature>::type; type_to_string<first>::get(L); lua_pushstring(L, " "); lua_pushstring(L, function); lua_pushstring(L, "("); format_signature_aux( L , true , typename meta::pop_front<Signature>::type() ); lua_pushstring(L, ")"); size_t sz = meta::size<Signature>::value; size_t ncat = sz * 2 + 2; if(sz == 1) ++ncat; lua_concat(L, ncat); } } // namespace detail } // namespace luabind #endif // LUABIND_FORMAT_SIGNATURE_081014_HPP <commit_msg>Fixed a "dead code" warning of Coverity Scan<commit_after>// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP # define LUABIND_FORMAT_SIGNATURE_081014_HPP #include <luabind/config.hpp> #include <luabind/lua_include.hpp> #include <luabind/typeid.hpp> #include <luabind/detail/meta.hpp> namespace luabind { namespace adl { class object; class argument; template <class Base> struct table; } // namespace adl using adl::object; using adl::argument; using adl::table; namespace detail { LUABIND_API std::string get_class_name(lua_State* L, type_id const& i); template <class T, class Enable = void> struct type_to_string { static void get(lua_State* L) { lua_pushstring(L, get_class_name(L, typeid(T)).c_str()); } }; template <class T> struct type_to_string<T*> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "*"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T&> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, "&"); lua_concat(L, 2); } }; template <class T> struct type_to_string<T const> { static void get(lua_State* L) { type_to_string<T>::get(L); lua_pushstring(L, " const"); lua_concat(L, 2); } }; # define LUABIND_TYPE_TO_STRING(x) \ template <> \ struct type_to_string<x> \ { \ static void get(lua_State* L) \ { \ lua_pushstring(L, #x); \ } \ }; # define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(unsigned x) LUABIND_INTEGRAL_TYPE_TO_STRING(char) LUABIND_INTEGRAL_TYPE_TO_STRING(short) LUABIND_INTEGRAL_TYPE_TO_STRING(int) LUABIND_INTEGRAL_TYPE_TO_STRING(long) LUABIND_TYPE_TO_STRING(void) LUABIND_TYPE_TO_STRING(bool) LUABIND_TYPE_TO_STRING(std::string) LUABIND_TYPE_TO_STRING(lua_State) LUABIND_TYPE_TO_STRING(luabind::object) LUABIND_TYPE_TO_STRING(luabind::argument) # undef LUABIND_INTEGRAL_TYPE_TO_STRING # undef LUABIND_TYPE_TO_STRING template <class Base> struct type_to_string<table<Base> > { static void get(lua_State* L) { lua_pushstring(L, "table"); } }; inline void format_signature_aux(lua_State*, bool, meta::type_list< >) {} template <class Signature> void format_signature_aux(lua_State* L, bool first, Signature) { if(!first) lua_pushstring(L, ","); type_to_string<typename meta::front<Signature>::type>::get(L); format_signature_aux(L, false, typename meta::pop_front<Signature>::type()); } template <class Signature> void format_signature(lua_State* L, char const* function, Signature) { using first = typename meta::front<Signature>::type; type_to_string<first>::get(L); lua_pushstring(L, " "); lua_pushstring(L, function); lua_pushstring(L, "("); format_signature_aux( L , true , typename meta::pop_front<Signature>::type() ); lua_pushstring(L, ")"); constexpr size_t ncat = meta::size<Signature>::value * 2 + 2 + (meta::size<Signature>::value == 1 ? 1 : 0); lua_concat(L, static_cast<int>(ncat)); } } // namespace detail } // namespace luabind #endif // LUABIND_FORMAT_SIGNATURE_081014_HPP <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include <gtest/gtest.h> #include "OgreRoot.h" #include "OgreSceneNode.h" #include "OgreEntity.h" #include "OgreCamera.h" #include "RootWithoutRenderSystemFixture.h" #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800) #include <random> using std::minstd_rand; #else #include <tr1/random> using std::tr1::minstd_rand; #endif using namespace Ogre; TEST(Root,shutdown) { Root root; root.shutdown(); } TEST(SceneManager,removeAndDestroyAllChildren) { Root root; SceneManager* sm = root.createSceneManager(); sm->getRootSceneNode()->createChildSceneNode(); sm->getRootSceneNode()->createChildSceneNode(); sm->getRootSceneNode()->removeAndDestroyAllChildren(); } static void createRandomEntityClones(Entity* ent, size_t cloneCount, const Vector3& min, const Vector3& max, SceneManager* mgr) { // we want cross platform consistent sequence minstd_rand rng; for (size_t n = 0; n < cloneCount; ++n) { // Create a new node under the root. SceneNode* node = mgr->createSceneNode(); // Random translate. Vector3 nodePos = max - min; nodePos.x *= float(rng())/rng.max(); nodePos.y *= float(rng())/rng.max(); nodePos.z *= float(rng())/rng.max(); nodePos += min; node->setPosition(nodePos); mgr->getRootSceneNode()->addChild(node); Entity* cloneEnt = ent->clone(StringConverter::toString(n)); // Attach to new node. node->attachObject(cloneEnt); } } struct SceneQueryTest : public RootWithoutRenderSystemFixture { SceneManager* mSceneMgr; Camera* mCamera; SceneNode* mCameraNode; void SetUp() { RootWithoutRenderSystemFixture::SetUp(); mSceneMgr = mRoot->createSceneManager(); mCamera = mSceneMgr->createCamera("Camera"); mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mCameraNode->attachObject(mCamera); mCameraNode->setPosition(0,0,500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); // Create a set of random balls Entity* ent = mSceneMgr->createEntity("501", "sphere.mesh", "General"); // stick one at the origin so one will always be hit by ray mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); createRandomEntityClones(ent, 500, Vector3(-2500,-2500,-2500), Vector3(2500,2500,2500), mSceneMgr); mSceneMgr->_updateSceneGraph(mCamera); } }; TEST_F(SceneQueryTest,Intersection) { IntersectionSceneQuery* intersectionQuery = mSceneMgr->createIntersectionQuery(); int expected[][2] = { {0, 391}, {1, 8}, {117, 128}, {118, 171}, {118, 24}, {121, 72}, {121, 95}, {132, 344}, {14, 227}, {14, 49}, {144, 379}, {151, 271}, {153, 28}, {164, 222}, {169, 212}, {176, 20}, {179, 271}, {185, 238}, {190, 47}, {193, 481}, {201, 210}, {205, 404}, {235, 366}, {239, 3}, {250, 492}, {256, 67}, {26, 333}, {260, 487}, {263, 272}, {265, 319}, {265, 472}, {270, 45}, {284, 329}, {289, 405}, {316, 80}, {324, 388}, {334, 337}, {336, 436}, {34, 57}, {340, 440}, {342, 41}, {348, 82}, {35, 478}, {372, 412}, {380, 460}, {398, 92}, {417, 454}, {432, 99}, {448, 79}, {498, 82}, {72, 77} }; IntersectionSceneQueryResult& results = intersectionQuery->execute(); EXPECT_EQ(results.movables2movables.size(), sizeof(expected)/sizeof(expected[0])); int i = 0; for (SceneQueryMovableIntersectionList::iterator mov = results.movables2movables.begin(); mov != results.movables2movables.end(); ++mov) { SceneQueryMovableObjectPair& thepair = *mov; // printf("{%d, %d},", StringConverter::parseInt(thepair.first->getName()), StringConverter::parseInt(thepair.second->getName())); ASSERT_EQ(expected[i][0], StringConverter::parseInt(thepair.first->getName())); ASSERT_EQ(expected[i][1], StringConverter::parseInt(thepair.second->getName())); i++; } // printf("\n"); } TEST_F(SceneQueryTest, Ray) { RaySceneQuery* rayQuery = mSceneMgr->createRayQuery(mCamera->getCameraToViewportRay(0.5, 0.5)); rayQuery->setSortByDistance(true, 2); RaySceneQueryResult& results = rayQuery->execute(); ASSERT_EQ("501", results[0].movable->getName()); ASSERT_EQ("397", results[1].movable->getName()); } <commit_msg>Tests: fix building on old MSVC<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include <gtest/gtest.h> #include "OgreRoot.h" #include "OgreSceneNode.h" #include "OgreEntity.h" #include "OgreCamera.h" #include "RootWithoutRenderSystemFixture.h" #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600) #include <random> using std::minstd_rand; #else #include <tr1/random> using std::tr1::minstd_rand; #endif using namespace Ogre; TEST(Root,shutdown) { Root root; root.shutdown(); } TEST(SceneManager,removeAndDestroyAllChildren) { Root root; SceneManager* sm = root.createSceneManager(); sm->getRootSceneNode()->createChildSceneNode(); sm->getRootSceneNode()->createChildSceneNode(); sm->getRootSceneNode()->removeAndDestroyAllChildren(); } static void createRandomEntityClones(Entity* ent, size_t cloneCount, const Vector3& min, const Vector3& max, SceneManager* mgr) { // we want cross platform consistent sequence minstd_rand rng; for (size_t n = 0; n < cloneCount; ++n) { // Create a new node under the root. SceneNode* node = mgr->createSceneNode(); // Random translate. Vector3 nodePos = max - min; nodePos.x *= float(rng())/rng.max(); nodePos.y *= float(rng())/rng.max(); nodePos.z *= float(rng())/rng.max(); nodePos += min; node->setPosition(nodePos); mgr->getRootSceneNode()->addChild(node); Entity* cloneEnt = ent->clone(StringConverter::toString(n)); // Attach to new node. node->attachObject(cloneEnt); } } struct SceneQueryTest : public RootWithoutRenderSystemFixture { SceneManager* mSceneMgr; Camera* mCamera; SceneNode* mCameraNode; void SetUp() { RootWithoutRenderSystemFixture::SetUp(); mSceneMgr = mRoot->createSceneManager(); mCamera = mSceneMgr->createCamera("Camera"); mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mCameraNode->attachObject(mCamera); mCameraNode->setPosition(0,0,500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); // Create a set of random balls Entity* ent = mSceneMgr->createEntity("501", "sphere.mesh", "General"); // stick one at the origin so one will always be hit by ray mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); createRandomEntityClones(ent, 500, Vector3(-2500,-2500,-2500), Vector3(2500,2500,2500), mSceneMgr); mSceneMgr->_updateSceneGraph(mCamera); } }; TEST_F(SceneQueryTest,Intersection) { IntersectionSceneQuery* intersectionQuery = mSceneMgr->createIntersectionQuery(); int expected[][2] = { {0, 391}, {1, 8}, {117, 128}, {118, 171}, {118, 24}, {121, 72}, {121, 95}, {132, 344}, {14, 227}, {14, 49}, {144, 379}, {151, 271}, {153, 28}, {164, 222}, {169, 212}, {176, 20}, {179, 271}, {185, 238}, {190, 47}, {193, 481}, {201, 210}, {205, 404}, {235, 366}, {239, 3}, {250, 492}, {256, 67}, {26, 333}, {260, 487}, {263, 272}, {265, 319}, {265, 472}, {270, 45}, {284, 329}, {289, 405}, {316, 80}, {324, 388}, {334, 337}, {336, 436}, {34, 57}, {340, 440}, {342, 41}, {348, 82}, {35, 478}, {372, 412}, {380, 460}, {398, 92}, {417, 454}, {432, 99}, {448, 79}, {498, 82}, {72, 77} }; IntersectionSceneQueryResult& results = intersectionQuery->execute(); EXPECT_EQ(results.movables2movables.size(), sizeof(expected)/sizeof(expected[0])); int i = 0; for (SceneQueryMovableIntersectionList::iterator mov = results.movables2movables.begin(); mov != results.movables2movables.end(); ++mov) { SceneQueryMovableObjectPair& thepair = *mov; // printf("{%d, %d},", StringConverter::parseInt(thepair.first->getName()), StringConverter::parseInt(thepair.second->getName())); ASSERT_EQ(expected[i][0], StringConverter::parseInt(thepair.first->getName())); ASSERT_EQ(expected[i][1], StringConverter::parseInt(thepair.second->getName())); i++; } // printf("\n"); } TEST_F(SceneQueryTest, Ray) { RaySceneQuery* rayQuery = mSceneMgr->createRayQuery(mCamera->getCameraToViewportRay(0.5, 0.5)); rayQuery->setSortByDistance(true, 2); RaySceneQueryResult& results = rayQuery->execute(); ASSERT_EQ("501", results[0].movable->getName()); ASSERT_EQ("397", results[1].movable->getName()); } <|endoftext|>
<commit_before>// Catch #include <catch.hpp> #include <helper.hpp> // C++ Standard Library #include <cmath> #include <array> // Mantella #include <mantella> TEST_CASE("geometry: get2DRotationMatrix(...)", "") { SECTION("Generates 2D rotation matrix") { const std::array<double, 15>& angles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 360.0, -0.0, -45.0, -90.0, -180.0, -225.0, -315.0}}; for (const auto& angle : angles) { arma::Mat<double>::fixed<2, 2> expected({ std::cos(angle), -std::sin(angle), std::sin(angle), std::cos(angle) }); compare(mant::get2DRotationMatrix(angle), expected); } } } TEST_CASE("geometry: get3DRotationMatrix(...)", "") { SECTION("Generates 3D rotation matrix") { const std::array<double, 14>& rollAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -45, 276, -56, -45.89}}; const std::array<double, 14>& pitchAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -90, -89, 78, -245}}; const std::array<double, 14>& yawAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -225, -310, -90, 345}}; for (const auto& rollAngle : rollAngles) { for (const auto& pitchAngle : pitchAngles) { for (const auto& yawAngle : yawAngles) { arma::Mat<double>::fixed<3, 3> expectedRoll({ 1.0, 0.0, 0.0, 0.0, std::cos(rollAngle), -std::sin(rollAngle), 0.0, std::sin(rollAngle), std::cos(rollAngle), }); arma::Mat<double>::fixed<3, 3> expectedPitch({ std::cos(pitchAngle), 0.0, std::sin(pitchAngle), 0.0, 1.0, 0.0, -std::sin(pitchAngle), 0.0, std::cos(pitchAngle) }); arma::Mat<double>::fixed<3, 3> expectedYaw({ std::cos(yawAngle), -std::sin(yawAngle), 0.0, std::sin(yawAngle), std::cos(yawAngle), 0.0, 0.0, 0.0, 1.0 }); compare<double>(mant::get3DRotationMatrix(rollAngle, pitchAngle, yawAngle), expectedRoll * expectedPitch * expectedYaw); } } } } } TEST_CASE("geometry: getCircleCircleIntersection(...)", "") { SECTION("Finds intersection") { arma::Col<double>::fixed<2> expected; expected = {-2.5522451636, 1.8231290303}; compare(mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-1.5, 2.4}, 1.2), expected); expected = {-0.1804143359, 0.9753358195}; compare(mant::getCircleCircleIntersection({1.8, -2.5}, 4.0, {-3.0, 2.0}, 3.0), expected); } SECTION("Throws an exception, if both centers are on the same spot") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-2.0, 3.0}, 1.3), std::logic_error); } SECTION("Throws an exception, if the circles are to far apart") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-8.0, 3.0}, 1.3, {-2.0, 3.0}, 1.3), std::logic_error); } SECTION("Throws an exception, if a circle is enclosed by the other one") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-2.0, 2.8}, 0.3, {-2.0, 3.0}, 1.3), std::logic_error); } } TEST_CASE("geometry: getCircleSphereIntersection(...)", "") { SECTION("Finds intersection") { arma::Col<double>::fixed<3> expected; expected = {-2.095, 1.1962336728, 0.0}; compare(mant::getCircleSphereIntersection({-2.0, 0.0, 0.0}, 1.2, {0.0, 0.0, 1.0}, {-3.0, 0.0, 0.0}, 1.5), expected); expected = {-2.5522451636, 1.8231290303, 0.0}; compare(mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 1.3, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 1.2), expected); expected = {-0.1804143359, 0.9753358195, 0.0}; compare(mant::getCircleSphereIntersection({1.8, -2.5, 0.0}, 4.0, {0.0, 0.0, 1.0}, {-3.0, 2.0, 0.0}, 3.0), expected); } } <commit_msg>test: Added exception tests for geometry.hpp<commit_after>// Catch #include <catch.hpp> #include <helper.hpp> // C++ Standard Library #include <cmath> #include <array> // Mantella #include <mantella> TEST_CASE("geometry: get2DRotationMatrix(...)", "") { SECTION("Generates 2D rotation matrix") { const std::array<double, 15>& angles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 360.0, -0.0, -45.0, -90.0, -180.0, -225.0, -315.0}}; for (const auto& angle : angles) { arma::Mat<double>::fixed<2, 2> expected({ std::cos(angle), -std::sin(angle), std::sin(angle), std::cos(angle) }); compare(mant::get2DRotationMatrix(angle), expected); } } } TEST_CASE("geometry: get3DRotationMatrix(...)", "") { SECTION("Generates 3D rotation matrix") { const std::array<double, 14>& rollAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -45, 276, -56, -45.89}}; const std::array<double, 14>& pitchAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -90, -89, 78, -245}}; const std::array<double, 14>& yawAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -225, -310, -90, 345}}; for (const auto& rollAngle : rollAngles) { for (const auto& pitchAngle : pitchAngles) { for (const auto& yawAngle : yawAngles) { arma::Mat<double>::fixed<3, 3> expectedRoll({ 1.0, 0.0, 0.0, 0.0, std::cos(rollAngle), -std::sin(rollAngle), 0.0, std::sin(rollAngle), std::cos(rollAngle), }); arma::Mat<double>::fixed<3, 3> expectedPitch({ std::cos(pitchAngle), 0.0, std::sin(pitchAngle), 0.0, 1.0, 0.0, -std::sin(pitchAngle), 0.0, std::cos(pitchAngle) }); arma::Mat<double>::fixed<3, 3> expectedYaw({ std::cos(yawAngle), -std::sin(yawAngle), 0.0, std::sin(yawAngle), std::cos(yawAngle), 0.0, 0.0, 0.0, 1.0 }); compare<double>(mant::get3DRotationMatrix(rollAngle, pitchAngle, yawAngle), expectedRoll * expectedPitch * expectedYaw); } } } } } TEST_CASE("geometry: getCircleCircleIntersection(...)", "") { SECTION("Finds intersection") { arma::Col<double>::fixed<2> expected; expected = {-2.5522451636, 1.8231290303}; compare(mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-1.5, 2.4}, 1.2), expected); expected = {-0.1804143359, 0.9753358195}; compare(mant::getCircleCircleIntersection({1.8, -2.5}, 4.0, {-3.0, 2.0}, 3.0), expected); } SECTION("Throws an exception, if both centers are on the same spot") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-2.0, 3.0}, 1.3), std::logic_error); } SECTION("Throws an exception, if the circles are to far apart") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-8.0, 3.0}, 1.3, {-2.0, 3.0}, 1.3), std::logic_error); } SECTION("Throws an exception, if the first circle is enclosed by second one") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({-4.0, 2.8}, 0.3, {-4.0, 3.0}, 1.3), std::logic_error); } SECTION("Throws an exception, if the second circle is enclosed by first one") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({6.8, 1.4}, 2.0, {6.5, 1.2}, 0.1), std::logic_error); } SECTION("Throws an exception, if any radius is 0 or negative.") { CHECK_THROWS_AS(mant::getCircleCircleIntersection({1.8, -2.5}, 0.0, {1.8, 0.5}, 3.0), std::logic_error); CHECK_THROWS_AS(mant::getCircleCircleIntersection({1.8, -2.5}, 4.0, {-3.0, 2.0}, -3.0), std::logic_error); } } TEST_CASE("geometry: getCircleSphereIntersection(...)", "") { SECTION("Finds intersection") { arma::Col<double>::fixed<3> expected; expected = {-2.095, 1.1962336728, 0.0}; compare(mant::getCircleSphereIntersection({-2.0, 0.0, 0.0}, 1.2, {0.0, 0.0, 1.0}, {-3.0, 0.0, 0.0}, 1.5), expected); expected = {-2.5522451636, 1.8231290303, 0.0}; compare(mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 1.3, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 1.2), expected); expected = {-0.1804143359, 0.9753358195, 0.0}; compare(mant::getCircleSphereIntersection({1.8, -2.5, 0.0}, 4.0, {0.0, 0.0, 1.0}, {-3.0, 2.0, 0.0}, 3.0), expected); } SECTION("Throws an exception, if both centers are on the same spot") { CHECK_THROWS_AS(mant::getCircleSphereIntersection({-2.0, 0.0, 0.0}, 1.2, {0.0, 0.0, 1.0}, {-2.0, 0.0, 0.0}, 1.5), std::logic_error); } SECTION("Throws an exception, if the circle and sphere are to far apart") { CHECK_THROWS_AS(mant::getCircleSphereIntersection({-7.0, 3.0, 0.0}, 1.3, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 1.2), std::logic_error); } SECTION("Throws an exception, if the circle is enclosed by the sphere") { CHECK_THROWS_AS(mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 1.3, {0.0, 1.0, 1.0}, {-1.5, 2.4, 0.0}, 5.0), std::logic_error); } SECTION("Throws an exception, if the sphere is enclosed by the circle") { CHECK_THROWS_AS(mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 6.3, {0.0, 1.0, 1.0}, {-1.5, 2.4, 0.0}, 0.2), std::logic_error); } SECTION("Throws an exception, if any radius is 0 or negative.") { CHECK_THROWS_AS(mant::getCircleSphereIntersection({-1.5, 3.4, 0.0}, 1.0, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 0.0), std::logic_error); CHECK_THROWS_AS(mant::getCircleSphereIntersection({1.8, -2.5, 0.0}, -4.0, {0.0, 0.0, 1.0}, {-3.0, 2.0, 0.0}, 3.0), std::logic_error); } } <|endoftext|>
<commit_before>#include "alloGLV/al_ControlGLV.hpp" namespace al{ bool GLVInputControl::onMouseDown(const Mouse& m){ glv::space_t xrel=m.x(), yrel=m.y(); glv().setMouseDown(xrel,yrel, m.button(), 0); glv().setMousePos(m.x(), m.y(), xrel, yrel); return !glv().propagateEvent(); } bool GLVInputControl::onMouseUp(const al::Mouse& m){ glv::space_t xrel, yrel; glv().setMouseUp(xrel,yrel, m.button(), 0); glv().setMousePos(m.x(), m.y(), xrel, yrel); return !glv().propagateEvent(); } bool GLVInputControl::keyToGLV(const al::Keyboard& k, bool down){ down ? glv().setKeyDown(k.key()) : glv().setKeyUp(k.key()); const_cast<glv::Keyboard*>(&glv().keyboard())->alt(k.alt()); const_cast<glv::Keyboard*>(&glv().keyboard())->caps(k.caps()); const_cast<glv::Keyboard*>(&glv().keyboard())->ctrl(k.ctrl()); const_cast<glv::Keyboard*>(&glv().keyboard())->meta(k.meta()); const_cast<glv::Keyboard*>(&glv().keyboard())->shift(k.shift()); return glv().propagateEvent(); } bool GLVWindowControl::onCreate(){ glv().broadcastEvent(glv::Event::WindowCreate); return true; } bool GLVWindowControl::onDestroy(){ glv().broadcastEvent(glv::Event::WindowDestroy); return true; } bool GLVWindowControl::onResize(int dw, int dh){ glv().extent(glv().width() + dw, glv().height() + dh); //printf("GLVWindowControl onResize: %d %d %f %f\n", dw, dh, glv().width(), glv().height()); glv().broadcastEvent(glv::Event::WindowResize); return true; } GLVDetachable::GLVDetachable() : glv::GLV(0,0), mParentWindow(NULL), mInputControl(*this), mWindowControl(*this) { init(); } GLVDetachable::GLVDetachable(Window& parent) : glv::GLV(0,0), mInputControl(*this), mWindowControl(*this) { parentWindow(parent); init(); } static void ntDetachedButton(const glv::Notification& n){ GLVDetachable * R = n.receiver<GLVDetachable>(); if(n.sender<glv::Button>()->getValue()){ R->detached(true); } else{ R->detached(false); } } void GLVDetachable::init(){ mDetachedButton.attach(ntDetachedButton, glv::Update::Value, this); mDetachedButton.disable(glv::Momentary); mDetachedButton.symbolOn(glv::draw::viewChild); mDetachedButton.symbolOff(glv::draw::viewSibling); mDetachedButton.disable(glv::DrawBorder); stretch(1,1); this->disable(glv::DrawBack); } void GLVDetachable::addGUI(Window& w){ w.prepend(mInputControl); w.append(mWindowControl); } void GLVDetachable::remGUI(Window& w){ w.remove(mInputControl); w.remove(mWindowControl); } GLVDetachable& GLVDetachable::detached(bool v){ if(v && !detached()){ // is not detached if(mParentWindow){ remGUI(parentWindow()); } glv::Rect ru = unionOfChildren(); enable(glv::DrawBack); { glv::View * cv = child; while(cv){ cv->posAdd(-ru.l, -ru.t); cv = cv->sibling; } } //ru.print(); //posAdd(-ru.l, -ru.t); detachedWindow().create(Window::Dim(ru.w, ru.h)); addGUI(detachedWindow()); } else if(detached()){ // is currently detached, attach back to parent, if any remGUI(detachedWindow()); detachedWindow().destroy(); if(mParentWindow){ disable(glv::DrawBack); pos(0,0); addGUI(parentWindow()); } } return *this; } GLVDetachable& GLVDetachable::parentWindow(Window& v){ if(&v != mParentWindow){ if(!detached()){ if(mParentWindow){ remGUI(parentWindow()); } mParentWindow = &v; disable(glv::DrawBack); addGUI(parentWindow()); //printf("%d\n", parentWindow().created()); } else{ mParentWindow = &v; } } return *this; } } // al:: <commit_msg>fix problem with mouse x,y state when detaching GUI<commit_after>#include "alloGLV/al_ControlGLV.hpp" namespace al{ bool GLVInputControl::onMouseDown(const Mouse& m){ glv::space_t xrel=m.x(), yrel=m.y(); glv().setMouseDown(xrel,yrel, m.button(), 0); glv().setMousePos(m.x(), m.y(), xrel, yrel); return !glv().propagateEvent(); } bool GLVInputControl::onMouseUp(const al::Mouse& m){ glv::space_t xrel, yrel; glv().setMouseUp(xrel,yrel, m.button(), 0); glv().setMousePos(m.x(), m.y(), xrel, yrel); return !glv().propagateEvent(); } bool GLVInputControl::keyToGLV(const al::Keyboard& k, bool down){ down ? glv().setKeyDown(k.key()) : glv().setKeyUp(k.key()); const_cast<glv::Keyboard*>(&glv().keyboard())->alt(k.alt()); const_cast<glv::Keyboard*>(&glv().keyboard())->caps(k.caps()); const_cast<glv::Keyboard*>(&glv().keyboard())->ctrl(k.ctrl()); const_cast<glv::Keyboard*>(&glv().keyboard())->meta(k.meta()); const_cast<glv::Keyboard*>(&glv().keyboard())->shift(k.shift()); return glv().propagateEvent(); } bool GLVWindowControl::onCreate(){ glv().broadcastEvent(glv::Event::WindowCreate); return true; } bool GLVWindowControl::onDestroy(){ glv().broadcastEvent(glv::Event::WindowDestroy); return true; } bool GLVWindowControl::onResize(int dw, int dh){ glv().extent(glv().width() + dw, glv().height() + dh); //printf("GLVWindowControl onResize: %d %d %f %f\n", dw, dh, glv().width(), glv().height()); glv().broadcastEvent(glv::Event::WindowResize); return true; } GLVDetachable::GLVDetachable() : glv::GLV(0,0), mParentWindow(NULL), mInputControl(*this), mWindowControl(*this) { init(); } GLVDetachable::GLVDetachable(Window& parent) : glv::GLV(0,0), mInputControl(*this), mWindowControl(*this) { parentWindow(parent); init(); } static void ntDetachedButton(const glv::Notification& n){ GLVDetachable * R = n.receiver<GLVDetachable>(); //if(R->mouse().isDown()) return; if(n.sender<glv::Button>()->getValue()){ R->detached(true); } else{ R->detached(false); } } void GLVDetachable::init(){ mDetachedButton.attach(ntDetachedButton, glv::Update::Value, this); mDetachedButton.disable(glv::Momentary); mDetachedButton.symbolOn(glv::draw::viewChild); mDetachedButton.symbolOff(glv::draw::viewSibling); mDetachedButton.disable(glv::DrawBorder); stretch(1,1); this->disable(glv::DrawBack); } void GLVDetachable::addGUI(Window& w){ w.prepend(mInputControl); w.append(mWindowControl); } void GLVDetachable::remGUI(Window& w){ w.remove(mInputControl); w.remove(mWindowControl); } GLVDetachable& GLVDetachable::detached(bool v){ if(v && !detached()){ // is not detached if(mParentWindow){ remGUI(parentWindow()); } glv::Rect ru = unionOfChildren(); enable(glv::DrawBack); { glv::View * cv = child; while(cv){ cv->posAdd(-ru.l, -ru.t); cv = cv->sibling; } } //ru.print(); //posAdd(-ru.l, -ru.t); //detachedWindow().create(Window::Dim(ru.w, ru.h)); int pl=0, pt=0; if(mParentWindow){ pl = parentWindow().dimensions().l; pt = parentWindow().dimensions().t; //printf("%d %d\n", pl, pt); } detachedWindow().create(Window::Dim(pl, pt, ru.w, ru.h)); addGUI(detachedWindow()); } else if(detached()){ // is currently detached, attach back to parent, if any remGUI(detachedWindow()); detachedWindow().destroy(); if(mParentWindow){ disable(glv::DrawBack); pos(0,0); addGUI(parentWindow()); } } // This is a hack to ensure all GLV mouse button states are "up" (false). // Because the GLV changes windows between mouse down and mouse up calls, // the mouse relative position gets into an inconsistent state on mouse up. const int mx = mouse().x(); const int my = mouse().y(); for(int i=0; i<GLV_MAX_MOUSE_BUTTONS; ++i){ glv::space_t x=mx,y=my; setMouseUp(x,y, i, 1); } return *this; } GLVDetachable& GLVDetachable::parentWindow(Window& v){ if(&v != mParentWindow){ if(!detached()){ if(mParentWindow){ remGUI(parentWindow()); } mParentWindow = &v; disable(glv::DrawBack); addGUI(parentWindow()); //printf("%d\n", parentWindow().created()); } else{ mParentWindow = &v; } } return *this; } } // al:: <|endoftext|>
<commit_before>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_filter_tests.cpp * @brief filter 対応テスト * * @author t.sirayanagi * @version 1.0 * * @par copyright * Copyright (C) 2012-2014, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "../include/iutest.hpp" IUTEST(Test, Fail) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Fail, Test) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Foo, Bar) { IUTEST_ASSERT_EQ(3, 3); } IUTEST(Foo, Baz) { IUTEST_ASSERT_EQ(3, 3); } IUTEST(Foo, BarFail) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Foo, Qux) { IUTEST_ASSERT_EQ(3, 3); } #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { IUTEST_INIT(&argc, argv); { ::iutest::IUTEST_FLAG(filter) = "*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret == 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "Foo.Bar"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "***.Bar"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "???.Ba?"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "Foo.Ba*-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "Foo.Ba*:-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret == 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "*Baz*:*Qux*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = ":::*Baz*:::::*Qux*:::"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } printf("*** Successful ***\n"); return 0; } <commit_msg>update r517<commit_after>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_filter_tests.cpp * @brief filter 対応テスト * * @author t.sirayanagi * @version 1.0 * * @par copyright * Copyright (C) 2012-2014, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "../include/iutest.hpp" IUTEST(Test, Fail) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Fail, Test) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Foo, Bar) { IUTEST_ASSERT_EQ(3, 3); } IUTEST(Foo, Baz) { IUTEST_ASSERT_EQ(3, 3); } IUTEST(Foo, BarFail) { IUTEST_ASSERT_EQ(2, 3); } IUTEST(Foo, Qux) { IUTEST_ASSERT_EQ(3, 3); } #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { IUTEST_INIT(&argc, argv); { ::iutest::IUTEST_FLAG(filter) = "*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret == 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "Foo.Bar"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "***.Bar"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "???.Ba?"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = "Foo.Ba*-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } #if !defined(IUTEST_USE_GTEST) { ::iutest::IUTEST_FLAG(filter) = "Foo.Ba*:-*Fail*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret == 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } #endif { ::iutest::IUTEST_FLAG(filter) = "*Baz*:*Qux*"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } { ::iutest::IUTEST_FLAG(filter) = ":::*Baz*:::::*Qux*:::"; const int ret = IUTEST_RUN_ALL_TESTS(); if( ret != 0 ) return 1; #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 ); IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 ); #endif } printf("*** Successful ***\n"); return 0; } <|endoftext|>
<commit_before>/** * @file main.cpp * * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include <cmath> #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include "StateSpace.h" #include "PriorityQueue.h" #include "State.h" #include "encoder.h" #include "CreateModule.h" /** * @brief Gives a std::string representation of a primitive type. * * @remark Can be used to print priority queue contents. * @param x Primitive type such as int, double, long ... * @return std::string conversion of param x */ template<typename T> std::string to_string(T x) { return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str(); } /** * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system. * * This function computes a normal distribution over the parameterised number of loop iterations in order * to provide a function which explores the state space dilligently initially which then decays off to the * optimal solution after a large number of loop iterations. * * The normal distribution used by this function is: * * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f] * * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset. * * @param t Number of loop iterations. * @return Value of normal distribution at t loop iterations. */ double temperature(unsigned long t); //function to select next action /** * @brief Selects an action to perform based on experience, iterations and probabilities. * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param iterations Number of loop iterations completed. * @return integer corresponding to chosen action */ int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations); /** * @brief Updates the utility (Q-value) of the system. * * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation, * * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f] * * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1. * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate * "living in the moment", whilst higher values indicate "planning for the future". * * @param space Reference to StateSpace object * @param action Integer code to previous performed action * @param new_state Reference to State instance giving the new system state * @param old_state Reference to State instance giving the old system state * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1]) * @param gamma Discount factor applied to q-learning equation (in the interval [0,1]) */ void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma); /** * @brief Program launcher! * * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update * utilities and choose most optimal actions to perform based on position and velocity. * * @return Program exit code */ int main() { // STUFF WE DONT UNDERSTAND, AND DONT NEED TO //__________________________________________________________________________________________ //__________________________________________________________________________________________ // Libraries to load std::string bodyLibName = "bodyinfo"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string bodyModuleName = "BodyInfo"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "MotionTimingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch (...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); CreateModule(movementLibName, movementModuleName, broker, false, true); CreateModule(bodyLibName, bodyModuleName, broker, false, true); AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport); AL::ALProxy movementToolsProxy(movementModuleName, pip, pport); AL::ALMotionProxy motion(pip, pport); //__________________________________________________________________________________________ //__________________________________________________________________________________________ //END OF STUFF WE DONT UNDERSTAND, BREATHE NOW //learning factor const double alpha = 0.5; //discount factor const double gamma = 0.5; //seed rng std::srand(static_cast<unsigned int>(std::time(NULL))); int action_forwards = FORWARD; int action_backwards = BACKWARD; int chosen_action = action_forwards; //create a priority queue to copy to all the state space priority queues PriorityQueue<int, double> initiator_queue(MAX); initiator_queue.enqueueWithPriority(action_forwards, 0); initiator_queue.enqueueWithPriority(action_backwards, 0); //create encoder Encoder encoder; encoder.Calibrate(); qi::os::msleep(5000); //create the state space StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue); //state objects State current_state(0, 0, FORWARD); State old_state(0, 0, FORWARD); unsigned long i = 0; while (true) { // set current state angle to angle received from encoder // and set current state velocity to difference in new and // old state angles over some time difference current_state.theta = M_PI * (encoder.GetAngle()) / 180; current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action); // call updateQ function with state space, old and current states // and learning rate, discount factor updateQ(space, chosen_action, old_state, current_state, alpha, gamma); // set old_state to current_state old_state = current_state; // determine chosen_action for current state chosen_action = selectAction(space[current_state], i); // depending upon chosen action, call robot movement tools proxy with either // swingForwards or swingBackwards commands. (chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards"); ++i; } return 1; } double temperature(unsigned long t) { return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset } int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) { typedef std::vector<std::pair<int, double> > VecPair ; //turn priority queue into a vector of pairs VecPair vec = a_queue.saveOrderedQueueAsVector(); //sum for partition function double sum = 0.0; // calculate partition function by iterating over action-values for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { sum += std::exp((iter->second) / temperature(iterations)); } // compute Boltzmann factors for action-values and enqueue to vec for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) { iter->second = std::exp(iter->second / temperature(iterations)) / sum; } // calculate cumulative probability distribution for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) { //second member of pair becomes addition of its current value //and that of the index before it iter->second += (iter-1)->second; } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached } void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) { //oldQ value reference double oldQ = space[old_state].search(action).second; //reward given to current state double R = new_state.getReward(); //optimal Q value for new state i.e. first element double maxQ = space[new_state].peekFront().second; //new Q value determined by Q learning algorithm double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ); // change priority of action to new Q value space[old_state].changePriority(action, newQ); } /* OLD SELECT ACTION int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) { /* // queue to store action values PriorityQueue<int, double> actionQueue(MAX); double sum = 0.0; // calculate partition function by iterating over action-values for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) { sum += std::exp((iter->second) / temperature(iterations)); } // compute Boltzmann factors for action-values and enqueue to actionQueue for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) { double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum; actionQueue.enqueueWithPriority(iter.operator*().first, priority); } // calculate cumulative probability distribution for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) { // change priority of it1->first data item in actionQueue to // sum of priorities of it1 and it2 items actionQueue.changePriority(it1->first, it1->second + it2->second); } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached double rand_num = static_cast<double>(rand()) / RAND_MAX; return (rand_num > 0.5)?0:1; } */ <commit_msg>renamed temperature to be more descriptive<commit_after>/** * @file main.cpp * * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include <cmath> #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include "StateSpace.h" #include "PriorityQueue.h" #include "State.h" #include "encoder.h" #include "CreateModule.h" /** * @brief Gives a std::string representation of a primitive type. * * @remark Can be used to print priority queue contents. * @param x Primitive type such as int, double, long ... * @return std::string conversion of param x */ template<typename T> std::string to_string(T x) { return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str(); } /** * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system. * * This function computes a normal distribution over the parameterised number of loop iterations in order * to provide a function which explores the state space dilligently initially which then decays off to the * optimal solution after a large number of loop iterations. * * The normal distribution used by this function is: * * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f] * * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset. * * @param t Number of loop iterations. * @return Value of normal distribution at t loop iterations. */ double probabilityFluxDensityCoeffieicent(unsigned long t); //function to select next action /** * @brief Selects an action to perform based on experience, iterations and probabilities. * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param iterations Number of loop iterations completed. * @return integer corresponding to chosen action */ int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations); /** * @brief Updates the utility (Q-value) of the system. * * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation, * * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f] * * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1. * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate * "living in the moment", whilst higher values indicate "planning for the future". * * @param space Reference to StateSpace object * @param action Integer code to previous performed action * @param new_state Reference to State instance giving the new system state * @param old_state Reference to State instance giving the old system state * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1]) * @param gamma Discount factor applied to q-learning equation (in the interval [0,1]) */ void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma); /** * @brief Program launcher! * * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update * utilities and choose most optimal actions to perform based on position and velocity. * * @return Program exit code */ int main() { // STUFF WE DONT UNDERSTAND, AND DONT NEED TO //__________________________________________________________________________________________ //__________________________________________________________________________________________ // Libraries to load std::string bodyLibName = "bodyinfo"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string bodyModuleName = "BodyInfo"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "MotionTimingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch (...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); CreateModule(movementLibName, movementModuleName, broker, false, true); CreateModule(bodyLibName, bodyModuleName, broker, false, true); AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport); AL::ALProxy movementToolsProxy(movementModuleName, pip, pport); AL::ALMotionProxy motion(pip, pport); //__________________________________________________________________________________________ //__________________________________________________________________________________________ //END OF STUFF WE DONT UNDERSTAND, BREATHE NOW //learning factor const double alpha = 0.5; //discount factor const double gamma = 0.5; //seed rng std::srand(static_cast<unsigned int>(std::time(NULL))); int action_forwards = FORWARD; int action_backwards = BACKWARD; int chosen_action = action_forwards; //create a priority queue to copy to all the state space priority queues PriorityQueue<int, double> initiator_queue(MAX); initiator_queue.enqueueWithPriority(action_forwards, 0); initiator_queue.enqueueWithPriority(action_backwards, 0); //create encoder Encoder encoder; encoder.Calibrate(); qi::os::msleep(5000); //create the state space StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue); //state objects State current_state(0, 0, FORWARD); State old_state(0, 0, FORWARD); unsigned long i = 0; while (true) { // set current state angle to angle received from encoder // and set current state velocity to difference in new and // old state angles over some time difference current_state.theta = M_PI * (encoder.GetAngle()) / 180; current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action); // call updateQ function with state space, old and current states // and learning rate, discount factor updateQ(space, chosen_action, old_state, current_state, alpha, gamma); // set old_state to current_state old_state = current_state; // determine chosen_action for current state chosen_action = selectAction(space[current_state], i); // depending upon chosen action, call robot movement tools proxy with either // swingForwards or swingBackwards commands. (chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards"); ++i; } return 1; } double probabilityFluxDensityCoeffieicent(unsigned long t) { return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset } int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) { typedef std::vector<std::pair<int, double> > VecPair ; //turn priority queue into a vector of pairs VecPair vec = a_queue.saveOrderedQueueAsVector(); //sum for partition function double sum = 0.0; // calculate partition function by iterating over action-values for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { sum += std::exp((iter->second) / probabilityFluxDensityCoeffieicent(iterations)); } // compute Boltzmann factors for action-values and enqueue to vec for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) { iter->second = std::exp(iter->second / probabilityFluxDensityCoeffieicent(iterations)) / sum; } // calculate cumulative probability distribution for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) { //second member of pair becomes addition of its current value //and that of the index before it iter->second += (iter-1)->second; } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached } void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) { //oldQ value reference double oldQ = space[old_state].search(action).second; //reward given to current state double R = new_state.getReward(); //optimal Q value for new state i.e. first element double maxQ = space[new_state].peekFront().second; //new Q value determined by Q learning algorithm double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ); // change priority of action to new Q value space[old_state].changePriority(action, newQ); } /* OLD SELECT ACTION int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) { /* // queue to store action values PriorityQueue<int, double> actionQueue(MAX); double sum = 0.0; // calculate partition function by iterating over action-values for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) { sum += std::exp((iter->second) / temperature(iterations)); } // compute Boltzmann factors for action-values and enqueue to actionQueue for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) { double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum; actionQueue.enqueueWithPriority(iter.operator*().first, priority); } // calculate cumulative probability distribution for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) { // change priority of it1->first data item in actionQueue to // sum of priorities of it1 and it2 items actionQueue.changePriority(it1->first, it1->second + it2->second); } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached double rand_num = static_cast<double>(rand()) / RAND_MAX; return (rand_num > 0.5)?0:1; } */ <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Samsung Electronics Co., 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. * */ // CLASS HEADER #include "geometry-api.h" // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> // INTERNAL INCLUDES #include <v8-utils.h> #include <rendering/geometry-wrapper.h> #include <object/property-buffer-api.h> namespace Dali { namespace V8Plugin { /** * ## Geometry API * * Geometry is handle to an object that can be used to define a geometric elements. * * @class Geometry * @extends Handle */ Geometry GeometryApi::GetGeometry( v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::HandleScope handleScope( isolate ); v8::Local<v8::Object> object = args.This(); v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) ); void* ptr = field->Value(); GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(ptr); return wrapper->GetGeometry(); } Geometry GeometryApi::GetGeometryFromParams( int paramIndex, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args ) { found = false; v8::HandleScope handleScope( isolate ); BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( paramIndex, BaseWrappedObject::GEOMETRY, isolate, args ); if( wrappedObject ) { found = true; GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(wrappedObject); return wrapper->GetGeometry(); } else { return Geometry(); } } /** * Create a new geometry object. * * @constructor * @method Geometry * @for Geometry * @return {Object} Geometry */ Geometry GeometryApi::New( const v8::FunctionCallbackInfo< v8::Value >& args ) { return Geometry::New(); } /** * Add a PropertyBuffer to be used as source of geometry vertices * * @method addVertexBuffer * @for Geometry * @param {Object} vertexBuffer PropertyBuffer to be used as source of geometry vertices * @return {interger} Index of the newly added buffer, can be used with RemoveVertexBuffer * to remove this buffer if no longer required * @example *``` * var vertexFormat ={ "aPosition" : dali.PROPERTY_VECTOR2 }; * var vertexData = [ 0, 1, * -0.95, 0.31, * -0.59, -0.81, * 0.59, -0.81, * 0.95, 0.31]; * * var vertexDataArray = new Float32Array(vertexData.length); * vertexDataArray.set(vertexData, 0); * var vertices = new dali.PropertyBuffer(vertexFormat, 5); * vertices.setData(vertexDataArray); * * var geometry = new dali.Geometry(); * geometry.addVertexBuffer( vertices ); *``` */ void GeometryApi::AddVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); PropertyBuffer vertexBuffer = PropertyBufferApi::GetPropertyBufferFromParams( 0, found, isolate, args ); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "invalid property buffer parameter" ); } else { args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.AddVertexBuffer(vertexBuffer) ) ); } } /** * Retrieve the number of vertex buffers that have been added to this geometry * * @method getNumberOfVertexBuffers * @for Geometry * @return {integer} Number of vertex buffers that have been added to this geometry */ void GeometryApi::GetNumberOfVertexBuffers( const v8::FunctionCallbackInfo<v8::Value>& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetNumberOfVertexBuffers() ) ); } /** * Remove a vertex buffer * * @method removeVertexBuffer * @for Geometry * @param {integer} index Index to the vertex buffer to remove, * which must be between 0 and getNumberOfVertexBuffers() */ void GeometryApi::RemoveVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); int index = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing index from param 0" ); } else { geometry.RemoveVertexBuffer(static_cast<std::size_t>(index)); } } /** * Set a PropertyBuffer to be used as a source of indices for the geometry * * This buffer is required to have exactly one component and it must be of the * type dali.PROPERTY_INTEGER * * By setting this buffer it will cause the geometry to be rendered using indices. * To unset call SetIndexBuffer with an empty handle. * * @method setIndexBuffer * @for Geometry * @param {Uint32Array} data The data that will be copied to the buffer * * @example * var indexData = [0, 1, 1, 2, 2, 3, 3, 4, 4, 0]; * var indexDataArray = new Uint32Array(indexData.length); * indexDataArray.set(indexData, 0); * * geometry.SetIndexBuffer( indexDataArray, indexDataArray.length ); *``` */ void GeometryApi::SetIndexBuffer( const v8::FunctionCallbackInfo<v8::Value>& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); void* data = V8Utils::GetArrayBufferViewParameter( PARAMETER_0, found, isolate, args); if( ! found ) { DALI_SCRIPT_EXCEPTION( isolate, "invalid data parameter" ); } else { int size = V8Utils::GetIntegerParameter( PARAMETER_1, found, isolate, args, 0); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing buffer size from param 1" ); } else { geometry.SetIndexBuffer( static_cast<const unsigned short*>(data), size ); } } } /** * Set the type of primitives this geometry contains * * @method setGeometryType * @for Geometry * @param {integer} geometryType Type of primitives this geometry contains * @example * // geometry type is one of the following * dali.GEOMETRY_POINTS * dali.GEOMETRY_LINES * dali.GEOMETRY_LINE_LOOP * dali.GEOMETRY_LINE_STRIP * dali.GEOMETRY_TRIANGLES * dali.GEOMETRY_TRIANGLE_FAN * dali.GEOMETRY_TRIANGLE_STRIP * * geometry.SetGeometryType( dali.GEOMETRY_LINES ); */ void GeometryApi::SetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); int geometryType = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing geometryType from param 0" ); } else { geometry.SetGeometryType(static_cast<Geometry::GeometryType>(geometryType)); } } /** * Get the type of primitives this geometry contains * * @method getGeometryType * @for Geometry * @return {integer} Type of primitives this geometry contains * @example * // returns one of the following * dali.GEOMETRY_POINTS * dali.GEOMETRY_LINES * dali.GEOMETRY_LINE_LOOP * dali.GEOMETRY_LINE_STRIP * dali.GEOMETRY_TRIANGLES * dali.GEOMETRY_TRIANGLE_FAN * dali.GEOMETRY_TRIANGLE_STRIP */ void GeometryApi::GetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetGeometryType() ) ); } } // namespace V8Plugin } // namespace Dali <commit_msg>Fixed bug in SetIndexBuffer for v8 plugin<commit_after>/* * Copyright (c) 2015 Samsung Electronics Co., 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. * */ // CLASS HEADER #include "geometry-api.h" // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> // INTERNAL INCLUDES #include <v8-utils.h> #include <rendering/geometry-wrapper.h> #include <object/property-buffer-api.h> namespace Dali { namespace V8Plugin { /** * ## Geometry API * * Geometry is handle to an object that can be used to define a geometric elements. * * @class Geometry * @extends Handle */ Geometry GeometryApi::GetGeometry( v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::HandleScope handleScope( isolate ); v8::Local<v8::Object> object = args.This(); v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) ); void* ptr = field->Value(); GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(ptr); return wrapper->GetGeometry(); } Geometry GeometryApi::GetGeometryFromParams( int paramIndex, bool& found, v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args ) { found = false; v8::HandleScope handleScope( isolate ); BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( paramIndex, BaseWrappedObject::GEOMETRY, isolate, args ); if( wrappedObject ) { found = true; GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(wrappedObject); return wrapper->GetGeometry(); } else { return Geometry(); } } /** * Create a new geometry object. * * @constructor * @method Geometry * @for Geometry * @return {Object} Geometry */ Geometry GeometryApi::New( const v8::FunctionCallbackInfo< v8::Value >& args ) { return Geometry::New(); } /** * Add a PropertyBuffer to be used as source of geometry vertices * * @method addVertexBuffer * @for Geometry * @param {Object} vertexBuffer PropertyBuffer to be used as source of geometry vertices * @return {interger} Index of the newly added buffer, can be used with RemoveVertexBuffer * to remove this buffer if no longer required * @example *``` * var vertexFormat ={ "aPosition" : dali.PROPERTY_VECTOR2 }; * var vertexData = [ 0, 1, * -0.95, 0.31, * -0.59, -0.81, * 0.59, -0.81, * 0.95, 0.31]; * * var vertexDataArray = new Float32Array(vertexData.length); * vertexDataArray.set(vertexData, 0); * var vertices = new dali.PropertyBuffer(vertexFormat, 5); * vertices.setData(vertexDataArray); * * var geometry = new dali.Geometry(); * geometry.addVertexBuffer( vertices ); *``` */ void GeometryApi::AddVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); PropertyBuffer vertexBuffer = PropertyBufferApi::GetPropertyBufferFromParams( 0, found, isolate, args ); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "invalid property buffer parameter" ); } else { args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.AddVertexBuffer(vertexBuffer) ) ); } } /** * Retrieve the number of vertex buffers that have been added to this geometry * * @method getNumberOfVertexBuffers * @for Geometry * @return {integer} Number of vertex buffers that have been added to this geometry */ void GeometryApi::GetNumberOfVertexBuffers( const v8::FunctionCallbackInfo<v8::Value>& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetNumberOfVertexBuffers() ) ); } /** * Remove a vertex buffer * * @method removeVertexBuffer * @for Geometry * @param {integer} index Index to the vertex buffer to remove, * which must be between 0 and getNumberOfVertexBuffers() */ void GeometryApi::RemoveVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); int index = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing index from param 0" ); } else { geometry.RemoveVertexBuffer(static_cast<std::size_t>(index)); } } /** * Set a PropertyBuffer to be used as a source of indices for the geometry * * This buffer is required to have exactly one component and it must be of the * type dali.PROPERTY_INTEGER * * By setting this buffer it will cause the geometry to be rendered using indices. * To unset call SetIndexBuffer with an empty handle. * * @method setIndexBuffer * @for Geometry * @param {Uint32Array} data The data that will be copied to the buffer * * @example * var indexData = [0, 1, 1, 2, 2, 3, 3, 4, 4, 0]; * var indexDataArray = new Uint32Array(indexData.length); * indexDataArray.set(indexData, 0); * * geometry.SetIndexBuffer( indexDataArray, indexDataArray.length ); *``` */ void GeometryApi::SetIndexBuffer( const v8::FunctionCallbackInfo<v8::Value>& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); void* data = V8Utils::GetArrayBufferViewParameter( PARAMETER_0, found, isolate, args); if( ! found ) { DALI_SCRIPT_EXCEPTION( isolate, "invalid data parameter" ); } else { unsigned int size = V8Utils::GetIntegerParameter( PARAMETER_1, found, isolate, args, 0); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing buffer size from param 1" ); } else { Dali::Vector<unsigned short> indices; indices.Resize( size ); unsigned int* indexData = static_cast<unsigned int*>(data); for( size_t i(0); i<size; ++i ) { indices[i] = indexData[i]; } geometry.SetIndexBuffer( &indices[0], size ); } } } /** * Set the type of primitives this geometry contains * * @method setGeometryType * @for Geometry * @param {integer} geometryType Type of primitives this geometry contains * @example * // geometry type is one of the following * dali.GEOMETRY_POINTS * dali.GEOMETRY_LINES * dali.GEOMETRY_LINE_LOOP * dali.GEOMETRY_LINE_STRIP * dali.GEOMETRY_TRIANGLES * dali.GEOMETRY_TRIANGLE_FAN * dali.GEOMETRY_TRIANGLE_STRIP * * geometry.SetGeometryType( dali.GEOMETRY_LINES ); */ void GeometryApi::SetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); bool found( false ); int geometryType = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */); if( !found ) { DALI_SCRIPT_EXCEPTION( isolate, "missing geometryType from param 0" ); } else { geometry.SetGeometryType(static_cast<Geometry::GeometryType>(geometryType)); } } /** * Get the type of primitives this geometry contains * * @method getGeometryType * @for Geometry * @return {integer} Type of primitives this geometry contains * @example * // returns one of the following * dali.GEOMETRY_POINTS * dali.GEOMETRY_LINES * dali.GEOMETRY_LINE_LOOP * dali.GEOMETRY_LINE_STRIP * dali.GEOMETRY_TRIANGLES * dali.GEOMETRY_TRIANGLE_FAN * dali.GEOMETRY_TRIANGLE_STRIP */ void GeometryApi::GetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args ) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope( isolate ); Geometry geometry = GetGeometry( isolate, args ); args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetGeometryType() ) ); } } // namespace V8Plugin } // namespace Dali <|endoftext|>
<commit_before>#include <BALL/VIEW/RENDERING/RENDERERS/rtfactRenderer.h> #include <RTfact/Config/Init.inc.cpp> //#include <RTfact/Utils/Packets/Detail/Constants.inc.cpp> #include <BALL/STRUCTURE/triangulatedSurface.h> #include <BALL/VIEW/PRIMITIVES/sphere.h> #include <BALL/VIEW/PRIMITIVES/twoColoredTube.h> using namespace RTfact::Remote; namespace BALL { namespace VIEW { bool RTfactRenderer::init(const Scene& scene) throw() { scene_ = &scene; using RTfact::Triangle; using RTfact::Vec3f; using RTfact::Remote::GroupHandle; using RTfact::Remote::GeoHandle; using RTfact::Transform; using RTfact::Remote::float3; GroupHandle root = m_renderer.getRoot(); TriangleVector faces; Triangle t(Vec3f<1>(0,0,0),Vec3f<1>(1,0,0),Vec3f<1>(1,1,0)); t.texCoords[0] = std::make_pair(0.f,0.f); t.texCoords[1] = std::make_pair(0.f,512.f); t.texCoords[2] = std::make_pair(512.f,0.f); faces.push_back(t); for(TriangleVector::iterator it = faces.begin(); it != faces.end(); it++) { it->normals[0]=it->normal; it->normals[1]=it->normal; it->normals[2]=it->normal; } GeoHandle geo1 = m_renderer.createGeometry(faces); GroupHandle topGroup = m_renderer.createGroup(Transform::identity()); topGroup->add(geo1); root->add(topGroup); RTfact::Remote::RTAppearanceHandle mat1 = m_renderer.createAppearance("PhongShader"); mat1->setParam("diffuseColor", float3(1.0, 1.0, 0)); mat1->setParam("ambientIntensity", float3(.7, .7, .7)); geo1->setAppearance(mat1); m_renderer.setCameraPosition( float3(-1.48978, 4.14466, 11.4965), float3(0.864694, -0.481748, 0.142207), float3(0, 1, 0)); //root->setTransform(Transform::rotationY(0.2f)); //root->add(geo2); m_renderer.createAccelStruct(); // prepare the sphere template TriangulatedSphere sphere_template; sphere_template.icosaeder(); sphere_template.refine(3, true); sphere_template.exportSurface(sphere_template_); // prepare the tube template TriangulatedSurface* tube_template = TriangulatedSurface::createTube(18, 0, false, true); tube_template->exportSurface(tube_template_); delete (tube_template); return true; } void RTfactRenderer::prepareBufferedRendering(const Stage& stage) { Camera const& camera = stage.getCamera(); Vector3 const& position = camera.getViewPoint(); Vector3 const& view_vector = camera.getViewVector(); Vector3 const& look_up = camera.getLookUpVector(); m_renderer.setCameraPosition(float3(position.x, position.y, position.z), float3(view_vector.x, view_vector.y, view_vector.z), float3(look_up.x, look_up.y, look_up.z)); Size num_lights = lights_.size(); Vector3 direction, light_position; Size current_light=0; List<LightSource>::ConstIterator it = stage.getLightSources().begin(); for (; it != stage.getLightSources().end(); ++it, ++current_light) { if (current_light >= num_lights) { RTfact::Remote::RTLightHandle light; switch (it->getType()) { case LightSource::DIRECTIONAL: light = m_renderer.createLight("DirectionalLight"); break; case LightSource::POSITIONAL: light = m_renderer.createLight("PointLight"); break; default: std::cerr << "Light source type not supported!" << std::endl; break; } lights_.push_back(light); } switch (it->getType()) { case LightSource::DIRECTIONAL: direction = it->getDirection(); if (it->isRelativeToCamera()) direction = stage.calculateAbsoluteCoordinates(direction); lights_[current_light]->setParam("direction", float3(direction.x, direction.y, direction.z)); break; case LightSource::POSITIONAL: light_position = it->getPosition(); if (it->isRelativeToCamera()) { light_position = stage.calculateAbsoluteCoordinates(it->getPosition())+stage.getCamera().getViewPoint(); } lights_[current_light]->setParam("position", float3(light_position.x, light_position.y, light_position.z)); break; default: std::cerr << "Light source type not supported!" << std::endl; break; } float intensity = it->getIntensity()*500; ColorRGBA const& color = it->getColor(); lights_[current_light]->setParam("intensity", float3((float)color.getRed()*intensity,(float)color.getGreen()*intensity,(float)color.getBlue()*intensity)); } } void RTfactRenderer::renderToBufferImpl(FrameBufferPtr buffer) { bool recreate_accel = false; RepresentationManager& pm = scene_->getMainControl()->getRepresentationManager(); RepresentationList::ConstIterator it = pm.getRepresentations().begin(); for (; it != pm.getRepresentations().end(); ++it) { Representation const* rep = *it; if (rep->isHidden()) continue; List<GeometricObject*>::ConstIterator it; for (it = rep->getGeometricObjects().begin(); it != rep->getGeometricObjects().end(); it++) { if (objects_.find(*it) == objects_.end()) { recreate_accel = true; objects_.insert(*it); if (RTTI::isKindOf<Mesh>(**it)) { Mesh const& mesh = *(const Mesh*)*it; float const* vertices = reinterpret_cast<float const*>(&(mesh.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(mesh.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(mesh.triangle[0])); RTAppearanceHandle material = m_renderer.createAppearance("PhongShader"); material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material->setParam("shininess", (float)76.8); GeoHandle handle; float const* colors = 0; if (mesh.colors.size() > 1) { colors = reinterpret_cast<float const*>(&(mesh.colors[0])); material->setParam("useVertexColor", true); handle = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material); } else { ColorRGBA const &c = (mesh.colors.size() == 1) ? mesh.colors[0] : ColorRGBA(1., 1., 1., 1.); material->setParam("diffuseColor", float3(c.getRed(), c.getGreen(), c.getBlue())); material->setParam("useVertexColor", false); handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material); } GroupHandle meshGroup = m_renderer.createGroup(Transform::identity()); meshGroup->add(handle); m_renderer.getRoot()->add(meshGroup); } if (RTTI::isKindOf<Sphere>(**it)) { Sphere const& sphere = *(const Sphere*)*it; float const* vertices = reinterpret_cast<float const*>(&(sphere_template_.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(sphere_template_.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(sphere_template_.triangle[0])); // TEST ColorRGBA const& color = sphere.getColor(); RTAppearanceHandle material = m_renderer.createAppearance("PhongShader"); material->setParam("diffuseColor", float3(color.getRed(), color.getGreen(), color.getBlue())); material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material->setParam("shininess", (float)76.8); material->setParam("useVertexColor", false); GeoHandle handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)sphere_template_.triangle.size(), material); Vector3 const& sphere_pos = sphere.getPosition(); float radius = sphere.getRadius(); GroupHandle sphereGroup = m_renderer.createGroup( Transform::translation(sphere_pos.x, sphere_pos.y, sphere_pos.z) *Transform::scale(Vec3f<1>(radius, radius, radius))); sphereGroup->add(handle); m_renderer.getRoot()->add(sphereGroup); } if (RTTI::isKindOf<TwoColoredTube>(**it)) { TwoColoredTube const& tube = *(const TwoColoredTube*)*it; float const* vertices = reinterpret_cast<float const*>(&(tube_template_.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(tube_template_.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(tube_template_.triangle[0])); // TEST std::vector<ColorRGBA> new_colors(tube_template_.vertex.size()); Size num_triangles = tube_template_.triangle.size(); for (Position i=0; i<num_triangles/2; ++i) { Surface::Triangle const& t = tube_template_.triangle[i]; new_colors[t.v1] = tube.getColor(); new_colors[t.v2] = tube.getColor(); new_colors[t.v3] = tube.getColor(); } for (Position i=num_triangles/2; i<num_triangles; ++i) { Surface::Triangle const& t = tube_template_.triangle[i]; new_colors[t.v1] = tube.getColor2(); new_colors[t.v2] = tube.getColor2(); new_colors[t.v3] = tube.getColor2(); } float const* colors = reinterpret_cast<float const*>(&(new_colors[0])); RTAppearanceHandle material = m_renderer.createAppearance("PhongShader"); material->setParam("diffuseColor", float3(0.4, 0.4, 0.4)); material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material->setParam("shininess", (float)76.8); material->setParam("useVertexColor", true); GeoHandle handle = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material); GroupHandle tubeGroup = transformTube(tube); tubeGroup->add(handle); m_renderer.getRoot()->add(tubeGroup); } } } } if (recreate_accel) m_renderer.createAccelStruct(); FrameBufferFormat fmt = buffer->getFormat(); if (fmt.getPixelFormat() == PixelFormat::RGBF_96) { m_renderer.attachFrameBuffer(fmt.getWidth(), fmt.getHeight(), fmt.getPitch(), (float*)buffer->getData()); m_renderer.renderToBuffer(); } } GroupHandle RTfactRenderer::transformTube(const TwoColoredTube& tube) { Vector3 vec = tube.getVertex2() - tube.getVertex1(); const double len = vec.getLength(); const double angle = acos(vec.z / len); // the denominator accounts for the non-normalized rotation axis const float radius = tube.getRadius(); Matrix4x4 trafo = Matrix4x4::getIdentity(); //Rotate the vector around the normal vec /= sqrt(vec.x*vec.x + vec.y*vec.y); trafo.rotate(Angle(-angle), vec.y, -vec.x, 0); Matrix4f matrix(trafo.m11, trafo.m12, trafo.m13, trafo.m14, trafo.m21, trafo.m22, trafo.m23, trafo.m24, trafo.m31, trafo.m32, trafo.m33, trafo.m34, trafo.m41, trafo.m42, trafo.m43, trafo.m44); Vector3 const& midpoint = tube.getVertex1(); return m_renderer.createGroup( Transform::translation(midpoint.x, midpoint.y, midpoint.z) *matrix*Transform::scale(Vec3f<1>(radius, radius, len))); } } } <commit_msg>Raytraced tubes and spheres look now a bit nicer.<commit_after>#include <BALL/VIEW/RENDERING/RENDERERS/rtfactRenderer.h> #include <RTfact/Config/Init.inc.cpp> //#include <RTfact/Utils/Packets/Detail/Constants.inc.cpp> #include <BALL/STRUCTURE/triangulatedSurface.h> #include <BALL/VIEW/PRIMITIVES/sphere.h> #include <BALL/VIEW/PRIMITIVES/twoColoredTube.h> using namespace RTfact::Remote; namespace BALL { namespace VIEW { bool RTfactRenderer::init(const Scene& scene) throw() { scene_ = &scene; using RTfact::Triangle; using RTfact::Vec3f; using RTfact::Remote::GroupHandle; using RTfact::Remote::GeoHandle; using RTfact::Transform; using RTfact::Remote::float3; GroupHandle root = m_renderer.getRoot(); TriangleVector faces; Triangle t(Vec3f<1>(0,0,0),Vec3f<1>(1,0,0),Vec3f<1>(1,1,0)); t.texCoords[0] = std::make_pair(0.f,0.f); t.texCoords[1] = std::make_pair(0.f,512.f); t.texCoords[2] = std::make_pair(512.f,0.f); faces.push_back(t); for(TriangleVector::iterator it = faces.begin(); it != faces.end(); it++) { it->normals[0]=it->normal; it->normals[1]=it->normal; it->normals[2]=it->normal; } GeoHandle geo1 = m_renderer.createGeometry(faces); GroupHandle topGroup = m_renderer.createGroup(Transform::identity()); topGroup->add(geo1); root->add(topGroup); RTfact::Remote::RTAppearanceHandle mat1 = m_renderer.createAppearance("PhongShader"); mat1->setParam("diffuseColor", float3(1.0, 1.0, 0)); mat1->setParam("ambientIntensity", float3(.7, .7, .7)); geo1->setAppearance(mat1); m_renderer.setCameraPosition( float3(-1.48978, 4.14466, 11.4965), float3(0.864694, -0.481748, 0.142207), float3(0, 1, 0)); //root->setTransform(Transform::rotationY(0.2f)); //root->add(geo2); m_renderer.createAccelStruct(); // prepare the sphere template TriangulatedSphere sphere_template; sphere_template.icosaeder(); sphere_template.refine(3, true); sphere_template.exportSurface(sphere_template_); // prepare the tube template TriangulatedSurface* tube_template = TriangulatedSurface::createTube(18, 0, false, true); tube_template->exportSurface(tube_template_); delete (tube_template); return true; } void RTfactRenderer::prepareBufferedRendering(const Stage& stage) { Camera const& camera = stage.getCamera(); Vector3 const& position = camera.getViewPoint(); Vector3 const& view_vector = camera.getViewVector(); Vector3 const& look_up = camera.getLookUpVector(); m_renderer.setCameraPosition(float3(position.x, position.y, position.z), float3(view_vector.x, view_vector.y, view_vector.z), float3(look_up.x, look_up.y, look_up.z)); Size num_lights = lights_.size(); Vector3 direction, light_position; Size current_light=0; List<LightSource>::ConstIterator it = stage.getLightSources().begin(); for (; it != stage.getLightSources().end(); ++it, ++current_light) { if (current_light >= num_lights) { RTfact::Remote::RTLightHandle light; switch (it->getType()) { case LightSource::DIRECTIONAL: light = m_renderer.createLight("DirectionalLight"); break; case LightSource::POSITIONAL: light = m_renderer.createLight("PointLight"); break; default: std::cerr << "Light source type not supported!" << std::endl; break; } lights_.push_back(light); } switch (it->getType()) { case LightSource::DIRECTIONAL: direction = it->getDirection(); if (it->isRelativeToCamera()) direction = stage.calculateAbsoluteCoordinates(direction); lights_[current_light]->setParam("direction", float3(direction.x, direction.y, direction.z)); break; case LightSource::POSITIONAL: light_position = it->getPosition(); if (it->isRelativeToCamera()) { light_position = stage.calculateAbsoluteCoordinates(it->getPosition())+stage.getCamera().getViewPoint(); } lights_[current_light]->setParam("position", float3(light_position.x, light_position.y, light_position.z)); break; default: std::cerr << "Light source type not supported!" << std::endl; break; } float intensity = it->getIntensity()*500; ColorRGBA const& color = it->getColor(); lights_[current_light]->setParam("intensity", float3((float)color.getRed()*intensity,(float)color.getGreen()*intensity,(float)color.getBlue()*intensity)); } } void RTfactRenderer::renderToBufferImpl(FrameBufferPtr buffer) { bool recreate_accel = false; RepresentationManager& pm = scene_->getMainControl()->getRepresentationManager(); RepresentationList::ConstIterator it = pm.getRepresentations().begin(); for (; it != pm.getRepresentations().end(); ++it) { Representation const* rep = *it; if (rep->isHidden()) continue; List<GeometricObject*>::ConstIterator it; for (it = rep->getGeometricObjects().begin(); it != rep->getGeometricObjects().end(); it++) { if (objects_.find(*it) == objects_.end()) { recreate_accel = true; objects_.insert(*it); if (RTTI::isKindOf<Mesh>(**it)) { Mesh const& mesh = *(const Mesh*)*it; float const* vertices = reinterpret_cast<float const*>(&(mesh.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(mesh.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(mesh.triangle[0])); RTAppearanceHandle material = m_renderer.createAppearance("PhongShader"); material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material->setParam("reflective", float3(0.0, 0.0, 0.0)); material->setParam("shininess", (float)76.8); GeoHandle handle; float const* colors = 0; if (mesh.colors.size() > 1) { colors = reinterpret_cast<float const*>(&(mesh.colors[0])); material->setParam("useVertexColor", true); handle = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material); } else { ColorRGBA const &c = (mesh.colors.size() == 1) ? mesh.colors[0] : ColorRGBA(1., 1., 1., 1.); material->setParam("diffuseColor", float3(c.getRed(), c.getGreen(), c.getBlue())); material->setParam("useVertexColor", false); handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material); } GroupHandle meshGroup = m_renderer.createGroup(Transform::identity()); meshGroup->add(handle); m_renderer.getRoot()->add(meshGroup); } if (RTTI::isKindOf<Sphere>(**it)) { Sphere const& sphere = *(const Sphere*)*it; float const* vertices = reinterpret_cast<float const*>(&(sphere_template_.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(sphere_template_.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(sphere_template_.triangle[0])); ColorRGBA const& color = sphere.getColor(); RTAppearanceHandle material = m_renderer.createAppearance("PhongShader"); material->setParam("diffuseColor", float3(color.getRed(), color.getGreen(), color.getBlue())); material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material->setParam("shininess", (float)76.8); material->setParam("useVertexColor", false); GeoHandle handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)sphere_template_.triangle.size(), material); Vector3 const& sphere_pos = sphere.getPosition(); float radius = sphere.getRadius(); GroupHandle sphereGroup = m_renderer.createGroup( Transform::translation(sphere_pos.x, sphere_pos.y, sphere_pos.z) *Transform::scale(Vec3f<1>(radius, radius, radius))); sphereGroup->add(handle); m_renderer.getRoot()->add(sphereGroup); } if (RTTI::isKindOf<TwoColoredTube>(**it)) { TwoColoredTube const& old_tube = *(const TwoColoredTube*)*it; float const* vertices = reinterpret_cast<float const*>(&(tube_template_.vertex[0])); float const* normals = reinterpret_cast<float const*>(&(tube_template_.normal[0])); Index const* indices = reinterpret_cast<Index const*>(&(tube_template_.triangle[0])); // we will produce two tubes using the same vertex/normal/color values, just with the correct offsets ColorRGBA const& color1 = old_tube.getColor(); ColorRGBA const& color2 = old_tube.getColor2(); RTAppearanceHandle material_1 = m_renderer.createAppearance("PhongShader"); material_1->setParam("diffuseColor", float3(color1.getRed(), color1.getGreen(), color1.getBlue())); material_1->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material_1->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material_1->setParam("shininess", (float)76.8); material_1->setParam("useVertexColor", false); GeoHandle handle_1 = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material_1); if (color1 == color2) { GroupHandle tubeGroup = transformTube(old_tube); tubeGroup->add(handle_1); m_renderer.getRoot()->add(tubeGroup); } else { RTAppearanceHandle material_2 = m_renderer.createAppearance("PhongShader"); material_2->setParam("diffuseColor", float3(color2.getRed(), color2.getGreen(), color2.getBlue())); material_2->setParam("ambientIntensity", float3(0.25, 0.25, 0.25)); material_2->setParam("specularColor", float3(0.774597, 0.774597, 0.774597)); material_2->setParam("shininess", (float)76.8); material_2->setParam("useVertexColor", false); GeoHandle handle_2 = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material_2); TwoColoredTube new_tube = old_tube; new_tube.setVertex2(old_tube.getMiddleVertex()); GroupHandle tubeGroup_1 = transformTube(new_tube); tubeGroup_1->add(handle_1); new_tube.setVertex1(old_tube.getVertex2()); new_tube.setVertex2(old_tube.getMiddleVertex()); GroupHandle tubeGroup_2 = transformTube(new_tube); tubeGroup_2->add(handle_2); m_renderer.getRoot()->add(tubeGroup_1); m_renderer.getRoot()->add(tubeGroup_2); } } } } } if (recreate_accel) m_renderer.createAccelStruct(); FrameBufferFormat fmt = buffer->getFormat(); if (fmt.getPixelFormat() == PixelFormat::RGBF_96) { m_renderer.attachFrameBuffer(fmt.getWidth(), fmt.getHeight(), fmt.getPitch(), (float*)buffer->getData()); m_renderer.renderToBuffer(); } } GroupHandle RTfactRenderer::transformTube(const TwoColoredTube& tube) { Vector3 vec = tube.getVertex2() - tube.getVertex1(); const double len = vec.getLength(); const double angle = acos(vec.z / len); // the denominator accounts for the non-normalized rotation axis const float radius = tube.getRadius(); Matrix4x4 trafo = Matrix4x4::getIdentity(); //Rotate the vector around the normal vec /= sqrt(vec.x*vec.x + vec.y*vec.y); trafo.rotate(Angle(-angle), vec.y, -vec.x, 0); Matrix4f matrix(trafo.m11, trafo.m12, trafo.m13, trafo.m14, trafo.m21, trafo.m22, trafo.m23, trafo.m24, trafo.m31, trafo.m32, trafo.m33, trafo.m34, trafo.m41, trafo.m42, trafo.m43, trafo.m44); Vector3 const& midpoint = tube.getVertex1(); return m_renderer.createGroup( Transform::translation(midpoint.x, midpoint.y, midpoint.z) *matrix*Transform::scale(Vec3f<1>(radius, radius, len))); } } } <|endoftext|>
<commit_before>#include "rForcom.h" #include "de/hackcraft/psi3d/GLF.h" #include "de/hackcraft/psi3d/GLS.h" #include "de/hackcraft/world/Message.h" std::string rForcom::cname = "FORCOM"; unsigned int rForcom::cid = 1032; rForcom::rForcom(Entity* obj) { object = obj; quat_zero(ori); vector_zero(twr); } void rForcom::message(Message* message) { mMessage = message->getText(); } void rForcom::animate(float spf) { } void rForcom::drawHUD() { if (!active) return; // Reticle in screen center. if (reticle) { glPushMatrix(); { glTranslatef(0.5, 0.5, 0); glScalef(0.03, 0.04, 1); glPointSize(2); glBegin(GL_POINTS); { glColor4f(1, 0, 0, 0.2); glVertex3f(0, 0, 0); } glEnd(); glBegin(GL_LINES); { const float a = 0.7; // left glVertex3f(-1, 0, 0); glVertex3f(-a, 0, 0); // low glVertex3f(0, -1, 0); glVertex3f(0, -a, 0); // right glVertex3f(+1, 0, 0); glVertex3f(+a, 0, 0); // diagonal glVertex3f(-a, 0, 0); glVertex3f(0, -a, 0); glVertex3f(0, -a, 0); glVertex3f(+a, 0, 0); } glEnd(); } glPopMatrix(); } // Compass-Lines at top of HUD if (!true) { glPushMatrix(); { glTranslatef(0.5, 0.97, 0); glScalef(1.0, 0.02, 1.0); glColor4f(0, 1, 0, 0.2); float r = atan2(ori[1], ori[3]) / PI_OVER_180; if (r > 180) r -= 360; const float d = 1.0f / 360.0f; glLineWidth(3); glBegin(GL_LINES); { glColor4f(0, 0.3, 1, 0.2); float s = 1.2; for (int i = -180; i < 180; i += 10) { float t = fmod(r, 10); glVertex3f((i + t) * d, -s, 0); glVertex3f((i + t) * d, +s, 0); } } glEnd(); glLineWidth(1); glBegin(GL_LINES); { glColor4f(1, 1, 1, 0.6); float s = 1.0; for (int i = -180; i < 180; i += 10) { float t = fmod(r, 10); glVertex3f((i + t) * d, -s, 0); glVertex3f((i + t) * d, +s, 0); } } glEnd(); } glPopMatrix(); } // Compass // Ornamental HUD-Border-Frame if (true) { glLineWidth(5); glColor4f(1, 1, 0, 0.2); glBegin(GL_LINE_STRIP); { glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); } glEnd(); glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); glLineWidth(1); glLineStipple(1, 0xFF55); glColor4f(1, 1, 1, 0.6); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINE_STRIP); { glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); } glEnd(); glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); /* glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.1, 0); glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); */ glDisable(GL_LINE_STIPPLE); } // Border float f = 1.0f / (250 * 0.017453f); // Tower angle indicator if (true) { glLineWidth(3); // Tower left/right indication bar. glBegin(GL_LINES); { glColor4f(0, 0.2, 0.7, 0.4); glVertex3f(0.5, 0.1, 0); glVertex3f(0.5 + twr[1] * f, 0.1, 0); glVertex3f(0.5 + twr[1] * f, 0.08, 0); glVertex3f(0.5 + twr[1] * f, 0.12, 0); glVertex3f(0.5, 0.9, 0); glVertex3f(0.5 + twr[1] * f, 0.9, 0); glVertex3f(0.5 + twr[1] * f, 0.88, 0); glVertex3f(0.5 + twr[1] * f, 0.92, 0); } glEnd(); // Tower up/down indication bar. glBegin(GL_LINES); { glColor4f(0, 0.2, 0.7, 0.4); glVertex3f(0.1, 0.5, 0); glVertex3f(0.1, 0.5 + twr[0] * f, 0); glVertex3f(0.08, 0.5 + twr[0] * f, 0); glVertex3f(0.12, 0.5 + twr[0] * f, 0); glVertex3f(0.9, 0.5, 0); glVertex3f(0.9, 0.5 + twr[0] * f, 0); glVertex3f(0.88, 0.5 + twr[0] * f, 0); glVertex3f(0.92, 0.5 + twr[0] * f, 0); } glEnd(); } // Tower angle indicator // Message display if (true) { glPushMatrix(); { glColor4f(0.99, 0.99, 0.19, 1); glTranslatef(0, 1, 0); glScalef(1.0f / 60.0f, 1.0f / 20.0f, 1.0f); glColor4f(0.09, 0.99, 0.09, 1); glTranslatef(0, -0, 0); GLF::glprint(mMessage.c_str()); //GLF::glprintf("TEST TEST TEST ... TEST TEST TEST\ntest test test"); } glPopMatrix(); } // Message display } <commit_msg>Mobile-System: Cleaning initialization issues (removing empty copy constructor).<commit_after>#include "rForcom.h" #include "de/hackcraft/psi3d/GLF.h" #include "de/hackcraft/psi3d/GLS.h" #include "de/hackcraft/world/Message.h" std::string rForcom::cname = "FORCOM"; unsigned int rForcom::cid = 1032; rForcom::rForcom(Entity* obj) { object = obj; quat_zero(ori); vector_zero(twr); reticle = true; } void rForcom::message(Message* message) { mMessage = message->getText(); } void rForcom::animate(float spf) { } void rForcom::drawHUD() { if (!active) return; // Reticle in screen center. if (reticle) { glPushMatrix(); { glTranslatef(0.5, 0.5, 0); glScalef(0.03, 0.04, 1); glPointSize(2); glBegin(GL_POINTS); { glColor4f(1, 0, 0, 0.2); glVertex3f(0, 0, 0); } glEnd(); glBegin(GL_LINES); { const float a = 0.7; // left glVertex3f(-1, 0, 0); glVertex3f(-a, 0, 0); // low glVertex3f(0, -1, 0); glVertex3f(0, -a, 0); // right glVertex3f(+1, 0, 0); glVertex3f(+a, 0, 0); // diagonal glVertex3f(-a, 0, 0); glVertex3f(0, -a, 0); glVertex3f(0, -a, 0); glVertex3f(+a, 0, 0); } glEnd(); } glPopMatrix(); } // Compass-Lines at top of HUD if (!true) { glPushMatrix(); { glTranslatef(0.5, 0.97, 0); glScalef(1.0, 0.02, 1.0); glColor4f(0, 1, 0, 0.2); float r = atan2(ori[1], ori[3]) / PI_OVER_180; if (r > 180) r -= 360; const float d = 1.0f / 360.0f; glLineWidth(3); glBegin(GL_LINES); { glColor4f(0, 0.3, 1, 0.2); float s = 1.2; for (int i = -180; i < 180; i += 10) { float t = fmod(r, 10); glVertex3f((i + t) * d, -s, 0); glVertex3f((i + t) * d, +s, 0); } } glEnd(); glLineWidth(1); glBegin(GL_LINES); { glColor4f(1, 1, 1, 0.6); float s = 1.0; for (int i = -180; i < 180; i += 10) { float t = fmod(r, 10); glVertex3f((i + t) * d, -s, 0); glVertex3f((i + t) * d, +s, 0); } } glEnd(); } glPopMatrix(); } // Compass // Ornamental HUD-Border-Frame if (true) { glLineWidth(5); glColor4f(1, 1, 0, 0.2); glBegin(GL_LINE_STRIP); { glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); } glEnd(); glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); glLineWidth(1); glLineStipple(1, 0xFF55); glColor4f(1, 1, 1, 0.6); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINE_STRIP); { glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); } glEnd(); glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); /* glBegin(GL_LINE_STRIP); { glVertex3f(0.2, 0.1, 0); glVertex3f(0.8, 0.1, 0); glVertex3f(0.9, 0.2, 0); glVertex3f(0.9, 0.8, 0); glVertex3f(0.8, 0.9, 0); glVertex3f(0.2, 0.9, 0); glVertex3f(0.1, 0.8, 0); glVertex3f(0.1, 0.2, 0); glVertex3f(0.2, 0.1, 0); } glEnd(); */ glDisable(GL_LINE_STIPPLE); } // Border float f = 1.0f / (250 * 0.017453f); // Tower angle indicator if (true) { glLineWidth(3); // Tower left/right indication bar. glBegin(GL_LINES); { glColor4f(0, 0.2, 0.7, 0.4); glVertex3f(0.5, 0.1, 0); glVertex3f(0.5 + twr[1] * f, 0.1, 0); glVertex3f(0.5 + twr[1] * f, 0.08, 0); glVertex3f(0.5 + twr[1] * f, 0.12, 0); glVertex3f(0.5, 0.9, 0); glVertex3f(0.5 + twr[1] * f, 0.9, 0); glVertex3f(0.5 + twr[1] * f, 0.88, 0); glVertex3f(0.5 + twr[1] * f, 0.92, 0); } glEnd(); // Tower up/down indication bar. glBegin(GL_LINES); { glColor4f(0, 0.2, 0.7, 0.4); glVertex3f(0.1, 0.5, 0); glVertex3f(0.1, 0.5 + twr[0] * f, 0); glVertex3f(0.08, 0.5 + twr[0] * f, 0); glVertex3f(0.12, 0.5 + twr[0] * f, 0); glVertex3f(0.9, 0.5, 0); glVertex3f(0.9, 0.5 + twr[0] * f, 0); glVertex3f(0.88, 0.5 + twr[0] * f, 0); glVertex3f(0.92, 0.5 + twr[0] * f, 0); } glEnd(); } // Tower angle indicator // Message display if (true) { glPushMatrix(); { glColor4f(0.99, 0.99, 0.19, 1); glTranslatef(0, 1, 0); glScalef(1.0f / 60.0f, 1.0f / 20.0f, 1.0f); glColor4f(0.09, 0.99, 0.09, 1); glTranslatef(0, -0, 0); GLF::glprint(mMessage.c_str()); //GLF::glprintf("TEST TEST TEST ... TEST TEST TEST\ntest test test"); } glPopMatrix(); } // Message display } <|endoftext|>
<commit_before>// Copyright 2015 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test/scoped_temp_dir.h" #include <fcntl.h> #include <string.h> #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" #include "gtest/gtest.h" #include "test/errors.h" #include "test/file.h" #if defined(OS_POSIX) #include <unistd.h> #elif defined(OS_WIN) #include <direct.h> #include <io.h> #endif // OS_POSIX namespace crashpad { namespace test { namespace { void CreateFile(const base::FilePath& path) { #if defined(OS_POSIX) int fd = HANDLE_EINTR(creat(path.value().c_str(), 0644)); ASSERT_GE(fd, 0) << ErrnoMessage("creat") << " " << path.value(); ASSERT_EQ(IGNORE_EINTR(close(fd)), 0) << ErrnoMessage("close") << " " << path.value(); #elif defined(OS_WIN) int fd = _wcreat(path.value().c_str(), _S_IREAD | _S_IWRITE); ASSERT_GE(fd, 0) << ErrnoMessage("_wcreat") << " " << path.value(); ASSERT_EQ(_close(fd), 0) << ErrnoMessage("_close") << " " << path.value(); #else #error "Not implemented" #endif EXPECT_TRUE(FileExists(path)); } void CreateDirectory(const base::FilePath& path) { #if defined(OS_POSIX) ASSERT_EQ(mkdir(path.value().c_str(), 0755), 0) << ErrnoMessage("mkdir") << " " << path.value(); #elif defined(OS_WIN) ASSERT_EQ(_wmkdir(path.value().c_str()), 0) << ErrnoMessage("_wmkdir") << " " << path.value(); #else #error "Not implemented" #endif ASSERT_TRUE(FileExists(path)); } TEST(ScopedTempDir, Empty) { base::FilePath path; { ScopedTempDir dir; path = dir.path(); EXPECT_TRUE(FileExists(path)); } EXPECT_FALSE(FileExists(path)); } TEST(ScopedTempDir, WithTwoFiles) { base::FilePath parent, file1, file2; { ScopedTempDir dir; parent = dir.path(); ASSERT_TRUE(FileExists(parent)); file1 = parent.Append(FILE_PATH_LITERAL("test1")); CreateFile(file1); file2 = parent.Append(FILE_PATH_LITERAL("test 2")); CreateFile(file2); } EXPECT_FALSE(FileExists(file1)); EXPECT_FALSE(FileExists(file2)); EXPECT_FALSE(FileExists(parent)); } TEST(ScopedTempDir, WithRecursiveDirectory) { base::FilePath parent, file1, child_dir, file2; { ScopedTempDir dir; parent = dir.path(); ASSERT_TRUE(FileExists(parent)); file1 = parent.Append(FILE_PATH_LITERAL(".first-level file")); CreateFile(file1); child_dir = parent.Append(FILE_PATH_LITERAL("subdir")); CreateDirectory(child_dir); file2 = child_dir.Append(FILE_PATH_LITERAL("second level file")); CreateFile(file2); } EXPECT_FALSE(FileExists(file1)); EXPECT_FALSE(FileExists(file2)); EXPECT_FALSE(FileExists(child_dir)); EXPECT_FALSE(FileExists(parent)); } } // namespace } // namespace test } // namespace crashpad <commit_msg>Fix crashpad_util_test build with GCC after 4b450c813795<commit_after>// Copyright 2015 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test/scoped_temp_dir.h" #include <fcntl.h> #include <string.h> #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" #include "gtest/gtest.h" #include "test/errors.h" #include "test/file.h" #if defined(OS_POSIX) #include <unistd.h> #elif defined(OS_WIN) #include <direct.h> #include <io.h> #endif // OS_POSIX namespace crashpad { namespace test { namespace { void CreateFile(const base::FilePath& path) { #if defined(OS_POSIX) int fd = HANDLE_EINTR(creat(path.value().c_str(), 0644)); ASSERT_GE(fd, 0) << ErrnoMessage("creat") << " " << path.value(); // gcc refuses to compile ASSERT_EQ(IGNORE_EINTR(close(fd)), 0). int close_rv = IGNORE_EINTR(close(fd)); ASSERT_EQ(close_rv, 0) << ErrnoMessage("close") << " " << path.value(); #elif defined(OS_WIN) int fd = _wcreat(path.value().c_str(), _S_IREAD | _S_IWRITE); ASSERT_GE(fd, 0) << ErrnoMessage("_wcreat") << " " << path.value(); ASSERT_EQ(_close(fd), 0) << ErrnoMessage("_close") << " " << path.value(); #else #error "Not implemented" #endif EXPECT_TRUE(FileExists(path)); } void CreateDirectory(const base::FilePath& path) { #if defined(OS_POSIX) ASSERT_EQ(mkdir(path.value().c_str(), 0755), 0) << ErrnoMessage("mkdir") << " " << path.value(); #elif defined(OS_WIN) ASSERT_EQ(_wmkdir(path.value().c_str()), 0) << ErrnoMessage("_wmkdir") << " " << path.value(); #else #error "Not implemented" #endif ASSERT_TRUE(FileExists(path)); } TEST(ScopedTempDir, Empty) { base::FilePath path; { ScopedTempDir dir; path = dir.path(); EXPECT_TRUE(FileExists(path)); } EXPECT_FALSE(FileExists(path)); } TEST(ScopedTempDir, WithTwoFiles) { base::FilePath parent, file1, file2; { ScopedTempDir dir; parent = dir.path(); ASSERT_TRUE(FileExists(parent)); file1 = parent.Append(FILE_PATH_LITERAL("test1")); CreateFile(file1); file2 = parent.Append(FILE_PATH_LITERAL("test 2")); CreateFile(file2); } EXPECT_FALSE(FileExists(file1)); EXPECT_FALSE(FileExists(file2)); EXPECT_FALSE(FileExists(parent)); } TEST(ScopedTempDir, WithRecursiveDirectory) { base::FilePath parent, file1, child_dir, file2; { ScopedTempDir dir; parent = dir.path(); ASSERT_TRUE(FileExists(parent)); file1 = parent.Append(FILE_PATH_LITERAL(".first-level file")); CreateFile(file1); child_dir = parent.Append(FILE_PATH_LITERAL("subdir")); CreateDirectory(child_dir); file2 = child_dir.Append(FILE_PATH_LITERAL("second level file")); CreateFile(file2); } EXPECT_FALSE(FileExists(file1)); EXPECT_FALSE(FileExists(file2)); EXPECT_FALSE(FileExists(child_dir)); EXPECT_FALSE(FileExists(parent)); } } // namespace } // namespace test } // namespace crashpad <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_OBJECT_REP_HPP_INCLUDED #define LUABIND_OBJECT_REP_HPP_INCLUDED #include <boost/aligned_storage.hpp> #include <luabind/config.hpp> #include <luabind/detail/class_rep.hpp> #include <luabind/detail/instance_holder.hpp> #include <luabind/detail/ref.hpp> namespace luabind { namespace detail { void finalize(lua_State* L, class_rep* crep); // this class is allocated inside lua for each pointer. // it contains the actual c++ object-pointer. // it also tells if it is const or not. class LUABIND_API object_rep { public: object_rep(instance_holder* instance, class_rep* crep); ~object_rep(); const class_rep* crep() const { return m_classrep; } class_rep* crep() { return m_classrep; } void set_instance(instance_holder* instance) { m_instance = instance; } void add_dependency(lua_State* L, int index); void release_dependency_refs(lua_State* L); std::pair<void*, int> get_instance(class_id target) const { if (m_instance == 0) return std::pair<void*, int>((void*)0, -1); return m_instance->get(m_classrep->casts(), target); } bool is_const() const { return m_instance && m_instance->pointee_const(); } void release() { if (m_instance) m_instance->release(); } void* allocate(std::size_t size) { if (size <= 32) return &m_instance_buffer; return std::malloc(size); } void deallocate(void* storage) { if (storage == &m_instance_buffer) return; std::free(storage); } private: object_rep(object_rep const&) {} void operator=(object_rep const&) {} instance_holder* m_instance; boost::aligned_storage<32> m_instance_buffer; class_rep* m_classrep; // the class information about this object's type std::size_t m_dependency_cnt; // counts dependencies }; template<class T> struct delete_s { static void apply(void* ptr) { delete static_cast<T*>(ptr); } }; template<class T> struct destruct_only_s { static void apply(void* ptr) { // Removes unreferenced formal parameter warning on VC7. (void)ptr; #ifndef NDEBUG int completeness_check[sizeof(T)]; (void)completeness_check; #endif static_cast<T*>(ptr)->~T(); } }; LUABIND_API object_rep* get_instance(lua_State* L, int index); LUABIND_API void push_instance_metatable(lua_State* L); LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls); }} #endif // LUABIND_OBJECT_REP_HPP_INCLUDED <commit_msg>OS X 10.9 compile fix<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_OBJECT_REP_HPP_INCLUDED #define LUABIND_OBJECT_REP_HPP_INCLUDED #include <cstdlib> #include <boost/aligned_storage.hpp> #include <luabind/config.hpp> #include <luabind/detail/class_rep.hpp> #include <luabind/detail/instance_holder.hpp> #include <luabind/detail/ref.hpp> namespace luabind { namespace detail { void finalize(lua_State* L, class_rep* crep); // this class is allocated inside lua for each pointer. // it contains the actual c++ object-pointer. // it also tells if it is const or not. class LUABIND_API object_rep { public: object_rep(instance_holder* instance, class_rep* crep); ~object_rep(); const class_rep* crep() const { return m_classrep; } class_rep* crep() { return m_classrep; } void set_instance(instance_holder* instance) { m_instance = instance; } void add_dependency(lua_State* L, int index); void release_dependency_refs(lua_State* L); std::pair<void*, int> get_instance(class_id target) const { if (m_instance == 0) return std::pair<void*, int>((void*)0, -1); return m_instance->get(m_classrep->casts(), target); } bool is_const() const { return m_instance && m_instance->pointee_const(); } void release() { if (m_instance) m_instance->release(); } void* allocate(std::size_t size) { if (size <= 32) return &m_instance_buffer; return std::malloc(size); } void deallocate(void* storage) { if (storage == &m_instance_buffer) return; std::free(storage); } private: object_rep(object_rep const&) {} void operator=(object_rep const&) {} instance_holder* m_instance; boost::aligned_storage<32> m_instance_buffer; class_rep* m_classrep; // the class information about this object's type std::size_t m_dependency_cnt; // counts dependencies }; template<class T> struct delete_s { static void apply(void* ptr) { delete static_cast<T*>(ptr); } }; template<class T> struct destruct_only_s { static void apply(void* ptr) { // Removes unreferenced formal parameter warning on VC7. (void)ptr; #ifndef NDEBUG int completeness_check[sizeof(T)]; (void)completeness_check; #endif static_cast<T*>(ptr)->~T(); } }; LUABIND_API object_rep* get_instance(lua_State* L, int index); LUABIND_API void push_instance_metatable(lua_State* L); LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls); }} #endif // LUABIND_OBJECT_REP_HPP_INCLUDED <|endoftext|>
<commit_before>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/io.hpp" #include <cstring> #include <asio/read.hpp> #include <asio/write.hpp> #include <boost/bind.hpp> using namespace libtorrent; int read_message(stream_socket& s, char* buffer) { using namespace libtorrent::detail; asio::error_code ec; asio::read(s, asio::buffer(buffer, 4), asio::transfer_all(), ec); TEST_CHECK(!ec); char* ptr = buffer; int length = read_int32(ptr); asio::read(s, asio::buffer(buffer, length), asio::transfer_all(), ec); TEST_CHECK(!ec); return length; } char const* message_name[] = {"choke", "unchoke", "interested", "not_interested" , "have", "bitfield", "request", "piece", "cancel", "dht_port", "", "", "" , "suggest_piece", "have_all", "have_none", "reject_request", "allowed_fast"}; void send_allow_fast(stream_socket& s, int piece) { using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x11\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); asio::error_code ec; asio::write(s, asio::buffer(msg, 9), asio::transfer_all(), ec); TEST_CHECK(!ec); } void send_suggest_piece(stream_socket& s, int piece) { using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x0d\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); asio::error_code ec; asio::write(s, asio::buffer(msg, 9), asio::transfer_all(), ec); TEST_CHECK(!ec); } void send_unchoke(stream_socket& s) { char msg[] = "\0\0\0\x01\x01"; asio::error_code ec; asio::write(s, asio::buffer(msg, 5), asio::transfer_all(), ec); TEST_CHECK(!ec); } void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer) { char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04" " " // space for info-hash "aaaaaaaaaaaaaaaaaaaa" // peer-id "\0\0\0\x01\x0e"; // have_all asio::error_code ec; std::memcpy(handshake + 28, ih.begin(), 20); asio::write(s, asio::buffer(handshake, sizeof(handshake) - 1), asio::transfer_all(), ec); TEST_CHECK(!ec); // read handshake asio::read(s, asio::buffer(buffer, 68), asio::transfer_all(), ec); TEST_CHECK(!ec); TEST_CHECK(buffer[0] == 19); TEST_CHECK(std::memcmp(buffer + 1, "BitTorrent protocol", 19) == 0); char* extensions = buffer + 20; // check for fast extension support TEST_CHECK(extensions[7] & 0x4); #ifndef TORRENT_DISABLE_EXTENSIONS // check for extension protocol support TEST_CHECK(extensions[5] & 0x10); #endif #ifndef TORRENT_DISABLE_DHT // check for DHT support TEST_CHECK(extensions[7] & 0x1); #endif TEST_CHECK(std::memcmp(buffer + 28, ih.begin(), 20) == 0); } // makes sure that pieces that are allowed and then // rejected aren't requested again void test_reject_fast() { boost::intrusive_ptr<torrent_info> t = create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000)); ses1.add_torrent(t, "./tmp1"); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> allowed_fast; allowed_fast.push_back(0); allowed_fast.push_back(1); allowed_fast.push_back(2); allowed_fast.push_back(3); std::for_each(allowed_fast.begin(), allowed_fast.end() , bind(&send_allow_fast, boost::ref(s), _1)); while (!allowed_fast.empty()) { read_message(s, recv_buffer); int msg = recv_buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) std::cerr << message_name[msg] << std::endl; else std::cerr << msg << std::endl; if (recv_buffer[0] != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(allowed_fast.begin() , allowed_fast.end(), piece); TEST_CHECK(i != allowed_fast.end()); if (i != allowed_fast.end()) allowed_fast.erase(i); // send reject request recv_buffer[0] = 0x10; asio::error_code ec; asio::write(s, asio::buffer("\0\0\0\x0d", 4), asio::transfer_all(), ec); TEST_CHECK(!ec); asio::write(s, asio::buffer(recv_buffer, 13), asio::transfer_all(), ec); TEST_CHECK(!ec); } } void test_respect_suggest() { boost::intrusive_ptr<torrent_info> t = create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000)); ses1.add_torrent(t, "./tmp1"); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> suggested; suggested.push_back(0); suggested.push_back(1); suggested.push_back(2); suggested.push_back(3); std::for_each(suggested.begin(), suggested.end() , bind(&send_suggest_piece, boost::ref(s), _1)); send_unchoke(s); int fail_counter = 100; while (!suggested.empty() && fail_counter > 0) { read_message(s, recv_buffer); std::cerr << "msg: "; int msg = recv_buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) std::cerr << message_name[msg] << std::endl; else std::cerr << msg << std::endl; fail_counter--; if (recv_buffer[0] != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(suggested.begin() , suggested.end(), piece); TEST_CHECK(i != suggested.end()); if (i != suggested.end()) suggested.erase(i); // send reject request recv_buffer[0] = 0x10; asio::error_code ec; asio::write(s, asio::buffer("\0\0\0\x0d", 4), asio::transfer_all(), ec); TEST_CHECK(!ec); asio::write(s, asio::buffer(recv_buffer, 13), asio::transfer_all(), ec); TEST_CHECK(!ec); } TEST_CHECK(fail_counter > 0); } int test_main() { test_reject_fast(); test_respect_suggest(); return 0; } <commit_msg>more verbose logging in test_fast_extension and avoids infinite loops in case of failures<commit_after>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/io.hpp" #include <cstring> #include <asio/read.hpp> #include <asio/write.hpp> #include <boost/bind.hpp> using namespace libtorrent; int read_message(stream_socket& s, char* buffer) { using namespace libtorrent::detail; asio::error_code ec; asio::read(s, asio::buffer(buffer, 4), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } char* ptr = buffer; int length = read_int32(ptr); asio::read(s, asio::buffer(buffer, length), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } return length; } char const* message_name[] = {"choke", "unchoke", "interested", "not_interested" , "have", "bitfield", "request", "piece", "cancel", "dht_port", "", "", "" , "suggest_piece", "have_all", "have_none", "reject_request", "allowed_fast"}; void send_allow_fast(stream_socket& s, int piece) { std::cout << "send allow fast: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x11\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); asio::error_code ec; asio::write(s, asio::buffer(msg, 9), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } } void send_suggest_piece(stream_socket& s, int piece) { std::cout << "send suggest piece: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x0d\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); asio::error_code ec; asio::write(s, asio::buffer(msg, 9), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } } void send_unchoke(stream_socket& s) { std::cout << "send unchoke" << std::endl; char msg[] = "\0\0\0\x01\x01"; asio::error_code ec; asio::write(s, asio::buffer(msg, 5), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } } void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer) { char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04" " " // space for info-hash "aaaaaaaaaaaaaaaaaaaa" // peer-id "\0\0\0\x01\x0e"; // have_all std::cout << "send handshake" << std::endl; asio::error_code ec; std::memcpy(handshake + 28, ih.begin(), 20); asio::write(s, asio::buffer(handshake, sizeof(handshake) - 1), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } // read handshake asio::read(s, asio::buffer(buffer, 68), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } std::cout << "received handshake" << std::endl; TEST_CHECK(buffer[0] == 19); TEST_CHECK(std::memcmp(buffer + 1, "BitTorrent protocol", 19) == 0); char* extensions = buffer + 20; // check for fast extension support TEST_CHECK(extensions[7] & 0x4); #ifndef TORRENT_DISABLE_EXTENSIONS // check for extension protocol support TEST_CHECK(extensions[5] & 0x10); #endif #ifndef TORRENT_DISABLE_DHT // check for DHT support TEST_CHECK(extensions[7] & 0x1); #endif TEST_CHECK(std::memcmp(buffer + 28, ih.begin(), 20) == 0); } // makes sure that pieces that are allowed and then // rejected aren't requested again void test_reject_fast() { boost::intrusive_ptr<torrent_info> t = create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000)); ses1.add_torrent(t, "./tmp1"); test_sleep(1000000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> allowed_fast; allowed_fast.push_back(0); allowed_fast.push_back(1); allowed_fast.push_back(2); allowed_fast.push_back(3); std::for_each(allowed_fast.begin(), allowed_fast.end() , bind(&send_allow_fast, boost::ref(s), _1)); while (!allowed_fast.empty()) { read_message(s, recv_buffer); int msg = recv_buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) std::cerr << message_name[msg] << std::endl; else std::cerr << msg << std::endl; if (recv_buffer[0] != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(allowed_fast.begin() , allowed_fast.end(), piece); TEST_CHECK(i != allowed_fast.end()); if (i != allowed_fast.end()) allowed_fast.erase(i); // send reject request recv_buffer[0] = 0x10; asio::error_code ec; asio::write(s, asio::buffer("\0\0\0\x0d", 4), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } asio::write(s, asio::buffer(recv_buffer, 13), asio::transfer_all(), ec); std::cout << ec.message() << std::endl; if (ec) { std::cout << ec.message() << std::endl; exit(1); } } } void test_respect_suggest() { boost::intrusive_ptr<torrent_info> t = create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000)); ses1.add_torrent(t, "./tmp1"); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1"), ses1.listen_port())); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> suggested; suggested.push_back(0); suggested.push_back(1); suggested.push_back(2); suggested.push_back(3); std::for_each(suggested.begin(), suggested.end() , bind(&send_suggest_piece, boost::ref(s), _1)); send_unchoke(s); int fail_counter = 100; while (!suggested.empty() && fail_counter > 0) { read_message(s, recv_buffer); std::cerr << "msg: "; int msg = recv_buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) std::cerr << message_name[msg] << std::endl; else std::cerr << msg << std::endl; fail_counter--; if (recv_buffer[0] != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(suggested.begin() , suggested.end(), piece); TEST_CHECK(i != suggested.end()); if (i != suggested.end()) suggested.erase(i); // send reject request recv_buffer[0] = 0x10; asio::error_code ec; asio::write(s, asio::buffer("\0\0\0\x0d", 4), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } asio::write(s, asio::buffer(recv_buffer, 13), asio::transfer_all(), ec); if (ec) { std::cout << ec.message() << std::endl; exit(1); } } TEST_CHECK(fail_counter > 0); } int test_main() { test_reject_fast(); test_respect_suggest(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbObjectList.h" #include "otbBandMathImageFilterX.h" namespace otb { namespace Wrapper { class BandMathX : public Application { public: /** Standard class typedefs. */ typedef BandMathX Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMathX, otb::Application); typedef otb::BandMathImageFilterX<FloatVectorImageType> BandMathImageFilterType; private: void DoInit() { SetName("BandMathX"); SetDescription("This application performs mathematical operations on multiband images.\n" "Mathematical formula interpretation is done via muParserX libraries https://code.google.com/p/muparserx/"); SetDocName("Band Math X"); SetDocLongDescription("The goal of this documentation is to give the user some hints about the syntax used in this application.\n" "The syntax is mainly constrained by the muparserx library, which can be considered as the core of the application.\n" "\n\n" "- Fundamentals:\n\n" "The default prefix name for variables related to the ith input is « im(i+1) » (note the indexing from 1 to N, for N inputs). \n" "The following list summaries the available variables for input #0 (and so on for every input): \n" "\n" "im1 --> a pixel from first input, made of n components (n bands)\n" "im1bj --> jth component of a pixel from first input (first band is indexed by 1)\n" "im1bjNkxp --> a neighbourhood (“N”) of pixels of the jth component from first input, of size kxp\n" "im1PhyX and im1PhyY --> spacing of first input in X and Y directions (horizontal and vertical)\n" "\nMoreover, we also have the following generic variables:\n" "idxX and idxY --> indices of the current pixel\n" "\n" "Always keep in mind that this application only addresses mathematically well-defined formulas.\n" "For instance, it is not possible to add vectors of different dimensions (this implies the addition of a row vector with a column vector),\n" "or add a scalar to a vector or a matrix, or divide two vectors, and so on...\n" "Thus, it is important to remember that a pixel of n components is always represented as a row vector.\n" "\n" "Example :\n\n" " im1 + im2 \n" "\nrepresents the addition of pixels from first and second inputs. This expression is consistent only if\n" "both inputs have the same number of bands.\n" "Note that it is also possible to use the following expressions to obtain the same result:\n" "\n" " im1b1 + im2b1 \n" " im1b2 + im2b2 \n" " ...." "\n\nNevertheless, the first expression is by far much pleaseant. We call this new functionnality the 'batch mode'\n" "(performing the same operation in a band-to-band fashion).\n" "\n\n" "- Operations involving neighborhoods of pixels:\n\n" "Another new fonctionnality is the possibility to perform operations that involve neighborhoods of pixels.\n" "Variable related to such neighborhoods are always defined following the pattern imIbJNKxP, where: \n" "- I is an number identifying the image input (rememeber, input #0 <=> im1, and so on)\n" "- J is an number identifying the band (remember, first band is indexed by 1)\n" "- KxP are two numbers that represent the size of the neighborhood (first one is related to the horizontal direction)\n" "All neighborhood are centred, thus K and P must be odd numbers.\n" "Many operators come with this new functionnality: conv, mean var median min max...\n" "For instance, if im1 represents the pixel of 3 bands image:\n\n" " im1 - mean(im1b1N5x5,im1b2N5x5,im1b3N5x5)\n" "\ncould represent a high pass filter (Note that by implying three neighborhoods, the operator returned a row vector of three components.\n" "It is a typical behaviour for several operators of this application).\n" "\n\n" "- Operators:\n\n" "In addition to the previous operators, other operators are available:\n" "- existing operators/functions from muParserX, that were not originally defined for vectors and\n" "matrices (for instance cos, sin, ...). These new operators/ functions keep the original names to\n" "which we add the prefix ”v” for vector (vcos, vsin, ...).\n" "- mult and div operators, that perform element-wise multiplication or division of vector/matrices (for instance im1 div im2)\n" "- bands, which is a very usefull operator. It allows to select specific bands from an image, and/or to rearrange them in a new vector;\n" "for instance bands(im1,{1,2,1,1}) produces a vector of 4 components made of band 1, band 2, band 1 and band 1 values from the first input.\n" "Note that curly brackets must be used in order to select the desired band indices.\n" "\n\n" "- Application itself:\n\n" "Setting the list of inputs can be done with the 'il' parameter.\n" "Setting an expression can be done with the 'exp' parameter.\n" "Setting the output image can be done with the 'out' parameter.\n" "\n\n" "Finally, we strongly recommend that the reader takes a look at the cookbook, where additional information can be found.\n" ); SetDocLimitations("Only one output is possible (to be improved)"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag("Util"); AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image."); AddRAMParameter(); AddParameter(ParameterType_StringList, "exp", "Expression"); SetParameterDescription("exp", "The mathematical expression to apply."); MandatoryOff("exp"); AddParameter(ParameterType_String, "incontext", "Import context"); SetParameterDescription("incontext", "A txt file containing user's constants and expressions."); MandatoryOff("incontext"); AddParameter(ParameterType_String, "outcontext", "Export context"); SetParameterDescription("outcontext", "A txt file containing user's constants and expressions."); MandatoryOff("outcontext"); // Doc example parameter settings SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"); SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif"); SetDocExampleParameterValue("exp", "\"cos(im1b1)+im2b1*im3b1-im3b2+ndvi(im3b3, im3b4)\""); } void DoUpdateParameters() { } void DoExecute() { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages == 0) { itkExceptionMacro("No input Image set...; please set at least one input image"); } if ( (!HasUserValue("exp")) && (!HasUserValue("incontext")) ) { itkExceptionMacro("No expression set...; please set at least one one expression"); } m_Filter = BandMathImageFilterType::New(); for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); m_Filter->SetNthInput(i,currentImage); } if ( (HasUserValue("exp")) && (IsParameterEnabled("exp")) ) { std::vector<std::string> stringList = GetParameterStringList("exp"); for(int s=0; s<stringList.size(); s++) m_Filter->SetExpression(stringList[s]); } if ( (HasUserValue("incontext")) && (IsParameterEnabled("incontext")) ) m_Filter->importContext(GetParameterString("incontext")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); if ( (HasUserValue("outcontext")) && (IsParameterEnabled("outcontext")) ) m_Filter->exportContext(GetParameterString("outcontext")); } BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMathX) <commit_msg>BandMathX app: documentation improved<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbObjectList.h" #include "otbBandMathImageFilterX.h" namespace otb { namespace Wrapper { class BandMathX : public Application { public: /** Standard class typedefs. */ typedef BandMathX Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMathX, otb::Application); typedef otb::BandMathImageFilterX<FloatVectorImageType> BandMathImageFilterType; private: void DoInit() { SetName("BandMathX"); SetDescription("This application performs mathematical operations on multiband images.\n" "Mathematical formula interpretation is done via muParserX libraries https://code.google.com/p/muparserx/"); SetDocName("Band Math X"); SetDocLongDescription("The goal of this documentation is to give the user some hints about the syntax used in this application.\n" "The syntax is mainly constrained by the muparserx library, which can be considered as the core of the application.\n" "\n\n" "- Fundamentals:\n\n" "The default prefix name for variables related to the ith input is « im(i+1) » (note the indexing from 1 to N, for N inputs). \n" "The following list summaries the available variables for input #0 (and so on for every input): \n" "\n" "im1 --> a pixel from first input, made of n components (n bands)\n" "im1bj --> jth component of a pixel from first input (first band is indexed by 1)\n" "im1bjNkxp --> a neighbourhood (“N”) of pixels of the jth component from first input, of size kxp\n" "im1PhyX and im1PhyY --> spacing of first input in X and Y directions (horizontal and vertical)\n" "\nMoreover, we also have the following generic variables:\n" "idxX and idxY --> indices of the current pixel\n" "\n" "Always keep in mind that this application only addresses mathematically well-defined formulas.\n" "For instance, it is not possible to add vectors of different dimensions (this implies the addition of a row vector with a column vector),\n" "or add a scalar to a vector or a matrix, or divide two vectors, and so on...\n" "Thus, it is important to remember that a pixel of n components is always represented as a row vector.\n" "\n" "Example :\n\n" " im1 + im2 \n" "\nrepresents the addition of pixels from first and second inputs. This expression is consistent only if\n" "both inputs have the same number of bands.\n" "Note that it is also possible to use the following expressions to obtain the same result:\n" "\n" " im1b1 + im2b1 \n" " im1b2 + im2b2 \n" " ...." "\n\nNevertheless, the first expression is by far much pleaseant. We call this new functionnality the 'batch mode'\n" "(performing the same operation in a band-to-band fashion).\n" "\n\n" "- Operations involving neighborhoods of pixels:\n\n" "Another new fonctionnality is the possibility to perform operations that involve neighborhoods of pixels.\n" "Variable related to such neighborhoods are always defined following the pattern imIbJNKxP, where: \n" "- I is an number identifying the image input (rememeber, input #0 <=> im1, and so on)\n" "- J is an number identifying the band (remember, first band is indexed by 1)\n" "- KxP are two numbers that represent the size of the neighborhood (first one is related to the horizontal direction)\n" "All neighborhood are centred, thus K and P must be odd numbers.\n" "Many operators come with this new functionnality: conv, mean var median min max...\n" "For instance, if im1 represents the pixel of 3 bands image:\n\n" " im1 - mean(im1b1N5x5,im1b2N5x5,im1b3N5x5)\n" "\ncould represent a high pass filter (Note that by implying three neighborhoods, the operator returned a row vector of three components.\n" "It is a typical behaviour for several operators of this application).\n" "\n\n" "- Operators:\n\n" "In addition to the previous operators, other operators are available:\n" "- existing operators/functions from muParserX, that were not originally defined for vectors and\n" "matrices (for instance cos, sin, ...). These new operators/ functions keep the original names to\n" "which we add the prefix ”v” for vector (vcos, vsin, ...).\n" "- mult and div operators, that perform element-wise multiplication or division of vector/matrices (for instance im1 div im2)\n" "- bands, which is a very usefull operator. It allows to select specific bands from an image, and/or to rearrange them in a new vector;\n" "for instance bands(im1,{1,2,1,1}) produces a vector of 4 components made of band 1, band 2, band 1 and band 1 values from the first input.\n" "Note that curly brackets must be used in order to select the desired band indices.\n" "\n\n" "- Application itself:\n\n" "The application takes the following parameters :" "- Setting the list of inputs can be done with the 'il' parameter.\n" "- Setting expressions can be done with the 'exp' parameter. Separating expressions by semi-colons (;) will concatenate their results into one multiband output image.\n" "Adding expressions without the use of semi-colons will produce additional output images (not implemented yet).\n" "- Setting constants can be done with the 'incontext' parameter. User must provide a txt file with a specific syntax: #type name value\n" "An example of such a file is given below:\n\n" "#F expo 1.1\n" "#M kernel1 { 0.1 , 0.2 , 0.3 ; 0.4 , 0.5 , 0.6 ; 0.7 , 0.8 , 0.9 ; 1 , 1.1 , 1.2 ; 1.3 , 1.4 , 1.5 }\n" "\nAs we can see, #I/#F allows the definition of an integer/float constant, whereas #M allows the definition of a vector/matrix.\n" "In the latter case, elements of a row must be separated by comma, and rows must be separated by semicolons.\n" "It is also possible to define expressions within the same txt file, with the pattern #E expr; they will be added to the list of expressions to be applied. For instance:\n\n" "#E conv(kernel1,im1b1N3x5) ; im2b1^expo\n" "\n- The 'outcontext' parameter allows to save user's constants and expressions (context).\n" "- Setting the output image can be done with the 'out' parameter (multi-outputs is not implemented yet).\n" "\n\n" "Finally, we strongly recommend that the reader takes a look at the cookbook, where additional information can be found (http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf).\n" ); SetDocLimitations("Only one output is possible (to be improved)"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag("Util"); AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image."); AddRAMParameter(); AddParameter(ParameterType_StringList, "exp", "Expressions"); SetParameterDescription("exp", "Mathematical expressions to apply."); MandatoryOff("exp"); AddParameter(ParameterType_String, "incontext", "Import context"); SetParameterDescription("incontext", "A txt file containing user's constants and expressions."); MandatoryOff("incontext"); AddParameter(ParameterType_String, "outcontext", "Export context"); SetParameterDescription("outcontext", "A txt file where to save user's constants and expressions."); MandatoryOff("outcontext"); // Doc example parameter settings SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"); SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif"); SetDocExampleParameterValue("exp", "\"cos(im1b1)+im2b1*im3b1-im3b2+ndvi(im3b3, im3b4)\""); } void DoUpdateParameters() { } void DoExecute() { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages == 0) { itkExceptionMacro("No input Image set...; please set at least one input image"); } if ( (!HasUserValue("exp")) && (!HasUserValue("incontext")) ) { itkExceptionMacro("No expression set...; please set at least one one expression"); } m_Filter = BandMathImageFilterType::New(); for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); m_Filter->SetNthInput(i,currentImage); } if ( (HasUserValue("exp")) && (IsParameterEnabled("exp")) ) { std::vector<std::string> stringList = GetParameterStringList("exp"); for(int s=0; s<stringList.size(); s++) m_Filter->SetExpression(stringList[s]); } if ( (HasUserValue("incontext")) && (IsParameterEnabled("incontext")) ) m_Filter->importContext(GetParameterString("incontext")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); if ( (HasUserValue("outcontext")) && (IsParameterEnabled("outcontext")) ) m_Filter->exportContext(GetParameterString("outcontext")); } BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMathX) <|endoftext|>
<commit_before><commit_msg>ENH: handle cleaning of temporary files<commit_after><|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <chrono> #include "joynr/JoynrClusterControllerRuntime.h" #include "joynr/Settings.h" #include "joynr/SystemServicesSettings.h" #include "joynr/system/ProviderReregistrationControllerProxy.h" #include "utils/TestLibJoynrWebSocketRuntime.h" using namespace ::testing; using namespace joynr; TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime) { auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings"); joynr::SystemServicesSettings systemServiceSettings(*integrationSettings); const std::string domain(systemServiceSettings.getDomain()); auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings)); runtime->init(); runtime->start(); auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain); auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build(); Semaphore finishedSemaphore; providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr); EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10))); runtime->stop(); runtime = nullptr; } TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime) { auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings"); joynr::SystemServicesSettings systemServiceSettings(*integrationSettings); const std::string domain(systemServiceSettings.getDomain()); auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings)); ccRuntime->init(); ccRuntime->start(); auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings"); auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr); ASSERT_TRUE(wsRuntime->connect(std::chrono::seconds(2))); auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain); auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build(); Semaphore finishedSemaphore; providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); }); EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10))); wsRuntime = nullptr; ccRuntime->stop(); ccRuntime = nullptr; } <commit_msg>[C++] Increase discovery timeouts in ProviderReregistrationControllerTest<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <chrono> #include "joynr/JoynrClusterControllerRuntime.h" #include "joynr/Settings.h" #include "joynr/SystemServicesSettings.h" #include "joynr/system/ProviderReregistrationControllerProxy.h" #include "joynr/DiscoveryQos.h" #include "utils/TestLibJoynrWebSocketRuntime.h" using namespace ::testing; using namespace joynr; TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime) { auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings"); joynr::SystemServicesSettings systemServiceSettings(*integrationSettings); const std::string domain(systemServiceSettings.getDomain()); auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings)); runtime->init(); runtime->start(); DiscoveryQos discoveryQos; discoveryQos.setDiscoveryTimeoutMs(3000); auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain); auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->setDiscoveryQos(discoveryQos)->build(); Semaphore finishedSemaphore; providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr); EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10))); runtime->stop(); runtime = nullptr; } TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime) { auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings"); joynr::SystemServicesSettings systemServiceSettings(*integrationSettings); const std::string domain(systemServiceSettings.getDomain()); auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings)); ccRuntime->init(); ccRuntime->start(); DiscoveryQos discoveryQos; discoveryQos.setDiscoveryTimeoutMs(3000); auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings"); auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr); ASSERT_TRUE(wsRuntime->connect(std::chrono::seconds(2))); auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain); auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->setDiscoveryQos(discoveryQos)->build(); Semaphore finishedSemaphore; providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); }); EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10))); wsRuntime = nullptr; ccRuntime->stop(); ccRuntime = nullptr; } <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <cluster/PluginConfig.h> #include <boost/concept_check.hpp> #include <jccl/Config/ConfigElement.h> #include <plugins/StartBarrierPlugin/StartBarrierPlugin.h> #include <gadget/Util/Debug.h> #include <cluster/ClusterDepChecker.h> #include <cluster/ClusterManager.h> #include <cluster/ClusterNetwork.h> #include <gadget/Node.h> #include <cluster/Packets/StartBlock.h> extern "C" { GADGET_CLUSTER_PLUGIN_EXPORT(void) initPlugin(cluster::ClusterManager* mgr) { mgr->addPlugin(new cluster::StartBarrierPlugin()); } } namespace cluster { StartBarrierPlugin::StartBarrierPlugin() : mBarrierMaster(false) , mComplete(false) , mHandlerGUID("566a50ff-5e73-43e0-a9a9-0fb62b76731a") {;} StartBarrierPlugin::~StartBarrierPlugin() { } void StartBarrierPlugin::handlePacket(Packet* packet, gadget::Node* node) { // On Barrier Recv // -If Master // -Remove Pending slave // -If all recved // -Send responce to all nodes // -Set Running TRUE // -Else // -Set Running TRUE if ( NULL != packet && NULL != node ) { if(packet->getPacketType() == cluster::Header::RIM_START_BLOCK) { //We are not actually using any data in this packet for now. //StartBlock* temp_start_block = dynamic_cast<StartBlock*>(packet); //vprASSERT(NULL != temp_start_block && "Dynamic cast failed!"); if (isBarrierMaster()) { removePendingBarrierSlave(node->getHostname()); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "handlePacket() Master has received a START signal.\n" << vprDEBUG_FLUSH; } else { vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "handlePacket() Slave has finished start barrier\n" << vprDEBUG_FLUSH; mComplete = true; ClusterManager::instance()->setClusterReady(true); } } else { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"StartBarrierPlugin::handlePacket() ERROR: ") << "We do not handle this type of packet.\n" << vprDEBUG_FLUSH; } } } /** Add the pending element to the configuration. * @pre configCanHandle (element) == true. * @return true iff element was successfully added to configuration. */ bool StartBarrierPlugin::configAdd(jccl::ConfigElementPtr element) { // -If the cluster manager has been configured. if(!ClusterManager::instance()->isClusterActive()) { // XXX: This could be made into a dependancy also. return false; } mPendingSlaves = ClusterManager::instance()->getNodes(); mSlaves = ClusterManager::instance()->getNodes(); ///////////////////////////////////////// // Starting Barrier Stuff // // -Set flag we have started configuring the cluster // -Get Sync Machine element Name // -Get ElementPtr to this element // -Get the Hostname of this node mBarrierMachineElementName = element->getProperty<std::string>(std::string("start_master")); jccl::ConfigElementPtr barrier_machine_element = ClusterManager::instance()->getConfigElementPointer(mBarrierMachineElementName); vprASSERT(NULL != barrier_machine_element.get() && "StartBarrierPlugin element must have a start_master."); mBarrierMasterHostname = barrier_machine_element->getProperty<std::string>(std::string("host_name")); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Start Master element Name is: " << mBarrierMachineElementName << std::endl << vprDEBUG_FLUSH; vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Start Master Hostname is: " << mBarrierMasterHostname << std::endl << vprDEBUG_FLUSH; // Starting Barrier Stuff ///////////////////////////////////// if (ClusterNetwork::isLocalHost(mBarrierMasterHostname)) { mBarrierMaster = true; } else { mBarrierMaster = false; } return true; } /** Remove the pending element from the current configuration. * @pre configCanHandle (element) == true. * @return true iff the element (and any objects it represented) * were successfully removed. */ bool StartBarrierPlugin::configRemove(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** Checks if this handler can process element. * Typically, an implementation of handler will check the element's * description name/token to decide if it knows how to deal with * it. * @return true iff this handler can process element. */ bool StartBarrierPlugin::configCanHandle(jccl::ConfigElementPtr element) { return recognizeStartBarrierPluginConfig(element); } bool StartBarrierPlugin::recognizeStartBarrierPluginConfig(jccl::ConfigElementPtr element) { return element->getID() == getElementType(); } void StartBarrierPlugin::preDraw() {; } void StartBarrierPlugin::postPostFrame() { // -If we are not complete // -If all other plugins are ready // -If Slave // -Find the barrier master // -If connected // -Send a start block // -Else // -Add barrier node to pending list // -Else // -If number of pending start nodes is 0 // -Send a start block to all of them //This is where all the real work gets done if (!mComplete) { if (ClusterManager::instance()->pluginsReady() && 0 == ClusterManager::instance()->getNetwork()->getNumPendingNodes()) { if (!mBarrierMaster) { gadget::Node* start_master = ClusterManager::instance()->getNetwork()->getNodeByName(mBarrierMachineElementName); if (NULL == start_master) { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"[StartBarrierPlugin] Barrier machine configuration element not yet loaded.") << std::endl << vprDEBUG_FLUSH; } else if (start_master->isConnected()) { //Send packet to server machine StartBlock temp_start_block(getHandlerGUID(), 0); start_master->send(&temp_start_block); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Sending signal to start master: " << mBarrierMasterHostname << std::endl << vprDEBUG_FLUSH; } else { //If we are not connected and we are not in pending list, add to the pending list if (gadget::Node::PENDING != start_master->getStatus()) { start_master->setStatus(gadget::Node::PENDING); } } } else { vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Barrier Master waiting...\n" << vprDEBUG_FLUSH; int num_pending_nodes = getPendingBarrierSlaves().size(); if (0 == num_pending_nodes) { mComplete = true; ClusterManager::instance()->setClusterReady(true); std::cout << "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX DONE - list=0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" << std::endl; StartBlock temp_start_block(getHandlerGUID(), 0); //Send responce to all nodes for (std::vector<std::string>::iterator i = mSlaves.begin(); i != mSlaves.end() ; i++) { vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_STATUS_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Sending start signal to slave: " << (*i) << std::endl << vprDEBUG_FLUSH; // Dead lock since we are actually in a recursion of Nodes gadget::Node* node = ClusterManager::instance()->getNetwork()->getNodeByHostname(*i); if(NULL == node) { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Error, could not find a Node by the name of: " << (*i) << std::endl << vprDEBUG_FLUSH; } else { node->send(&temp_start_block); } } }//End (0==num_pending_nodes) }//End (mBarrierMaster) }//End (Plugins Ready) }//End (!mComplete) } bool StartBarrierPlugin::isPluginReady() { return true; } } // End of gadget namespace <commit_msg>Bug fixed: Fixed the StartBarrierPlugin to work with the new and improved ClusterNetwork.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <cluster/PluginConfig.h> #include <boost/concept_check.hpp> #include <jccl/Config/ConfigElement.h> #include <plugins/StartBarrierPlugin/StartBarrierPlugin.h> #include <gadget/Util/Debug.h> #include <cluster/ClusterDepChecker.h> #include <cluster/ClusterManager.h> #include <cluster/ClusterNetwork.h> #include <gadget/Node.h> #include <cluster/Packets/StartBlock.h> extern "C" { GADGET_CLUSTER_PLUGIN_EXPORT(void) initPlugin(cluster::ClusterManager* mgr) { mgr->addPlugin(new cluster::StartBarrierPlugin()); } } namespace cluster { StartBarrierPlugin::StartBarrierPlugin() : mBarrierMaster(false) , mComplete(false) , mHandlerGUID("566a50ff-5e73-43e0-a9a9-0fb62b76731a") {;} StartBarrierPlugin::~StartBarrierPlugin() { } void StartBarrierPlugin::handlePacket(Packet* packet, gadget::Node* node) { // On Barrier Recv // -If Master // -Remove Pending slave // -If all recved // -Send responce to all nodes // -Set Running TRUE // -Else // -Set Running TRUE if ( NULL != packet && NULL != node ) { if(packet->getPacketType() == cluster::Header::RIM_START_BLOCK) { //We are not actually using any data in this packet for now. //StartBlock* temp_start_block = dynamic_cast<StartBlock*>(packet); //vprASSERT(NULL != temp_start_block && "Dynamic cast failed!"); if (isBarrierMaster()) { removePendingBarrierSlave(node->getHostname()); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "handlePacket() Master has received a START signal.\n" << vprDEBUG_FLUSH; } else { vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "handlePacket() Slave has finished start barrier\n" << vprDEBUG_FLUSH; mComplete = true; ClusterManager::instance()->setClusterReady(true); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_STATUS_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Received signal from master, barrier released." << std::endl << vprDEBUG_FLUSH; } } else { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"StartBarrierPlugin::handlePacket() ERROR: ") << "We do not handle this type of packet.\n" << vprDEBUG_FLUSH; } } } /** Add the pending element to the configuration. * @pre configCanHandle (element) == true. * @return true iff element was successfully added to configuration. */ bool StartBarrierPlugin::configAdd(jccl::ConfigElementPtr element) { // -If the cluster manager has been configured. if(!ClusterManager::instance()->isClusterActive()) { // XXX: This could be made into a dependancy also. return false; } mPendingSlaves = ClusterManager::instance()->getNodes(); mSlaves = ClusterManager::instance()->getNodes(); ///////////////////////////////////////// // Starting Barrier Stuff // // -Set flag we have started configuring the cluster // -Get Sync Machine element Name // -Get ElementPtr to this element // -Get the Hostname of this node mBarrierMachineElementName = element->getProperty<std::string>(std::string("start_master")); jccl::ConfigElementPtr barrier_machine_element = ClusterManager::instance()->getConfigElementPointer(mBarrierMachineElementName); vprASSERT(NULL != barrier_machine_element.get() && "StartBarrierPlugin element must have a start_master."); mBarrierMasterHostname = barrier_machine_element->getProperty<std::string>(std::string("host_name")); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Start Master element Name is: " << mBarrierMachineElementName << std::endl << vprDEBUG_FLUSH; vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Start Master Hostname is: " << mBarrierMasterHostname << std::endl << vprDEBUG_FLUSH; // Starting Barrier Stuff ///////////////////////////////////// if (ClusterNetwork::isLocalHost(mBarrierMasterHostname)) { mBarrierMaster = true; } else { mBarrierMaster = false; } return true; } /** Remove the pending element from the current configuration. * @pre configCanHandle (element) == true. * @return true iff the element (and any objects it represented) * were successfully removed. */ bool StartBarrierPlugin::configRemove(jccl::ConfigElementPtr element) { boost::ignore_unused_variable_warning(element); return false; } /** Checks if this handler can process element. * Typically, an implementation of handler will check the element's * description name/token to decide if it knows how to deal with * it. * @return true iff this handler can process element. */ bool StartBarrierPlugin::configCanHandle(jccl::ConfigElementPtr element) { return recognizeStartBarrierPluginConfig(element); } bool StartBarrierPlugin::recognizeStartBarrierPluginConfig(jccl::ConfigElementPtr element) { return element->getID() == getElementType(); } void StartBarrierPlugin::preDraw() {; } void StartBarrierPlugin::postPostFrame() { // -If we are not complete // -If all other plugins are ready // -If Slave // -Find the barrier master // -If connected // -Send a start block // -Else // -Add barrier node to pending list // -Else // -If number of pending start nodes is 0 // -Send a start block to all of them //This is where all the real work gets done if (!mComplete) { if (ClusterManager::instance()->pluginsReady() && 0 == ClusterManager::instance()->getNetwork()->getNumPendingNodes()) { if (!mBarrierMaster) { gadget::Node* start_master = ClusterManager::instance()->getNetwork()->getNodeByName(mBarrierMachineElementName); if (NULL == start_master) { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"[StartBarrierPlugin] Barrier machine configuration element not yet loaded.") << std::endl << vprDEBUG_FLUSH; } else if (start_master->isConnected()) { //Send packet to server machine StartBlock temp_start_block(getHandlerGUID(), 0); start_master->send(&temp_start_block); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Sending signal to start master: " << mBarrierMasterHostname << std::endl << vprDEBUG_FLUSH; } else { //If we are not connected and we are not in pending list, add to the pending list if (gadget::Node::DISCONNECTED == start_master->getStatus()) { vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Moving node: " << start_master->getName() << " to pending state because we need to connect to it." << std::endl << vprDEBUG_FLUSH; start_master->setStatus(gadget::Node::PENDING); } } } else { vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Barrier Master waiting...\n" << vprDEBUG_FLUSH; int num_pending_nodes = getPendingBarrierSlaves().size(); if (0 == num_pending_nodes) { mComplete = true; ClusterManager::instance()->setClusterReady(true); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_STATUS_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Pending nodes list empty, releasing all slave nodes." << std::endl << vprDEBUG_FLUSH; StartBlock temp_start_block(getHandlerGUID(), 0); //Send responce to all nodes for (std::vector<std::string>::iterator i = mSlaves.begin(); i != mSlaves.end() ; i++) { vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_STATUS_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Sending start signal to slave: " << (*i) << std::endl << vprDEBUG_FLUSH; // Dead lock since we are actually in a recursion of Nodes gadget::Node* node = ClusterManager::instance()->getNetwork()->getNodeByHostname(*i); if(NULL == node) { vprDEBUG(gadgetDBG_RIM,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrCYAN,"[StartBarrierPlugin] ") << "Error, could not find a Node by the name of: " << (*i) << std::endl << vprDEBUG_FLUSH; } else { node->send(&temp_start_block); } } }//End (0==num_pending_nodes) }//End (mBarrierMaster) }//End (Plugins Ready) }//End (!mComplete) } bool StartBarrierPlugin::isPluginReady() { return true; } } // End of gadget namespace <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // 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/. #define EIGEN_DEBUG_ASSIGN #include "main.h" #include <typeinfo> std::string demangle_traversal(int t) { if(t==DefaultTraversal) return "DefaultTraversal"; if(t==LinearTraversal) return "LinearTraversal"; if(t==InnerVectorizedTraversal) return "InnerVectorizedTraversal"; if(t==LinearVectorizedTraversal) return "LinearVectorizedTraversal"; if(t==SliceVectorizedTraversal) return "SliceVectorizedTraversal"; return "?"; } std::string demangle_unrolling(int t) { if(t==NoUnrolling) return "NoUnrolling"; if(t==InnerUnrolling) return "InnerUnrolling"; if(t==CompleteUnrolling) return "CompleteUnrolling"; return "?"; } template<typename Dst, typename Src> bool test_assign(const Dst&, const Src&, int traversal, int unrolling) { internal::assign_traits<Dst,Src>::debug(); bool res = internal::assign_traits<Dst,Src>::Traversal==traversal && internal::assign_traits<Dst,Src>::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << "\n"; } return res; } template<typename Dst, typename Src> bool test_assign(int traversal, int unrolling) { internal::assign_traits<Dst,Src>::debug(); bool res = internal::assign_traits<Dst,Src>::Traversal==traversal && internal::assign_traits<Dst,Src>::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << "\n"; } return res; } template<typename Xpr> bool test_redux(const Xpr&, int traversal, int unrolling) { typedef internal::redux_traits<internal::scalar_sum_op<typename Xpr::Scalar>,Xpr> traits; bool res = traits::Traversal==traversal && traits::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(traits::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(traits::Unrolling) << "\n"; } return res; } template<typename Scalar, bool Enable = internal::packet_traits<Scalar>::Vectorizable> struct vectorization_logic { enum { PacketSize = internal::packet_traits<Scalar>::size }; static void run() { typedef Matrix<Scalar,PacketSize,1> Vector1; typedef Matrix<Scalar,Dynamic,1> VectorX; typedef Matrix<Scalar,Dynamic,Dynamic> MatrixXX; typedef Matrix<Scalar,PacketSize,PacketSize> Matrix11; typedef Matrix<Scalar,2*PacketSize,2*PacketSize> Matrix22; typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16> Matrix44; typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION> Matrix44u; typedef Matrix<Scalar,4*PacketSize,4*PacketSize,ColMajor> Matrix44c; typedef Matrix<Scalar,4*PacketSize,4*PacketSize,RowMajor> Matrix44r; typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : /*PacketSize==1 ?*/ 1) > Matrix1; typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : /*PacketSize==1 ?*/ 1), DontAlign|((Matrix1::Flags&RowMajorBit)?RowMajor:ColMajor)> Matrix1u; // this type is made such that it can only be vectorized when viewed as a linear 1D vector typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 6 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?2:3) : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 6 : PacketSize==4 ? 2 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?3:2) : /*PacketSize==1 ?*/ 3) > Matrix3; #if !EIGEN_GCC_AND_ARCH_DOESNT_WANT_STACK_ALIGNMENT VERIFY(test_assign(Vector1(),Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1()+Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().template cast<Scalar>(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1()+Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44(),Matrix44()+Matrix44(), InnerVectorizedTraversal,InnerUnrolling)); VERIFY(test_assign(Matrix44u(),Matrix44()+Matrix44(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix1u(),Matrix1()+Matrix1(), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44c().col(1),Matrix44c().col(2)+Matrix44c().col(3), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44r().row(2),Matrix44r().row(1)+Matrix44r().row(1), InnerVectorizedTraversal,CompleteUnrolling)); if(PacketSize>1) { typedef Matrix<Scalar,3,3,ColMajor> Matrix33c; VERIFY(test_assign(Matrix33c().row(2),Matrix33c().row(1)+Matrix33c().row(1), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix33c().col(0),Matrix33c().col(1)+Matrix33c().col(1), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix3(),Matrix3().cwiseQuotient(Matrix3()), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<Scalar,17,17>(),Matrix<Scalar,17,17>()+Matrix<Scalar,17,17>(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix11(),Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(2,3)+Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(8,4), DefaultTraversal,PacketSize>4?InnerUnrolling:CompleteUnrolling)); } VERIFY(test_redux(Matrix3(), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44(), LinearVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(Matrix44().template block<(Matrix1::Flags&RowMajorBit)?4:PacketSize,(Matrix1::Flags&RowMajorBit)?PacketSize:4>(1,2), DefaultTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44c().template block<2*PacketSize,1>(1,2), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44r().template block<1,2*PacketSize>(2,1), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY((test_assign< Map<Matrix22, Aligned, OuterStride<3*PacketSize> >, Matrix22 >(InnerVectorizedTraversal,CompleteUnrolling))); VERIFY((test_assign< Map<Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>, Aligned, InnerStride<3*PacketSize> >, Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)> >(DefaultTraversal,CompleteUnrolling))); VERIFY((test_assign(Matrix11(), Matrix<Scalar,PacketSize,EIGEN_PLAIN_ENUM_MIN(2,PacketSize)>()*Matrix<Scalar,EIGEN_PLAIN_ENUM_MIN(2,PacketSize),PacketSize>(), PacketSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD?DefaultTraversal:InnerVectorizedTraversal, CompleteUnrolling))); #endif VERIFY(test_assign(MatrixXX(10,10),MatrixXX(20,20).block(10,10,2,3), SliceVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(VectorX(10), LinearVectorizedTraversal,NoUnrolling)); } }; template<typename Scalar> struct vectorization_logic<Scalar,false> { static void run() {} }; void test_vectorization_logic() { #ifdef EIGEN_VECTORIZE CALL_SUBTEST( vectorization_logic<float>::run() ); CALL_SUBTEST( vectorization_logic<double>::run() ); CALL_SUBTEST( vectorization_logic<std::complex<float> >::run() ); CALL_SUBTEST( vectorization_logic<std::complex<double> >::run() ); if(internal::packet_traits<float>::Vectorizable) { VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,5,2>(), DefaultTraversal,CompleteUnrolling)); } if(internal::packet_traits<double>::Vectorizable) { VERIFY(test_assign(Matrix<double,3,3>(),Matrix<double,3,3>()+Matrix<double,3,3>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<double,7,3>(), DefaultTraversal,CompleteUnrolling)); } #endif // EIGEN_VECTORIZE } <commit_msg>Test vectorization logic for int<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // 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/. #define EIGEN_DEBUG_ASSIGN #include "main.h" #include <typeinfo> std::string demangle_traversal(int t) { if(t==DefaultTraversal) return "DefaultTraversal"; if(t==LinearTraversal) return "LinearTraversal"; if(t==InnerVectorizedTraversal) return "InnerVectorizedTraversal"; if(t==LinearVectorizedTraversal) return "LinearVectorizedTraversal"; if(t==SliceVectorizedTraversal) return "SliceVectorizedTraversal"; return "?"; } std::string demangle_unrolling(int t) { if(t==NoUnrolling) return "NoUnrolling"; if(t==InnerUnrolling) return "InnerUnrolling"; if(t==CompleteUnrolling) return "CompleteUnrolling"; return "?"; } template<typename Dst, typename Src> bool test_assign(const Dst&, const Src&, int traversal, int unrolling) { internal::assign_traits<Dst,Src>::debug(); bool res = internal::assign_traits<Dst,Src>::Traversal==traversal && internal::assign_traits<Dst,Src>::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << "\n"; } return res; } template<typename Dst, typename Src> bool test_assign(int traversal, int unrolling) { internal::assign_traits<Dst,Src>::debug(); bool res = internal::assign_traits<Dst,Src>::Traversal==traversal && internal::assign_traits<Dst,Src>::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(internal::assign_traits<Dst,Src>::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(internal::assign_traits<Dst,Src>::Unrolling) << "\n"; } return res; } template<typename Xpr> bool test_redux(const Xpr&, int traversal, int unrolling) { typedef internal::redux_traits<internal::scalar_sum_op<typename Xpr::Scalar>,Xpr> traits; bool res = traits::Traversal==traversal && traits::Unrolling==unrolling; if(!res) { std::cerr << " Expected Traversal == " << demangle_traversal(traversal) << " got " << demangle_traversal(traits::Traversal) << "\n"; std::cerr << " Expected Unrolling == " << demangle_unrolling(unrolling) << " got " << demangle_unrolling(traits::Unrolling) << "\n"; } return res; } template<typename Scalar, bool Enable = internal::packet_traits<Scalar>::Vectorizable> struct vectorization_logic { typedef internal::packet_traits<Scalar> PacketTraits; enum { PacketSize = PacketTraits::size }; static void run() { typedef Matrix<Scalar,PacketSize,1> Vector1; typedef Matrix<Scalar,Dynamic,1> VectorX; typedef Matrix<Scalar,Dynamic,Dynamic> MatrixXX; typedef Matrix<Scalar,PacketSize,PacketSize> Matrix11; typedef Matrix<Scalar,2*PacketSize,2*PacketSize> Matrix22; typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16> Matrix44; typedef Matrix<Scalar,(Matrix11::Flags&RowMajorBit)?16:4*PacketSize,(Matrix11::Flags&RowMajorBit)?4*PacketSize:16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION> Matrix44u; typedef Matrix<Scalar,4*PacketSize,4*PacketSize,ColMajor> Matrix44c; typedef Matrix<Scalar,4*PacketSize,4*PacketSize,RowMajor> Matrix44r; typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : /*PacketSize==1 ?*/ 1) > Matrix1; typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 2 : PacketSize==2 ? 1 : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 2 : PacketSize==4 ? 2 : PacketSize==2 ? 2 : /*PacketSize==1 ?*/ 1), DontAlign|((Matrix1::Flags&RowMajorBit)?RowMajor:ColMajor)> Matrix1u; // this type is made such that it can only be vectorized when viewed as a linear 1D vector typedef Matrix<Scalar, (PacketSize==8 ? 4 : PacketSize==4 ? 6 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?2:3) : /*PacketSize==1 ?*/ 1), (PacketSize==8 ? 6 : PacketSize==4 ? 2 : PacketSize==2 ? ((Matrix11::Flags&RowMajorBit)?3:2) : /*PacketSize==1 ?*/ 3) > Matrix3; #if !EIGEN_GCC_AND_ARCH_DOESNT_WANT_STACK_ALIGNMENT VERIFY(test_assign(Vector1(),Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1()+Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().template cast<Scalar>(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1()+Vector1(), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Vector1(),Vector1().cwiseProduct(Vector1()), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44(),Matrix44()+Matrix44(), InnerVectorizedTraversal,InnerUnrolling)); VERIFY(test_assign(Matrix44u(),Matrix44()+Matrix44(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix1u(),Matrix1()+Matrix1(), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44c().col(1),Matrix44c().col(2)+Matrix44c().col(3), InnerVectorizedTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix44r().row(2),Matrix44r().row(1)+Matrix44r().row(1), InnerVectorizedTraversal,CompleteUnrolling)); if(PacketSize>1) { typedef Matrix<Scalar,3,3,ColMajor> Matrix33c; VERIFY(test_assign(Matrix33c().row(2),Matrix33c().row(1)+Matrix33c().row(1), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix33c().col(0),Matrix33c().col(1)+Matrix33c().col(1), LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix3(),Matrix3().cwiseQuotient(Matrix3()), PacketTraits::HasDiv ? LinearVectorizedTraversal : LinearTraversal,CompleteUnrolling)); VERIFY(test_assign(Matrix<Scalar,17,17>(),Matrix<Scalar,17,17>()+Matrix<Scalar,17,17>(), LinearTraversal,NoUnrolling)); VERIFY(test_assign(Matrix11(),Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(2,3)+Matrix<Scalar,17,17>().template block<PacketSize,PacketSize>(8,4), DefaultTraversal,PacketSize>4?InnerUnrolling:CompleteUnrolling)); } VERIFY(test_redux(Matrix3(), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44(), LinearVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(Matrix44().template block<(Matrix1::Flags&RowMajorBit)?4:PacketSize,(Matrix1::Flags&RowMajorBit)?PacketSize:4>(1,2), DefaultTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44c().template block<2*PacketSize,1>(1,2), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix44r().template block<1,2*PacketSize>(2,1), LinearVectorizedTraversal,CompleteUnrolling)); VERIFY((test_assign< Map<Matrix22, Aligned, OuterStride<3*PacketSize> >, Matrix22 >(InnerVectorizedTraversal,CompleteUnrolling))); VERIFY((test_assign< Map<Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)>, Aligned, InnerStride<3*PacketSize> >, Matrix<Scalar,EIGEN_PLAIN_ENUM_MAX(2,PacketSize),EIGEN_PLAIN_ENUM_MAX(2,PacketSize)> >(DefaultTraversal,CompleteUnrolling))); VERIFY((test_assign(Matrix11(), Matrix<Scalar,PacketSize,EIGEN_PLAIN_ENUM_MIN(2,PacketSize)>()*Matrix<Scalar,EIGEN_PLAIN_ENUM_MIN(2,PacketSize),PacketSize>(), PacketSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD?DefaultTraversal:InnerVectorizedTraversal, CompleteUnrolling))); #endif VERIFY(test_assign(MatrixXX(10,10),MatrixXX(20,20).block(10,10,2,3), SliceVectorizedTraversal,NoUnrolling)); VERIFY(test_redux(VectorX(10), LinearVectorizedTraversal,NoUnrolling)); } }; template<typename Scalar> struct vectorization_logic<Scalar,false> { static void run() {} }; void test_vectorization_logic() { #ifdef EIGEN_VECTORIZE CALL_SUBTEST( vectorization_logic<int>::run() ); CALL_SUBTEST( vectorization_logic<float>::run() ); CALL_SUBTEST( vectorization_logic<double>::run() ); CALL_SUBTEST( vectorization_logic<std::complex<float> >::run() ); CALL_SUBTEST( vectorization_logic<std::complex<double> >::run() ); if(internal::packet_traits<float>::Vectorizable) { VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,5,2>(), DefaultTraversal,CompleteUnrolling)); } if(internal::packet_traits<double>::Vectorizable) { VERIFY(test_assign(Matrix<double,3,3>(),Matrix<double,3,3>()+Matrix<double,3,3>(), LinearTraversal,CompleteUnrolling)); VERIFY(test_redux(Matrix<double,7,3>(), DefaultTraversal,CompleteUnrolling)); } #endif // EIGEN_VECTORIZE } <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:30:41 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after><|endoftext|>
<commit_before>#include "mitkPropertyList.h" #include <fstream> int mitkPropertyListTest(int argc, char* argv[]) { mitk::PropertyList::Pointer propList; std::cout << "Testing New(): "; propList = mitk::PropertyList::New(); if (propList.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>extended test<commit_after>#include "mitkPropertyList.h" #include "mitkProperties.h" #include <fstream> int mitkPropertyListTest(int argc, char* argv[]) { mitk::PropertyList::Pointer propList; std::cout << "Testing mitk::PropertyList::New(): "; propList = mitk::PropertyList::New(); if (propList.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; mitk::BoolProperty::Pointer boolProp = new mitk::BoolProperty(false); std::cout << "Testing SetProperty(): "; bool propChanged = propList->SetProperty("test",boolProp); if (!propChanged) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } boolProp->SetValue(true); propChanged = propList->SetProperty("test",boolProp); if (!propChanged) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } propChanged = propList->SetProperty("test",boolProp); if (propChanged) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * opencog/spatial/3DSpaceMap/Pathfinder3D.cc * * Copyright (C) 2002-2011 OpenCog Foundation * All Rights Reserved * Author(s): Shujing Ke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Pathfinder3D.h" #include <set> #include <map> #include <iterator> using namespace opencog; using namespace opencog::spatial; bool Pathfinder3D::AStar3DPathFinder(Octree3DMapManager *mapManager, const BlockVector& begin, const BlockVector& target, vector<BlockVector>& path, BlockVector& nearestPos, BlockVector& bestPos, bool getNearestPos, bool getBestPos) { BlockVector end = target; map<BlockVector,double> costMap; map<BlockVector,double>::const_iterator itercost; int searchTimes = 0; float nearestDis = begin - target; float bestHeuristic = nearestDis * 1.41421356f; nearestPos = begin; bestPos = begin; bool nostandable = false; // check if the begin and target pos standable first if ((! mapManager->checkStandable(begin)) || (! mapManager->checkStandable(target))) { nostandable = true; if ((! getNearestPos) && (! getBestPos)) return false; } while(true) { set<BlockVector> searchedList; set<BlockVector>::const_iterator iter; BlockVector curPos; vector<BlockVector> currentPath; currentPath.push_back(begin); searchedList.insert(begin); int pathfindingSteps = 0; bool is_found = false; searchTimes ++; while(currentPath.size() != 0) { // successfully achieve the target if (currentPath.back() == end) { is_found = true; break; } // Calculate 24 neighbour cost and then pick the lowest one. double lowestCost = 999999.99; BlockVector lowestCostPos; double curCost; for (int i = -1; i < 2; i ++) { for (int j = -1; j < 2; j ++) { for (int k = -1; k < 2; k ++) { // Will not calculate the pos just above or below or equal to the begin position. if ( (i == 0) && (j == 0)) continue; curPos.x = currentPath.back().x + i; curPos.y = currentPath.back().y + j; curPos.z = currentPath.back().z + k; iter = searchedList.find(curPos); if (iter != searchedList.end()) { // already searched! continue; } // check if standable if (! mapManager->checkStandable(curPos)) { searchedList.insert(curPos); continue; } if ( ! checkNeighbourAccessable(mapManager,currentPath.back() , i, j, k)) continue; double costFromLastStep = 0.0; if (k == 1) // this pos is higher than last pos, have to cost more to jump up costFromLastStep = 0.2; else if (k == -1) // this pos is lower than last pos, have to cost more to jump down costFromLastStep = 0.1; itercost = costMap.find(curPos); if (itercost != costMap.end()) { if ((double)(itercost->second) + costFromLastStep < lowestCost) { lowestCost = (double)(itercost->second) + costFromLastStep; lowestCostPos = curPos; } } // calculate the cost of this pos curCost = calculateCostByDistance(begin, end, curPos,nearestDis,nearestPos,bestHeuristic,bestPos); pathfindingSteps++; costMap.insert(pair<BlockVector, int>(curPos,curCost)); if (curCost + costFromLastStep < lowestCost) { lowestCost = curCost +costFromLastStep; lowestCostPos = curPos; } } } } // if the lowestCost still == 99999.99, it shows that all the neighbours have been searched and failed, // so we should return to last step if (lowestCost > 999999.0) { currentPath.pop_back(); } else { // add the lowestcost neighbour pos to the currentPath currentPath.push_back(lowestCostPos); searchedList.insert(lowestCostPos); } } if (! is_found) return false; if ((currentPath.size() < 21) || (searchTimes > 4)) { path.insert(path.begin(), currentPath.begin(), currentPath.end()); if (nostandable) return false; else return true; } // find the farthest pos in this currrentPath from the end position vector<BlockVector>::iterator disIter, farPosIter; double farthestDis = 0.0; for(disIter = currentPath.begin(); disIter != currentPath.end(); ++ disIter) { double dis = (end - *disIter) + (begin - *disIter); if ( dis > farthestDis) { farPosIter = disIter; farthestDis = dis; } } path.insert(path.begin(), farPosIter, currentPath.end()); // The shortest way found! if (farPosIter == currentPath.begin()) { if (nostandable) return false; else return true; } end = *(--farPosIter); } } double Pathfinder3D::calculateCostByDistance(const BlockVector& begin, const BlockVector& target, const BlockVector& pos, float& nearestDis,BlockVector& nearestPos, float& bestHeuristic, BlockVector& bestPos) { float dis = target - pos; if (dis < nearestDis) { nearestDis = dis; nearestPos = pos; } float heuristic = dis*1.41421356f + (begin - pos); if (heuristic < bestHeuristic ) { bestHeuristic = heuristic; bestPos = pos; } return dis; } // before call this funciton, please make sure the pos want to access is standable first bool Pathfinder3D::checkNeighbourAccessable(Octree3DMapManager *mapManager, BlockVector& lastPos, int i, int j, int k) { // if want to access the pos 1 unit lower than last pos if (k == -1) { for (int h = 1; h <= mapManager->getAgentHeight(); h++) { if (i != 0) { BlockVector neighbour1(lastPos.x + i,lastPos.y,lastPos.z + h); if (mapManager->checkIsSolid(neighbour1)) return false; } if (j != 0) { BlockVector neighbour2(lastPos.x,lastPos.y + j,lastPos.z + h); if (mapManager->checkIsSolid(neighbour2)) return false; } if ( (i != 0) && (j != 0)) { BlockVector neighbour3(lastPos.x + i,lastPos.y + j,lastPos.z + h); if (mapManager->checkIsSolid(neighbour3)) return false; } } return true; } // when the pos has the same z with the the last pos // or if want to access the pos 1 unit higher than the last pos // check if there are 2 blocks in the 45 degree directions block the way // e.g.: the B are blocks, one cannot access C,E,F,G from L // CBE // BLB // FBG if ((i != 0) && (j != 0) ) // k == 0 or k == 1 { // all the blocks in the two neighbour 45 direction inside the agentHeight will block the way for (int h = 0; h < mapManager->getAgentHeight(); h++) { BlockVector neighbour1(lastPos.x + i,lastPos.y,lastPos.z + h + k ); if (mapManager->checkIsSolid(neighbour1)) return false; BlockVector neighbour2(lastPos.x,lastPos.y + j,lastPos.z + h + k ); if (mapManager->checkIsSolid(neighbour2)) return false; } return true; } return true; } <commit_msg>Fixed a bug in pathfinder about checkNeighbourAccessable<commit_after>/* * opencog/spatial/3DSpaceMap/Pathfinder3D.cc * * Copyright (C) 2002-2011 OpenCog Foundation * All Rights Reserved * Author(s): Shujing Ke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Pathfinder3D.h" #include <set> #include <map> #include <iterator> using namespace opencog; using namespace opencog::spatial; bool Pathfinder3D::AStar3DPathFinder(Octree3DMapManager *mapManager, const BlockVector& begin, const BlockVector& target, vector<BlockVector>& path, BlockVector& nearestPos, BlockVector& bestPos, bool getNearestPos, bool getBestPos) { BlockVector end = target; map<BlockVector,double> costMap; map<BlockVector,double>::const_iterator itercost; int searchTimes = 0; float nearestDis = begin - target; float bestHeuristic = nearestDis * 1.41421356f; nearestPos = begin; bestPos = begin; bool nostandable = false; // check if the begin and target pos standable first if ((! mapManager->checkStandable(begin)) || (! mapManager->checkStandable(target))) { nostandable = true; if ((! getNearestPos) && (! getBestPos)) return false; } while(true) { set<BlockVector> searchedList; set<BlockVector>::const_iterator iter; BlockVector curPos; vector<BlockVector> currentPath; currentPath.push_back(begin); searchedList.insert(begin); int pathfindingSteps = 0; bool is_found = false; searchTimes ++; while(currentPath.size() != 0) { // successfully achieve the target if (currentPath.back() == end) { is_found = true; break; } // Calculate 24 neighbour cost and then pick the lowest one. double lowestCost = 999999.99; BlockVector lowestCostPos; double curCost; for (int i = -1; i < 2; i ++) { for (int j = -1; j < 2; j ++) { for (int k = -1; k < 2; k ++) { // Will not calculate the pos just above or below or equal to the begin position. if ( (i == 0) && (j == 0)) continue; curPos.x = currentPath.back().x + i; curPos.y = currentPath.back().y + j; curPos.z = currentPath.back().z + k; iter = searchedList.find(curPos); if (iter != searchedList.end()) { // already searched! continue; } // check if standable if (! mapManager->checkStandable(curPos)) { searchedList.insert(curPos); continue; } if ( ! checkNeighbourAccessable(mapManager,currentPath.back() , i, j, k)) continue; double costFromLastStep = 0.0; if (k == 1) // this pos is higher than last pos, have to cost more to jump up costFromLastStep = 0.2; else if (k == -1) // this pos is lower than last pos, have to cost more to jump down costFromLastStep = 0.1; itercost = costMap.find(curPos); if (itercost != costMap.end()) { if ((double)(itercost->second) + costFromLastStep < lowestCost) { lowestCost = (double)(itercost->second) + costFromLastStep; lowestCostPos = curPos; } } // calculate the cost of this pos curCost = calculateCostByDistance(begin, end, curPos,nearestDis,nearestPos,bestHeuristic,bestPos); pathfindingSteps++; costMap.insert(pair<BlockVector, int>(curPos,curCost)); if (curCost + costFromLastStep < lowestCost) { lowestCost = curCost +costFromLastStep; lowestCostPos = curPos; } } } } // if the lowestCost still == 99999.99, it shows that all the neighbours have been searched and failed, // so we should return to last step if (lowestCost > 999999.0) { currentPath.pop_back(); } else { // add the lowestcost neighbour pos to the currentPath currentPath.push_back(lowestCostPos); searchedList.insert(lowestCostPos); } } if (! is_found) return false; if ((currentPath.size() < 21) || (searchTimes > 4)) { path.insert(path.begin(), currentPath.begin(), currentPath.end()); if (nostandable) return false; else return true; } // find the farthest pos in this currrentPath from the end position vector<BlockVector>::iterator disIter, farPosIter; double farthestDis = 0.0; for(disIter = currentPath.begin(); disIter != currentPath.end(); ++ disIter) { double dis = (end - *disIter) + (begin - *disIter); if ( dis > farthestDis) { farPosIter = disIter; farthestDis = dis; } } path.insert(path.begin(), farPosIter, currentPath.end()); // The shortest way found! if (farPosIter == currentPath.begin()) { if (nostandable) return false; else return true; } end = *(--farPosIter); } } double Pathfinder3D::calculateCostByDistance(const BlockVector& begin, const BlockVector& target, const BlockVector& pos, float& nearestDis,BlockVector& nearestPos, float& bestHeuristic, BlockVector& bestPos) { float dis = target - pos; if (dis < nearestDis) { nearestDis = dis; nearestPos = pos; } float heuristic = dis*1.41421356f + (begin - pos); if (heuristic < bestHeuristic ) { bestHeuristic = heuristic; bestPos = pos; } return dis; } // before call this funciton, please make sure the pos want to access is standable first bool Pathfinder3D::checkNeighbourAccessable(Octree3DMapManager *mapManager, BlockVector& lastPos, int i, int j, int k) { // if want to access the pos 1 unit lower than last pos if (k == -1) { for (int h = 1; h <= mapManager->getAgentHeight(); h++) { if (i != 0) { BlockVector neighbour1(lastPos.x + i,lastPos.y,lastPos.z + h); if (mapManager->checkIsSolid(neighbour1)) return false; } if (j != 0) { BlockVector neighbour2(lastPos.x,lastPos.y + j,lastPos.z + h); if (mapManager->checkIsSolid(neighbour2)) return false; } if ( (i != 0) && (j != 0)) { BlockVector neighbour3(lastPos.x + i,lastPos.y + j,lastPos.z + h); if (mapManager->checkIsSolid(neighbour3)) return false; } } return true; } // when the pos has the same z with the the last pos // or if want to access the pos 1 unit higher than the last pos // check if there are 2 blocks in the 45 degree directions block the way // e.g.: the B are blocks, one cannot access C,E,F,G from L // CBE // BLB // FBG if (k == 1) // if want to access higer position { if (mapManager->checkIsSolid(lastPos.x,lastPos.y,lastPos.z + 1)) // if the block on top is solid return false; } if ((i != 0) && (j != 0) ) // k == 0 or k == 1 { // all the blocks in the two neighbour 45 direction inside the agentHeight will block the way for (int h = 0; h < mapManager->getAgentHeight(); h++) { BlockVector neighbour1(lastPos.x + i,lastPos.y,lastPos.z + h + k ); if (mapManager->checkIsSolid(neighbour1)) return false; BlockVector neighbour2(lastPos.x,lastPos.y + j,lastPos.z + h + k ); if (mapManager->checkIsSolid(neighbour2)) return false; } return true; } return true; } <|endoftext|>
<commit_before>#ifndef GUARD_database_transaction_hpp #define GUARD_database_transaction_hpp #include "database_connection.hpp" #include <boost/noncopyable.hpp> namespace sqloxx { /** * Class for managing database transactions using RAII. * An instance of DatabaseTransaction, when created, causes * an SQL transaction to commenced on the DatabaseConnection with * which it is initialized. The SQL transaction can then * be finalized in one of three ways:\n * (a) We call the DatabaseTransaction's commit() method, causing * the transaction to be committed; * (b) We call the DatabaseTransaction's cancel() method, causing * the tranaction to be cancelled i.e. rolled back, or * (c) The DatabaseTransaction is destruced without commit() or * cancel() having been called - in which case the SQL transaction * is cancelled i.e. rolled back. * * (c) is intended as a balwark against programmer error, rather * than a way to avoid calling cancel() manually. See further * documentation of each for why. * * @todo Documentation and testing. */ class DatabaseTransaction: public boost::noncopyable { public: explicit DatabaseTransaction(DatabaseConnection& p_database_connection); ~DatabaseTransaction(); void commit(); void cancel(); private: bool m_is_active; DatabaseConnection& m_database_connection; }; // DatabaseTransaction } // sqloxx #endif // GUARD_database_transaction_hpp <commit_msg>Corrected minor typo in comment.<commit_after>#ifndef GUARD_database_transaction_hpp #define GUARD_database_transaction_hpp #include "database_connection.hpp" #include <boost/noncopyable.hpp> namespace sqloxx { /** * Class for managing database transactions using RAII. * An instance of DatabaseTransaction, when created, causes * an SQL transaction to be commenced on the DatabaseConnection with * which it is initialized. The SQL transaction can then * be finalized in one of three ways:\n * (a) We call the DatabaseTransaction's commit() method, causing * the transaction to be committed; * (b) We call the DatabaseTransaction's cancel() method, causing * the tranaction to be cancelled i.e. rolled back, or * (c) The DatabaseTransaction is destruced without commit() or * cancel() having been called - in which case the SQL transaction * is cancelled i.e. rolled back. * * (c) is intended as a balwark against programmer error, rather * than a way to avoid calling cancel() manually. See further * documentation of each for why. * * @todo Documentation and testing. */ class DatabaseTransaction: public boost::noncopyable { public: explicit DatabaseTransaction(DatabaseConnection& p_database_connection); ~DatabaseTransaction(); void commit(); void cancel(); private: bool m_is_active; DatabaseConnection& m_database_connection; }; // DatabaseTransaction } // sqloxx #endif // GUARD_database_transaction_hpp <|endoftext|>
<commit_before>/* * Application.cpp * * Created on: 30 avr. 2017 * Author: JulienCombattelli */ #include "Application/Application.h" #include "Application/Events.h" #include <exception> #include <initializer_list> Application::Application() : m_is_running(true) { add_event_handler<Moving_Button_Pressed>(&Application::send_direction_command, this); add_event_handler<Tilt_Change>(&Application::send_tilt_command, this); add_event_handler<Spreading_Change>(&Application::send_spreading_command, this); } Application::~Application() { std::cout << "Closing application" << std::endl; } void Application::run(int period_ms) { m_socket.connect("B8:27:EB:7C:3D:9D", 1); std::cout << "Connected on B8:27:EB:7C:3D:9D" << std::endl; while(m_is_running) { if(m_timer.time_elapsed_ms() > period_ms) { m_timer.restart(); try { m_window_manager.update(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; stop(); } } } } void Application::stop() { m_is_running = false; } void Application::send_direction_command(Sender& s, const Event& e) { bt::Packet packet; packet.append(std::vector<char>{0x01, 0x02, 0x03, 0x04}); m_socket.send(packet); } void Application::send_tilt_command(Sender& s, const Event& e) { bt::Packet packet; packet.append(std::vector<char>{0x01, 0x02, 0x03, 0x04}); m_socket.send(packet); } void Application::send_spreading_command(Sender& s, const Event& e) { bt::Packet packet; packet.append(std::vector<char>{0x01, 0x02, 0x03, 0x04}); m_socket.send(packet); } <commit_msg>creat packet for bt<commit_after>/* * Application.cpp * * Created on: 30 avr. 2017 * Author: JulienCombattelli */ #include "Application/Application.h" #include "Application/Events.h" #include <exception> #include <initializer_list> Application::Application() : m_is_running(true) { add_event_handler<Moving_Button_Pressed>(&Application::send_direction_command, this); add_event_handler<Tilt_Change>(&Application::send_tilt_command, this); add_event_handler<Spreading_Change>(&Application::send_spreading_command, this); } Application::~Application() { std::cout << "Closing application" << std::endl; } void Application::run(int period_ms) { m_socket.connect("B8:27:EB:7C:3D:9D", 1); std::cout << "Connected on B8:27:EB:7C:3D:9D" << std::endl; while(m_is_running) { if(m_timer.time_elapsed_ms() > period_ms) { m_timer.restart(); try { m_window_manager.update(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; stop(); } } } } void Application::stop() { m_is_running = false; } void Application::send_direction_command(Sender& s, const Event& e) { bt::Packet packet; switch(((Moving_Button_Pressed)e).m_dir) { case Moving_Button_Pressed::front : packet.append(std::vector<char>{0x01, 0x01}); break; case Moving_Button_Pressed::back : packet.append(std::vector<char>{0x01, 0x02}); break; case Moving_Button_Pressed::left : packet.append(std::vector<char>{0x01, 0x03}); break; case Moving_Button_Pressed::right : packet.append(std::vector<char>{0x01, 0x04}); break; default : packet.append(std::vector<char>{0x01, 0x00}); break; } m_socket.send(packet); } void Application::send_tilt_command(Sender& s, const Event& e) { bt::Packet packet; int8_t pitch = ((Tilt_Change)e).m_x; if(pitch > 100) pitch = 100; else if(pitch < -100) pitch = -100; int8_t roll = ((Tilt_Change)e).m_y; if(roll > 100) roll = 100; else if(roll < -100) roll = -100; packet.append(std::vector<char>{0x02, pitch, roll}); m_socket.send(packet); } void Application::send_spreading_command(Sender& s, const Event& e) { bt::Packet packet; uint8_t heigth = ((Spreading_Change)e).m_heigth; heigth = heigth*255; uint8_t spread = ((Spreading_Change)e).m_spread; spread = spread*255; packet.append(std::vector<char>{0x02, spread, heigth}); m_socket.send(packet); } <|endoftext|>
<commit_before>#include "server.hpp" #include "AppLogger.hpp" #include "ServerSettings.hpp" #include "SystemMeasurement.hpp" #include "SimpleHttpServer.hpp" #include "DBBackEnd.hpp" #include "SMTPAgent.hpp" #include <QCoreApplication> #include <QSettings> #include <QFileInfo> #include <QDir> #include <QBuffer> #include <QDebug> #include <algorithm> using namespace crossOver::server; using namespace crossOver::common; using namespace std; namespace { /// @brief Functor to sort containers of @c ClientConfiguration elements /// by their @c key field. struct RealmLessThanOnClientConfiguration // clang-format off { bool operator()(const ClientConfiguration &lh, const ClientConfiguration &rh) const noexcept { return lh.key < rh.key; } }; // clang-format on /// @brief It generates the list of messages when a system measurement @p sm /// exceds the configuration @p cc. QStringList generateAlertMessages (const ClientConfiguration &cc, const SystemMeasurement &sm) { QStringList alertMessages; if (sm.cpuLoad > cc.alerts.cpuLimit) alertMessages << QString ("CPU alert: Current load is %1 %%, threshold = %2 %%)") .arg (sm.cpuLoad) .arg (cc.alerts.cpuLimit); const double freeRamPerc = (sm.freeRam * 100.0) / sm.totalRam; if (freeRamPerc < cc.alerts.memoryLimit) alertMessages << QString ("Free memory alert: Current free memory is %1 " "%% (%2), threshold = %3 %%)") .arg (freeRamPerc) .arg (sm.freeRam) .arg (cc.alerts.memoryLimit); if (sm.numProcs > cc.alerts.processesLimit) alertMessages << QString ("Number of running processes alert: Current " "number of running processes is %1, threshold " "= %2") .arg (sm.numProcs) .arg (cc.alerts.processesLimit); return alertMessages; } } Server::Server (QObject *parent) : QObject (parent) { setupDBEngine(); setupClientsAuthAndAlarms (); setupTcpServer (); } void Server::setupDBEngine () { qDebug() << ServerLog::header() << "Initializing database engine"; m_dbBackEnd = new DBBackEnd (this); } void Server::setupClientsAuthAndAlarms () { qDebug() << ServerLog::header() << "Loading clients and alarms"; // Load Alarms and client conf QFileInfo xmlCCPath (QDir (QCoreApplication::applicationDirPath ()), "clientDefaultConf.xml"); m_clientsConf = loadClientConfFromXml (xmlCCPath.absoluteFilePath ()); sort (begin (m_clientsConf), end (m_clientsConf), RealmLessThanOnClientConfiguration ()); QSettings settings; const int clientCachedSize = settings.value (ServerSettings::clientCacheSize(), 200).toInt (); m_realm2ClientIdCache.setMaxCost (clientCachedSize); // Settup SMTP agent const QString smtpServer = settings.value( ServerSettings::smtpServer(), "smtp://smtp.gmail.com:587").toString(); const QString smtpUser = settings.value( ServerSettings::smtpUser(), "[email protected]").toString(); const QString smtpPass = settings.value( ServerSettings::smtpPassword(), "oCaQNY8vJvqAdHOi8W5n4Q").toString(); m_SMTPAgent = new SMTPAgent ( smtpServer, this); m_SMTPAgent->setUser( smtpUser); m_SMTPAgent->setPassword( smtpPass); } void Server::setupTcpServer () { qDebug() << ServerLog::header() << "Opening HTTP port and authorization keys"; m_httpServer = new SimpleHttpServer (this); connect (m_httpServer, &SimpleHttpServer::payLoadReady, this, &Server::processStatistics); for (const auto &cc : m_clientsConf) m_httpServer->addBasicAuthentication (cc.key); } void Server::processStatistics (QString realm, QByteArray data) { SystemMeasurement sm; // 1. Deserialize stats from HTTP payload QBuffer buffer (&data); buffer.open (QIODevice::ReadOnly); sm.deserializeFrom (&buffer); qDebug () << ServerLog::header() << "Cpu: " << sm.cpuLoad << " Free Ram: " << sm.freeRam << " Procs: " << sm.numProcs; const QString email = findClientMail (realm); // 2. Save stats into DB. m_dbBackEnd->addStatsToClient (realm, email, sm); // 3. Check alarms and send email. checkAlertForClient (realm, email, sm); } QString Server::findClientMail (const QString &realm) const { QString email; const ClientConfiguration ccFindKey (realm); const auto itrRange = equal_range (begin (m_clientsConf), end (m_clientsConf), ccFindKey, RealmLessThanOnClientConfiguration ()); if (itrRange.first != itrRange.second) email = itrRange.first->mail; return email; } void Server::checkAlertForClient (QString realm, QString findClientMail, SystemMeasurement sm) { const ClientConfiguration ccFindKey (realm); const auto itrRange = equal_range (begin (m_clientsConf), end (m_clientsConf), ccFindKey, RealmLessThanOnClientConfiguration ()); if (itrRange.first != itrRange.second) { const ClientConfiguration &cc = *itrRange.first; const QStringList alertMessages = generateAlertMessages (cc, sm); if (!alertMessages.empty ()) { QString emailBody; QTextStream eb(&emailBody); eb << "System has found the following alarms:" << endl; for (const QString& alert: alertMessages) eb << "\t" << alert << endl; m_SMTPAgent->send( m_SMTPAgent->user(), QStringList(cc.mail), QStringLiteral("[ALARMS] CrossOver Notification Deamon"), emailBody); } } } int main (int argc, char *argv[]) { // Configure app. QCoreApplication app (argc, argv); QCoreApplication::setOrganizationName ("CrossOver"); QCoreApplication::setApplicationName ("server"); QSettings::setPath (QSettings::NativeFormat, QSettings::SystemScope, QCoreApplication::applicationDirPath ()); // Settup logger AppLogger::initialize( QFileInfo( QDir(QCoreApplication::applicationDirPath()), "server.log")); // Create server instance Server *server = new Server (&app); Q_UNUSED (server); return app.exec (); } <commit_msg>Internal documentation for server class<commit_after>#include "server.hpp" #include "AppLogger.hpp" #include "ServerSettings.hpp" #include "SystemMeasurement.hpp" #include "SimpleHttpServer.hpp" #include "DBBackEnd.hpp" #include "SMTPAgent.hpp" #include <QCoreApplication> #include <QSettings> #include <QFileInfo> #include <QDir> #include <QBuffer> #include <QDebug> #include <algorithm> using namespace crossOver::server; using namespace crossOver::common; using namespace std; namespace { /// @brief Functor to sort containers of @c ClientConfiguration elements /// by their @c key field. struct RealmLessThanOnClientConfiguration // clang-format off { bool operator()(const ClientConfiguration &lh, const ClientConfiguration &rh) const noexcept { return lh.key < rh.key; } }; // clang-format on /// @brief It generates the list of messages when a system measurement @p sm /// exceds the configuration @p cc. QStringList generateAlertMessages (const ClientConfiguration &cc, const SystemMeasurement &sm) { QStringList alertMessages; if (sm.cpuLoad > cc.alerts.cpuLimit) alertMessages << QString ("CPU alert: Current load is %1 %%, threshold = %2 %%)") .arg (sm.cpuLoad) .arg (cc.alerts.cpuLimit); const double freeRamPerc = (sm.freeRam * 100.0) / sm.totalRam; if (freeRamPerc < cc.alerts.memoryLimit) alertMessages << QString ("Free memory alert: Current free memory is %1 " "%% (%2), threshold = %3 %%)") .arg (freeRamPerc) .arg (sm.freeRam) .arg (cc.alerts.memoryLimit); if (sm.numProcs > cc.alerts.processesLimit) alertMessages << QString ("Number of running processes alert: Current " "number of running processes is %1, threshold " "= %2") .arg (sm.numProcs) .arg (cc.alerts.processesLimit); return alertMessages; } } Server::Server (QObject *parent) : QObject (parent) { setupDBEngine(); setupClientsAuthAndAlarms (); setupTcpServer (); } void Server::setupDBEngine () { qDebug() << ServerLog::header() << "Initializing database engine"; m_dbBackEnd = new DBBackEnd (this); } void Server::setupClientsAuthAndAlarms () { qDebug() << ServerLog::header() << "Loading clients and alarms"; // Load Alarms and client conf QFileInfo xmlCCPath (QDir (QCoreApplication::applicationDirPath ()), "clientDefaultConf.xml"); m_clientsConf = loadClientConfFromXml (xmlCCPath.absoluteFilePath ()); sort (begin (m_clientsConf), end (m_clientsConf), RealmLessThanOnClientConfiguration ()); QSettings settings; const int clientCachedSize = settings.value (ServerSettings::clientCacheSize(), 200).toInt (); m_realm2ClientIdCache.setMaxCost (clientCachedSize); // Settup SMTP agent const QString smtpServer = settings.value( ServerSettings::smtpServer(), "smtp://smtp.gmail.com:587").toString(); const QString smtpUser = settings.value( ServerSettings::smtpUser(), "[email protected]").toString(); const QString smtpPass = settings.value( ServerSettings::smtpPassword(), "oCaQNY8vJvqAdHOi8W5n4Q").toString(); m_SMTPAgent = new SMTPAgent ( smtpServer, this); m_SMTPAgent->setUser( smtpUser); m_SMTPAgent->setPassword( smtpPass); } void Server::setupTcpServer () { qDebug() << ServerLog::header() << "Opening HTTP port and authorization keys"; m_httpServer = new SimpleHttpServer (this); connect (m_httpServer, &SimpleHttpServer::payLoadReady, this, &Server::processStatistics); for (const auto &cc : m_clientsConf) m_httpServer->addBasicAuthentication (cc.key); } void Server::processStatistics (QString realm, QByteArray data) { SystemMeasurement sm; // 1. Deserialize stats from HTTP payload QBuffer buffer (&data); buffer.open (QIODevice::ReadOnly); sm.deserializeFrom (&buffer); qDebug () << ServerLog::header() << "Cpu: " << sm.cpuLoad << " Free Ram: " << sm.freeRam << " Procs: " << sm.numProcs; const QString email = findClientMail (realm); // 2. Save stats into DB. m_dbBackEnd->addStatsToClient (realm, email, sm); // 3. Check alarms and send email. checkAlertForClient (realm, email, sm); } QString Server::findClientMail (const QString &realm) const { QString email; const ClientConfiguration ccFindKey (realm); const auto itrRange = equal_range (begin (m_clientsConf), end (m_clientsConf), ccFindKey, RealmLessThanOnClientConfiguration ()); if (itrRange.first != itrRange.second) email = itrRange.first->mail; return email; } void Server::checkAlertForClient (QString realm, QString findClientMail, SystemMeasurement sm) { const ClientConfiguration ccFindKey (realm); const auto itrRange = equal_range (begin (m_clientsConf), end (m_clientsConf), ccFindKey, RealmLessThanOnClientConfiguration ()); if (itrRange.first != itrRange.second) { const ClientConfiguration &cc = *itrRange.first; const QStringList alertMessages = generateAlertMessages (cc, sm); if (!alertMessages.empty ()) { QString emailBody; QTextStream eb(&emailBody); eb << "System has found the following alarms:" << endl; for (const QString& alert: alertMessages) eb << "\t" << alert << endl; m_SMTPAgent->send( m_SMTPAgent->user(), QStringList(cc.mail), QStringLiteral("[ALARMS] CrossOver Notification Deamon"), emailBody); } } } int main (int argc, char *argv[]) { // Configure app. QCoreApplication app (argc, argv); QCoreApplication::setOrganizationName ("CrossOver"); QCoreApplication::setApplicationName ("server"); QSettings::setPath (QSettings::NativeFormat, QSettings::SystemScope, QCoreApplication::applicationDirPath ()); // Settup logger AppLogger::initialize( QFileInfo( QDir(QCoreApplication::applicationDirPath()), "server.log")); // Create server instance Server *server = new Server (&app); Q_UNUSED (server); return app.exec (); } <|endoftext|>
<commit_before>#include <stdio.h> #include "RegViewVU.h" #include "../PS2VM.h" CRegViewVU::CRegViewVU(HWND hParent, const RECT& rect, CVirtualMachine& virtualMachine, CMIPS* pCtx) : CRegViewPage(hParent, rect) , m_pCtx(pCtx) { virtualMachine.OnMachineStateChange.connect(boost::bind(&CRegViewVU::Update, this)); virtualMachine.OnRunningStateChange.connect(boost::bind(&CRegViewVU::Update, this)); Update(); } CRegViewVU::~CRegViewVU() { } void CRegViewVU::Update() { SetDisplayText(GetDisplayText().c_str()); CRegViewPage::Update(); } std::string CRegViewVU::GetDisplayText() { char sLine[256]; std::string result; result += " x y \r\n"; result += " z w \r\n"; MIPSSTATE* pState = &m_pCtx->m_State; for(unsigned int i = 0; i < 32; i++) { char sReg1[32]; if(i < 10) { sprintf(sReg1, "VF%i ", i); } else { sprintf(sReg1, "VF%i ", i); } sprintf(sLine, "%s: %+.7e %+.7e\r\n %+.7e %+.7e\r\n", sReg1, \ *(float*)&pState->nCOP2[i].nV0, \ *(float*)&pState->nCOP2[i].nV1, \ *(float*)&pState->nCOP2[i].nV2, \ *(float*)&pState->nCOP2[i].nV3); result += sLine; } sprintf(sLine, "ACC : %+.7e %+.7e\r\n %+.7e %+.7e\r\n", \ *(float*)&pState->nCOP2A.nV0, \ *(float*)&pState->nCOP2A.nV1, \ *(float*)&pState->nCOP2A.nV2, \ *(float*)&pState->nCOP2A.nV3); result += sLine; sprintf(sLine, "Q : %+.7e\r\n", *(float*)&pState->nCOP2Q); result += sLine; sprintf(sLine, "I : %+.7e\r\n", *(float*)&pState->nCOP2I); result += sLine; sprintf(sLine, "P : %+.7e\r\n", *(float*)&pState->nCOP2P); result += sLine; sprintf(sLine, "R : %+.7e (0x%0.8X)\r\n", *(float*)&pState->nCOP2R, pState->nCOP2R); result += sLine; sprintf(sLine, "MACF : 0x%0.4X\r\n", pState->nCOP2MF); result += sLine; sprintf(sLine, "CLIP : 0x%0.6X\r\n", pState->nCOP2CF); result += sLine; sprintf(sLine, "PIPEQ: 0x%0.4X - %+.7e\r\n", pState->pipeQ.counter, *(float*)&pState->pipeQ.heldValue); result += sLine; unsigned int currentPipeMacCounter = pState->pipeMac.index - 1; uint32 macFlagPipeValues[MACFLAG_PIPELINE_SLOTS]; uint32 macFlagPipeTimes[MACFLAG_PIPELINE_SLOTS]; for(unsigned int i = 0; i < MACFLAG_PIPELINE_SLOTS; i++) { unsigned int currIndex = (currentPipeMacCounter - i) & (MACFLAG_PIPELINE_SLOTS - 1); macFlagPipeValues[i] = pState->pipeMac.values[currIndex]; macFlagPipeTimes[i] = pState->pipeMac.pipeTimes[currIndex]; } sprintf(sLine, "PIPEM: 0x%0.4X:0x%0.4X, 0x%0.4X:0x%0.4X\r\n", macFlagPipeTimes[0], macFlagPipeValues[0], macFlagPipeTimes[1], macFlagPipeValues[1]); result += sLine; sprintf(sLine, " 0x%0.4X:0x%0.4X, 0x%0.4X:0x%0.4X\r\n", macFlagPipeTimes[2], macFlagPipeValues[2], macFlagPipeTimes[3], macFlagPipeValues[3]); result += sLine; for(unsigned int i = 0; i < 16; i += 2) { char sReg1[32]; char sReg2[32]; if(i < 10) { sprintf(sReg1, "VI%i ", i); sprintf(sReg2, "VI%i ", i + 1); } else { sprintf(sReg1, "VI%i ", i); sprintf(sReg2, "VI%i ", i + 1); } sprintf(sLine, "%s: 0x%0.4X %s: 0x%0.4X\r\n", sReg1, pState->nCOP2VI[i] & 0xFFFF, sReg2, pState->nCOP2VI[i + 1] & 0xFFFF); result += sLine; } return result; } <commit_msg>Display VU pipe time in regview.<commit_after>#include <stdio.h> #include "RegViewVU.h" #include "../PS2VM.h" CRegViewVU::CRegViewVU(HWND hParent, const RECT& rect, CVirtualMachine& virtualMachine, CMIPS* pCtx) : CRegViewPage(hParent, rect) , m_pCtx(pCtx) { virtualMachine.OnMachineStateChange.connect(boost::bind(&CRegViewVU::Update, this)); virtualMachine.OnRunningStateChange.connect(boost::bind(&CRegViewVU::Update, this)); Update(); } CRegViewVU::~CRegViewVU() { } void CRegViewVU::Update() { SetDisplayText(GetDisplayText().c_str()); CRegViewPage::Update(); } std::string CRegViewVU::GetDisplayText() { char sLine[256]; std::string result; result += " x y \r\n"; result += " z w \r\n"; MIPSSTATE* pState = &m_pCtx->m_State; for(unsigned int i = 0; i < 32; i++) { char sReg1[32]; if(i < 10) { sprintf(sReg1, "VF%i ", i); } else { sprintf(sReg1, "VF%i ", i); } sprintf(sLine, "%s: %+.7e %+.7e\r\n %+.7e %+.7e\r\n", sReg1, \ *(float*)&pState->nCOP2[i].nV0, \ *(float*)&pState->nCOP2[i].nV1, \ *(float*)&pState->nCOP2[i].nV2, \ *(float*)&pState->nCOP2[i].nV3); result += sLine; } sprintf(sLine, "ACC : %+.7e %+.7e\r\n %+.7e %+.7e\r\n", \ *(float*)&pState->nCOP2A.nV0, \ *(float*)&pState->nCOP2A.nV1, \ *(float*)&pState->nCOP2A.nV2, \ *(float*)&pState->nCOP2A.nV3); result += sLine; sprintf(sLine, "Q : %+.7e\r\n", *(float*)&pState->nCOP2Q); result += sLine; sprintf(sLine, "I : %+.7e\r\n", *(float*)&pState->nCOP2I); result += sLine; sprintf(sLine, "P : %+.7e\r\n", *(float*)&pState->nCOP2P); result += sLine; sprintf(sLine, "R : %+.7e (0x%0.8X)\r\n", *(float*)&pState->nCOP2R, pState->nCOP2R); result += sLine; sprintf(sLine, "MACF : 0x%0.4X\r\n", pState->nCOP2MF); result += sLine; sprintf(sLine, "CLIP : 0x%0.6X\r\n", pState->nCOP2CF); result += sLine; sprintf(sLine, "PIPE : 0x%0.4X\r\n", pState->pipeTime); result += sLine; sprintf(sLine, "PIPEQ: 0x%0.4X - %+.7e\r\n", pState->pipeQ.counter, *(float*)&pState->pipeQ.heldValue); result += sLine; unsigned int currentPipeMacCounter = pState->pipeMac.index - 1; uint32 macFlagPipeValues[MACFLAG_PIPELINE_SLOTS]; uint32 macFlagPipeTimes[MACFLAG_PIPELINE_SLOTS]; for(unsigned int i = 0; i < MACFLAG_PIPELINE_SLOTS; i++) { unsigned int currIndex = (currentPipeMacCounter - i) & (MACFLAG_PIPELINE_SLOTS - 1); macFlagPipeValues[i] = pState->pipeMac.values[currIndex]; macFlagPipeTimes[i] = pState->pipeMac.pipeTimes[currIndex]; } sprintf(sLine, "PIPEM: 0x%0.4X:0x%0.4X, 0x%0.4X:0x%0.4X\r\n", macFlagPipeTimes[0], macFlagPipeValues[0], macFlagPipeTimes[1], macFlagPipeValues[1]); result += sLine; sprintf(sLine, " 0x%0.4X:0x%0.4X, 0x%0.4X:0x%0.4X\r\n", macFlagPipeTimes[2], macFlagPipeValues[2], macFlagPipeTimes[3], macFlagPipeValues[3]); result += sLine; for(unsigned int i = 0; i < 16; i += 2) { char sReg1[32]; char sReg2[32]; if(i < 10) { sprintf(sReg1, "VI%i ", i); sprintf(sReg2, "VI%i ", i + 1); } else { sprintf(sReg1, "VI%i ", i); sprintf(sReg2, "VI%i ", i + 1); } sprintf(sLine, "%s: 0x%0.4X %s: 0x%0.4X\r\n", sReg1, pState->nCOP2VI[i] & 0xFFFF, sReg2, pState->nCOP2VI[i + 1] & 0xFFFF); result += sLine; } return result; } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <But/Format/detail/ParsedFormat.hpp> #include <But/Format/detail/common.hpp> #include <But/Mpl/parse.hpp> namespace But { namespace Format { namespace detail { inline constexpr auto skipUntilEndOfComment(char const* fmt) { while( not isEos(*fmt) && *fmt!='}' ) ++fmt; return throwOnInvalidSyntax( *fmt!='}', "variable does not end with closing brace", fmt ); } inline constexpr auto parseBraceVariable(Segment& st, char const* fmt) { st.type_ = Segment::Type::Value; st.end_ = fmt; while( isDigit(*st.end_) ) ++st.end_; const auto numberEnd = st.end_; if( *st.end_ == '#' ) st.end_ = skipUntilEndOfComment(st.end_); throwOnInvalidSyntax( *st.end_!='}', "variable does not end with closing brace", st.end_ ); ++st.end_; const auto beginOffset = 2; st.referencedArgument_ = Mpl::parseUnsigned<unsigned>(st.begin_ + beginOffset, numberEnd); return st.end_; } inline constexpr auto parseBrace(Segment& st, char const* fmt) { throwOnInvalidSyntax( isEos(*fmt), "brace variable declaration is not complete", fmt ); if( *fmt == 'V' ) ++fmt; if( isDigit(*fmt) ) return parseBraceVariable(st, fmt+1); return throwOnInvalidSyntax(true, "invalid brace variable init sequence", fmt); } inline constexpr auto parseSimpleVariable(Segment& st, char const* fmt) { throwOnInvalidSyntax( not isDigit(*fmt), "simple variable declaration is not followed by a number", fmt ); st.type_ = Segment::Type::Value; st.end_ = fmt+1; while( isDigit(*st.end_) ) ++st.end_; throwOnInvalidSyntax( not isEos(*st.end_) && not isSpace(*st.end_), "variable does not end with end of data or space", st.end_ ); st.referencedArgument_ = Mpl::parseUnsigned<unsigned>(st.begin_+1, st.end_); return st.end_; } inline constexpr auto parseStringVariable(Segment& st, char const* fmt) { st.type_ = Segment::Type::String; st.end_ = fmt; return fmt+1; } inline constexpr auto parseVariable(Segment& st, char const* fmt) { st.begin_ = fmt; ++fmt; throwOnInvalidSyntax( isEos(*fmt), "end of data while declaring a variable", fmt ); if( isVariableBegin(*fmt) ) // "$$" case return parseStringVariable(st, fmt); if( *fmt=='{' ) return parseBrace(st, fmt+1); return parseSimpleVariable(st, fmt); } inline constexpr auto parseString(Segment& st, char const* fmt) { st.type_ = Segment::Type::String; st.begin_ = fmt; st.end_ = fmt; while( not isEos(*st.end_) && not isVariableBegin(*st.end_) ) ++st.end_; return st.end_; } template<typename Pf> constexpr auto parse(Pf&& pf, char const* fmt) { while( not isEos(*fmt) ) { throwOnInvalidSyntax( pf.segments_.max_size() == pf.segments_.size(), "format too long for a declared states count - expected end", fmt ); Segment st; if( isVariableBegin(*fmt) ) fmt = parseVariable(st, fmt); else fmt = parseString(st, fmt); pf.segments_.push_back( std::move(st) ); } return std::move(pf); } template<size_t N> constexpr auto parseCt(char const* fmt) { return parse( ParsedFormatCt<N>{}, fmt ); } inline auto parseRt(char const* fmt) { return parse( ParsedFormatRt{}, fmt ); } inline auto parseRt(std::string const& fmt) { return parseRt( fmt.c_str() ); } } } } <commit_msg>std::move -> std::forward as it should be<commit_after>#pragma once #include <vector> #include <But/Format/detail/ParsedFormat.hpp> #include <But/Format/detail/common.hpp> #include <But/Mpl/parse.hpp> namespace But { namespace Format { namespace detail { inline constexpr auto skipUntilEndOfComment(char const* fmt) { while( not isEos(*fmt) && *fmt!='}' ) ++fmt; return throwOnInvalidSyntax( *fmt!='}', "variable does not end with closing brace", fmt ); } inline constexpr auto parseBraceVariable(Segment& st, char const* fmt) { st.type_ = Segment::Type::Value; st.end_ = fmt; while( isDigit(*st.end_) ) ++st.end_; const auto numberEnd = st.end_; if( *st.end_ == '#' ) st.end_ = skipUntilEndOfComment(st.end_); throwOnInvalidSyntax( *st.end_!='}', "variable does not end with closing brace", st.end_ ); ++st.end_; const auto beginOffset = 2; st.referencedArgument_ = Mpl::parseUnsigned<unsigned>(st.begin_ + beginOffset, numberEnd); return st.end_; } inline constexpr auto parseBrace(Segment& st, char const* fmt) { throwOnInvalidSyntax( isEos(*fmt), "brace variable declaration is not complete", fmt ); if( *fmt == 'V' ) ++fmt; if( isDigit(*fmt) ) return parseBraceVariable(st, fmt+1); return throwOnInvalidSyntax(true, "invalid brace variable init sequence", fmt); } inline constexpr auto parseSimpleVariable(Segment& st, char const* fmt) { throwOnInvalidSyntax( not isDigit(*fmt), "simple variable declaration is not followed by a number", fmt ); st.type_ = Segment::Type::Value; st.end_ = fmt+1; while( isDigit(*st.end_) ) ++st.end_; throwOnInvalidSyntax( not isEos(*st.end_) && not isSpace(*st.end_), "variable does not end with end of data or space", st.end_ ); st.referencedArgument_ = Mpl::parseUnsigned<unsigned>(st.begin_+1, st.end_); return st.end_; } inline constexpr auto parseStringVariable(Segment& st, char const* fmt) { st.type_ = Segment::Type::String; st.end_ = fmt; return fmt+1; } inline constexpr auto parseVariable(Segment& st, char const* fmt) { st.begin_ = fmt; ++fmt; throwOnInvalidSyntax( isEos(*fmt), "end of data while declaring a variable", fmt ); if( isVariableBegin(*fmt) ) // "$$" case return parseStringVariable(st, fmt); if( *fmt=='{' ) return parseBrace(st, fmt+1); return parseSimpleVariable(st, fmt); } inline constexpr auto parseString(Segment& st, char const* fmt) { st.type_ = Segment::Type::String; st.begin_ = fmt; st.end_ = fmt; while( not isEos(*st.end_) && not isVariableBegin(*st.end_) ) ++st.end_; return st.end_; } template<typename Pf> constexpr auto parse(Pf&& pf, char const* fmt) { while( not isEos(*fmt) ) { throwOnInvalidSyntax( pf.segments_.max_size() == pf.segments_.size(), "format too long for a declared states count - expected end", fmt ); Segment st; if( isVariableBegin(*fmt) ) fmt = parseVariable(st, fmt); else fmt = parseString(st, fmt); pf.segments_.push_back( std::move(st) ); } return std::forward<Pf>(pf); } template<size_t N> constexpr auto parseCt(char const* fmt) { return parse( ParsedFormatCt<N>{}, fmt ); } inline auto parseRt(char const* fmt) { return parse( ParsedFormatRt{}, fmt ); } inline auto parseRt(std::string const& fmt) { return parseRt( fmt.c_str() ); } } } } <|endoftext|>
<commit_before> /** * @file ComputeMelbourneWubbena.hpp * This class eases computing Melbourne-Wubbena combination for GNSS data structures. */ #ifndef Compute_MELBOURNEWUBBENA_GPSTK #define Compute_MELBOURNEWUBBENA_GPSTK //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dagoberto Salazar - gAGE ( http://www.gage.es ). 2007 // //============================================================================ #include "ComputeCombination.hpp" namespace gpstk { /** @addtogroup DataStructures */ //@{ /** This class eases computing Melbourne-Wubbena combination for GNSS data structures. * This class is meant to be used with the GNSS data structures objects * found in "DataStructures" class. * * A typical way to use this class follows: * * @code * RinexObsStream rin("ebre0300.02o"); * * gnssRinex gRin; * ComputeMelbourne-Wubbena getMW; * * while(rin >> gRin) { * gRin >> getMW; * } * @endcode * * The "ComputeMelbourne-Wubbena" object will visit every satellite in the * GNSS data structure that is "gRin" and will try to compute its * Melbourne-Wubbena combination. * * When used with the ">>" operator, this class returns the same incoming * data structure with the Melbourne-Wubbena combinations inserted along their * corresponding satellites. Be warned that if a given satellite does not * have the observations required, it will be summarily deleted from the data * structure. * * Sometimes, the Rinex observations file does not have P1, but provides C1 * instead. In such cases, you must use the useC1() method. * */ class ComputeMelbourneWubbena : public ComputeCombination { public: /// Default constructor ComputeMelbourneWubbena() : type3(TypeID::L1), type4(TypeID::L2), DEN1(L1_FREQ + L2_FREQ), DEN2(L1_FREQ - L2_FREQ) { type1 = TypeID::P1; type2 = TypeID::P2; resultType = TypeID::MWubbena; }; /** Returns a satTypeValueMap object, adding the new data generated when calling this object. * * @param gData Data object holding the data. */ virtual satTypeValueMap& Combine(satTypeValueMap& gData) { double value1(0.0); double value2(0.0); double value3(0.0); double value4(0.0); SatIDSet satRejectedSet; // Loop through all the satellites satTypeValueMap::iterator it; for (it = gData.begin(); it != gData.end(); ++it) { try { // Try to extract the values value1 = (*it).second(type1); value2 = (*it).second(type2); value3 = (*it).second(type3); value4 = (*it).second(type4); } catch(...) { // If some value is missing, then schedule this satellite for removal satRejectedSet.insert( (*it).first ); continue; } // If everything is OK, then get the new value inside the structure (*it).second[resultType] = getCombination(value1, value2, value3, value4); } // Remove satellites with missing data gData.removeSatID(satRejectedSet); return gData; }; /// Some Rinex data files provide C1 instead of P1. Use this method in those cases. void useC1() { type1 = TypeID::C1; }; /// Destructor virtual ~ComputeMelbourneWubbena() {}; protected: /// Compute the combination of observables. virtual double getCombination(const double& p1, const double& p2, const double& l1, const double& l2) { return ( ( L1_FREQ*l1 - L2_FREQ*l2 ) / ( DEN2 ) - ( L1_FREQ*p1 + L2_FREQ*p2 ) / ( DEN1 ) ); }; /// Dummy function. virtual double getCombination(const double& obs1, const double& obs2) { return 0.0; }; private: /// Type of observation to be combined. Nro 3. TypeID type3; /// Type of observation to be combined. Nro 4. TypeID type4; const double DEN1; // DEN1 = L1_FREQ + L2_FREQ const double DEN2; // DEN2 = L1_FREQ - L2_FREQ }; // end class ComputeMelbourneWubbena //@} } #endif <commit_msg>Very minor change in documentation.<commit_after> /** * @file ComputeMelbourneWubbena.hpp * This class eases computing Melbourne-Wubbena combination for GNSS data structures. */ #ifndef Compute_MELBOURNEWUBBENA_GPSTK #define Compute_MELBOURNEWUBBENA_GPSTK //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dagoberto Salazar - gAGE ( http://www.gage.es ). 2007 // //============================================================================ #include "ComputeCombination.hpp" namespace gpstk { /** @addtogroup DataStructures */ //@{ /** This class eases computing Melbourne-Wubbena combination for GNSS data structures. * This class is meant to be used with the GNSS data structures objects * found in "DataStructures" class. * * A typical way to use this class follows: * * @code * RinexObsStream rin("ebre0300.02o"); * * gnssRinex gRin; * ComputeMelbourneWubbena getMW; * * while(rin >> gRin) { * gRin >> getMW; * } * @endcode * * The "ComputeMelbourne-Wubbena" object will visit every satellite in the * GNSS data structure that is "gRin" and will try to compute its * Melbourne-Wubbena combination. * * When used with the ">>" operator, this class returns the same incoming * data structure with the Melbourne-Wubbena combinations inserted along their * corresponding satellites. Be warned that if a given satellite does not * have the observations required, it will be summarily deleted from the data * structure. * * Sometimes, the Rinex observations file does not have P1, but provides C1 * instead. In such cases, you must use the useC1() method. * */ class ComputeMelbourneWubbena : public ComputeCombination { public: /// Default constructor ComputeMelbourneWubbena() : type3(TypeID::L1), type4(TypeID::L2), DEN1(L1_FREQ + L2_FREQ), DEN2(L1_FREQ - L2_FREQ) { type1 = TypeID::P1; type2 = TypeID::P2; resultType = TypeID::MWubbena; }; /** Returns a satTypeValueMap object, adding the new data generated when calling this object. * * @param gData Data object holding the data. */ virtual satTypeValueMap& Combine(satTypeValueMap& gData) { double value1(0.0); double value2(0.0); double value3(0.0); double value4(0.0); SatIDSet satRejectedSet; // Loop through all the satellites satTypeValueMap::iterator it; for (it = gData.begin(); it != gData.end(); ++it) { try { // Try to extract the values value1 = (*it).second(type1); value2 = (*it).second(type2); value3 = (*it).second(type3); value4 = (*it).second(type4); } catch(...) { // If some value is missing, then schedule this satellite for removal satRejectedSet.insert( (*it).first ); continue; } // If everything is OK, then get the new value inside the structure (*it).second[resultType] = getCombination(value1, value2, value3, value4); } // Remove satellites with missing data gData.removeSatID(satRejectedSet); return gData; }; /// Some Rinex data files provide C1 instead of P1. Use this method in those cases. void useC1() { type1 = TypeID::C1; }; /// Destructor virtual ~ComputeMelbourneWubbena() {}; protected: /// Compute the combination of observables. virtual double getCombination(const double& p1, const double& p2, const double& l1, const double& l2) { return ( ( L1_FREQ*l1 - L2_FREQ*l2 ) / ( DEN2 ) - ( L1_FREQ*p1 + L2_FREQ*p2 ) / ( DEN1 ) ); }; /// Dummy function. virtual double getCombination(const double& obs1, const double& obs2) { return 0.0; }; private: /// Type of observation to be combined. Nro 3. TypeID type3; /// Type of observation to be combined. Nro 4. TypeID type4; const double DEN1; // DEN1 = L1_FREQ + L2_FREQ const double DEN2; // DEN2 = L1_FREQ - L2_FREQ }; // end class ComputeMelbourneWubbena //@} } #endif <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 "BitFunnel/Index/IFactSet.h" // For FactHandle. #include "BitFunnel/Index/ITermTable.h" #include "BitFunnel/Index/PackedRowIdSequence.h" #include "BitFunnel/Index/RowId.h" #include "BitFunnel/Index/RowIdSequence.h" #include "BitFunnel/Term.h" #include "LoggerInterfaces/Logging.h" namespace BitFunnel { //************************************************************************* // // RowIdSequence // //************************************************************************* // TODO: should GetRawHash be GetClassifiedHash or GetGeneralHash? RowIdSequence::RowIdSequence(Term const & term, ITermTable const & termTable) : m_hash(term.GetRawHash()), m_termTable(termTable) { // TODO: Get rid of out parameter for m_termKind. Consider returning an std::pair. // TODO: See if there is any way this can run in the initializer so that members // can be const. // TODO: Eliminate Shard and Tier from RowId. const PackedRowIdSequence packed(termTable.GetRows(term)); Initialize(packed); } //// TODO: Implement this constructor. RowIdSequence::RowIdSequence(FactHandle fact, ITermTable const & termTable) : m_hash(0), m_termTable(termTable) { throw fact; // // TODO: Figure out how to eliminate StreamId::Metaword for facts. // // Do we just create c_MetaWordStreamId? Can user's use this StreamId? // const Term term(static_cast<Term::Hash>(fact), // StreamId::MetaWord, // static_cast<Term::IdfX10>(0)); // const PackedTermInfo info = termTable.GetTermInfo(term, m_termKind); // Initialize(info); } RowIdSequence::const_iterator RowIdSequence::begin() const { return const_iterator(*this, 0ull); } RowIdSequence::const_iterator RowIdSequence::end() const { return const_iterator(*this, m_rowIdCount); } RowId RowIdSequence::GetRow(size_t row) const { if (row >= m_rowIdCount) { RecoverableError error("RowIdSequence::GetRow(): row out of range."); throw error; } if (m_type == PackedRowIdSequence::Type::Explicit) { return m_termTable.GetRowIdExplicit(m_rowIdStart + row); } else if(m_type == PackedRowIdSequence::Type::Adhoc) { // TODO: can hash variant be created here in order to eliminate // third argument. return m_termTable.GetRowIdAdhoc(m_hash, m_rowIdStart + row, row); } else { return m_termTable.GetRowIdFact(m_rowIdStart + row); } // No special clause for ITermTable::Disposed as they return an empty // PackedTermInfo which does not support enumeration. } void RowIdSequence::Initialize(PackedRowIdSequence const & packed) { m_rowIdStart = packed.GetStart(); m_rowIdCount = packed.GetEnd() - packed.GetStart(); m_type = packed.GetType(); } } <commit_msg>Add hack for build failure on Windows.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 "BitFunnel/Index/IFactSet.h" // For FactHandle. #include "BitFunnel/Index/ITermTable.h" #include "BitFunnel/Index/PackedRowIdSequence.h" #include "BitFunnel/Index/RowId.h" #include "BitFunnel/Index/RowIdSequence.h" #include "BitFunnel/Term.h" #include "LoggerInterfaces/Logging.h" namespace BitFunnel { //************************************************************************* // // RowIdSequence // //************************************************************************* // TODO: should GetRawHash be GetClassifiedHash or GetGeneralHash? RowIdSequence::RowIdSequence(Term const & term, ITermTable const & termTable) : m_hash(term.GetRawHash()), m_termTable(termTable) { // TODO: Get rid of out parameter for m_termKind. Consider returning an std::pair. // TODO: See if there is any way this can run in the initializer so that members // can be const. // TODO: Eliminate Shard and Tier from RowId. const PackedRowIdSequence packed(termTable.GetRows(term)); Initialize(packed); } //// TODO: Implement this constructor. RowIdSequence::RowIdSequence(FactHandle fact, ITermTable const & termTable) : m_hash(0), m_termTable(termTable) { // We're throwing because this isn't implemented yet. This if is // because, on some configurations of VC++, throwing causes the build to // error out. For reasons we don't understand, this doesn't happen in // AppVeyor CI. if (fact != 17u) { throw fact; } // // TODO: Figure out how to eliminate StreamId::Metaword for facts. // // Do we just create c_MetaWordStreamId? Can user's use this StreamId? // const Term term(static_cast<Term::Hash>(fact), // StreamId::MetaWord, // static_cast<Term::IdfX10>(0)); // const PackedTermInfo info = termTable.GetTermInfo(term, m_termKind); // Initialize(info); } RowIdSequence::const_iterator RowIdSequence::begin() const { return const_iterator(*this, 0ull); } RowIdSequence::const_iterator RowIdSequence::end() const { return const_iterator(*this, m_rowIdCount); } RowId RowIdSequence::GetRow(size_t row) const { if (row >= m_rowIdCount) { RecoverableError error("RowIdSequence::GetRow(): row out of range."); throw error; } if (m_type == PackedRowIdSequence::Type::Explicit) { return m_termTable.GetRowIdExplicit(m_rowIdStart + row); } else if(m_type == PackedRowIdSequence::Type::Adhoc) { // TODO: can hash variant be created here in order to eliminate // third argument. return m_termTable.GetRowIdAdhoc(m_hash, m_rowIdStart + row, row); } else { return m_termTable.GetRowIdFact(m_rowIdStart + row); } // No special clause for ITermTable::Disposed as they return an empty // PackedTermInfo which does not support enumeration. } void RowIdSequence::Initialize(PackedRowIdSequence const & packed) { m_rowIdStart = packed.GetStart(); m_rowIdCount = packed.GetEnd() - packed.GetStart(); m_type = packed.GetType(); } } <|endoftext|>
<commit_before>#include "KEngine/Core/Entity.hpp" #include "KEngine/Interfaces/IEntityComponent.hpp" #include "KEngine/Log/Log.hpp" #include <cassert> namespace ke { Entity::Entity(const ke::EntityId p_ID) : m_EntityID(p_ID) {} Entity::Entity(ke::Entity && p_rrEntity) : m_Components(std::move(p_rrEntity.m_Components)) , m_ComponentSPMap(std::move(p_rrEntity.m_ComponentSPMap)) , m_EntityID(std::move(p_rrEntity.getId())) {} Entity & Entity::operator=(ke::Entity && p_rrEntity) { m_Components = std::move(p_rrEntity.m_Components); m_ComponentSPMap = std::move(p_rrEntity.m_ComponentSPMap); m_EntityID = p_rrEntity.getId(); return *this; } Entity::~Entity(void) { assert(this->m_ComponentSPMap.empty()); // component must be empty (all circular references removed). } void Entity::addComponent(ke::EntityComponentSptr p_spEntityComponent) { assert(p_spEntityComponent != nullptr); // should not be null. const auto result = m_ComponentSPMap.insert(std::make_pair(p_spEntityComponent->getType(), p_spEntityComponent)); assert(result.second); // fails if insertion failed. if (!result.second) { ke::Log::instance()->error("Attempted to add entity component of duplicate type: {0:#x}", p_spEntityComponent->getType()); return; } m_Components.push_back(p_spEntityComponent); } bool Entity::initialise(void) { bool result = true; for (auto & it : m_ComponentSPMap) if (!it.second->isInitialised()) { if (it.second->initialise()) { it.second->postInitialise(); } else { ke::Log::instance()->error("Entity named '{}'({}) failed to initialise its component: '{}'", this->getName(), this->getId(), it.second->getName()); result = false; } } return result; } void Entity::updateAll(const ke::Time & p_ElapsedTime) { if (!this->m_Initialised) { this->m_Initialised = this->initialise(); } for (auto & it : m_Components) it->update(p_ElapsedTime); } }<commit_msg>Fix components added to a Entity after it's been initialised will not be initialised<commit_after>#include "KEngine/Core/Entity.hpp" #include "KEngine/Interfaces/IEntityComponent.hpp" #include "KEngine/Log/Log.hpp" #include <cassert> namespace ke { Entity::Entity(const ke::EntityId p_ID) : m_EntityID(p_ID) {} Entity::Entity(ke::Entity && p_rrEntity) : m_Components(std::move(p_rrEntity.m_Components)) , m_ComponentSPMap(std::move(p_rrEntity.m_ComponentSPMap)) , m_EntityID(std::move(p_rrEntity.getId())) {} Entity & Entity::operator=(ke::Entity && p_rrEntity) { m_Components = std::move(p_rrEntity.m_Components); m_ComponentSPMap = std::move(p_rrEntity.m_ComponentSPMap); m_EntityID = p_rrEntity.getId(); return *this; } Entity::~Entity(void) { assert(this->m_ComponentSPMap.empty()); // component must be empty (all circular references removed). } void Entity::addComponent(ke::EntityComponentSptr p_spEntityComponent) { assert(p_spEntityComponent != nullptr); // should not be null. const auto result = m_ComponentSPMap.insert(std::make_pair(p_spEntityComponent->getType(), p_spEntityComponent)); assert(result.second); // fails if insertion failed. if (!result.second) { ke::Log::instance()->error("Attempted to add entity component of duplicate type: {0:#x}", p_spEntityComponent->getType()); return; } m_Components.push_back(p_spEntityComponent); if (m_Initialised) { if (!this->initialise()) { ke::Log::instance()->error("Failed to initialised entity component of type {0:#x} after adding it to entity '{}'({})", p_spEntityComponent->getType(), this->getName(), this->getId()); } } } bool Entity::initialise(void) { bool result = true; for (auto & it : m_ComponentSPMap) if (!it.second->isInitialised()) { if (it.second->initialise()) { it.second->postInitialise(); } else { ke::Log::instance()->error("Entity named '{}'({}) failed to initialise its component: '{}'", this->getName(), this->getId(), it.second->getName()); result = false; } } return result; } void Entity::updateAll(const ke::Time & p_ElapsedTime) { if (!this->m_Initialised) { this->m_Initialised = this->initialise(); } for (auto & it : m_Components) it->update(p_ElapsedTime); } }<|endoftext|>
<commit_before><commit_msg>fix -Wmaybe-uninitialized<commit_after><|endoftext|>
<commit_before><commit_msg>Planning: add TODO item for avoiding off-road.<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "resizeindicator.h" #include "formeditoritem.h" namespace QmlDesigner { ResizeIndicator::ResizeIndicator(LayerItem *layerItem) : m_layerItem(layerItem) { Q_ASSERT(layerItem); } ResizeIndicator::~ResizeIndicator() { m_itemControllerHash.clear(); } void ResizeIndicator::show() { QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); while (itemControllerIterator.hasNext()) { ResizeController controller = itemControllerIterator.next().value(); controller.show(); } } void ResizeIndicator::hide() { QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); while (itemControllerIterator.hasNext()) { ResizeController controller = itemControllerIterator.next().value(); controller.hide(); } } void ResizeIndicator::clear() { m_itemControllerHash.clear(); } bool itemIsResizable(const QmlItemNode &qmlItemNode) { return qmlItemNode.isValid() && qmlItemNode.instanceIsResizable() && qmlItemNode.modelIsMovable() && qmlItemNode.modelIsResizable() && !qmlItemNode.instanceHasRotationTransform() && !qmlItemNode.instanceIsInLayoutable(); } void ResizeIndicator::setItems(const QList<FormEditorItem*> &itemList) { clear(); foreach (FormEditorItem* item, itemList) { if (item && itemIsResizable(item->qmlItemNode())) { ResizeController controller(m_layerItem, item); m_itemControllerHash.insert(item, controller); } } } void ResizeIndicator::updateItems(const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem* item, itemList) { if (m_itemControllerHash.contains(item)) { if (!item || !itemIsResizable(item->qmlItemNode())) { m_itemControllerHash.take(item); } else { ResizeController controller(m_itemControllerHash.value(item)); controller.updatePosition(); } } } } } <commit_msg>QmlDesigner: After removing xy bindings item should be resizable again<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "resizeindicator.h" #include "formeditoritem.h" namespace QmlDesigner { ResizeIndicator::ResizeIndicator(LayerItem *layerItem) : m_layerItem(layerItem) { Q_ASSERT(layerItem); } ResizeIndicator::~ResizeIndicator() { m_itemControllerHash.clear(); } void ResizeIndicator::show() { QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); while (itemControllerIterator.hasNext()) { ResizeController controller = itemControllerIterator.next().value(); controller.show(); } } void ResizeIndicator::hide() { QHashIterator<FormEditorItem*, ResizeController> itemControllerIterator(m_itemControllerHash); while (itemControllerIterator.hasNext()) { ResizeController controller = itemControllerIterator.next().value(); controller.hide(); } } void ResizeIndicator::clear() { m_itemControllerHash.clear(); } bool itemIsResizable(const QmlItemNode &qmlItemNode) { return qmlItemNode.isValid() && qmlItemNode.instanceIsResizable() && qmlItemNode.modelIsMovable() && qmlItemNode.modelIsResizable() && !qmlItemNode.instanceHasRotationTransform() && !qmlItemNode.instanceIsInLayoutable(); } void ResizeIndicator::setItems(const QList<FormEditorItem*> &itemList) { clear(); foreach (FormEditorItem* item, itemList) { if (item && itemIsResizable(item->qmlItemNode())) { ResizeController controller(m_layerItem, item); m_itemControllerHash.insert(item, controller); } } } void ResizeIndicator::updateItems(const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem* item, itemList) { if (m_itemControllerHash.contains(item)) { if (!item || !itemIsResizable(item->qmlItemNode())) { m_itemControllerHash.take(item); } else { ResizeController controller(m_itemControllerHash.value(item)); controller.updatePosition(); } } else if (item && itemIsResizable(item->qmlItemNode())) { ResizeController controller(m_layerItem, item); m_itemControllerHash.insert(item, controller); } } } } <|endoftext|>
<commit_before>#include <limits> #include <vector> #include <gtest/gtest.h> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions.hpp> #include <boost/math/tools/promotion.hpp> #include <stan/math/rev.hpp> #include <stan/math/prim/fun/sign.hpp> #include <stan/math/prim/fun/fabs.hpp> #include <stan/math/prim/fun/log1m.hpp> template <typename T1, typename T2, typename T3, typename T4> inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type skew_de_cdf_test(const T1& y, const T2& mu, const T3& sigma, const T4& tau) { using stan::math::log1m; using std::exp; using std::log; if (y < mu) { return log(tau) - 2 / sigma * (1 - tau) * (mu - y); } else { return log1m((1 - tau) * exp(-2 / sigma * tau * (y - mu))); } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_computes_correct_gradients) { using stan::math::skew_double_exponential_lcdf; for (double ys : {-1.7, 0.2, 0.5, 0.9, 1.1, 3.2, 8.3}) { for (double mus : {-1.8, 0.1, 0.55, 0.89, 1.3, 4.2, 9.3}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { stan::math::var y = ys; stan::math::var mu = mus; stan::math::var sigma = sigmas; stan::math::var tau = taus; stan::math::var lp = skew_double_exponential_lcdf(y, mu, sigma, tau); std::vector<stan::math::var> theta; theta.push_back(y); theta.push_back(mu); theta.push_back(sigma); theta.push_back(tau); std::vector<double> grads; lp.grad(theta, grads); stan::math::var y_true = ys; stan::math::var mu_true = mus; stan::math::var sigma_true = sigmas; stan::math::var tau_true = taus; stan::math::var lp_test = skew_de_cdf_test(y_true, mu_true, sigma_true, tau_true); std::vector<stan::math::var> theta_true; theta_true.push_back(y_true); theta_true.push_back(mu_true); theta_true.push_back(sigma_true); theta_true.push_back(tau_true); std::vector<double> grads_true; lp_test.grad(theta_true, grads_true); EXPECT_NEAR(grads_true[0], grads[0], 0.001); EXPECT_NEAR(grads_true[1], grads[1], 0.001); EXPECT_NEAR(grads_true[2], grads[2], 0.001); EXPECT_NEAR(grads_true[3], grads[3], 0.001); } } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_scalar_arguments) { using stan::math::skew_double_exponential_lcdf; for (double ys : {0.2, 0.9, 1.1, 3.2}) { for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { EXPECT_NEAR(skew_de_cdf_test(ys, mus, sigmas, taus), skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vector_arguments) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1, 3.2}; for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (double y : ys) x += skew_de_cdf_test(y, mus, sigmas, taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_mu) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> mus{0.1, 1.3, 3.0}; for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus[i], sigmas, taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_sigma) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> sigmas{0.1, 1.1, 3.2}; for (double mus : {0.1, 1.3, 3.0}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus, sigmas[i], taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_tau) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> taus{0.1, 0.5, 0.9}; for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus, sigmas, taus[i]); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_mu_sigma_and_tau) { using stan::math::skew_double_exponential_lcdf; std::vector<double> mus{0.1, 1.3, 3.0}; std::vector<double> sigmas{0.1, 1.1, 3.2}; std::vector<double> taus{0.1, 0.5, 0.9}; for (double ys : {0.1, 1.3, 3.0}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys, mus[i], sigmas[i], taus[i]); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_errors) { using stan::math::skew_double_exponential_lcdf; static double inff = std::numeric_limits<double>::infinity(); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, -1, 0.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, 0.1, -0.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(inff, 0.0, 0.1, 1.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, inff, 0.1, 1.5), std::domain_error); } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_inconsistent_size) { using stan::math::skew_double_exponential_lcdf; std::vector<double> mus{0.1, 1.3, 3.0}; std::vector<double> sigmas{0.1, 1.1, 3.2, 1.0}; std::vector<double> taus{0.1, 0.5, 0.9}; EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, mus, sigmas, taus), std::invalid_argument); } #include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(ProbDistributionsSkewedDoubleExponential, cdf_log_matches_lcdf) { double y = 0.8; double mu = 2; double sigma = 2.3; double tau = 0.1; EXPECT_FLOAT_EQ( (stan::math::skew_double_exponential_lcdf(y, mu, sigma, tau)), (stan::math::skew_double_exponential_cdf_log(y, mu, sigma, tau))); EXPECT_FLOAT_EQ( (stan::math::skew_double_exponential_lcdf<double, double, double, double>( y, mu, sigma, tau)), (stan::math::skew_double_exponential_cdf_log<double, double, double, double>(y, mu, sigma, tau))); } <commit_msg>Remove double include statement<commit_after>#include <limits> #include <vector> #include <gtest/gtest.h> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions.hpp> #include <boost/math/tools/promotion.hpp> #include <stan/math/rev.hpp> #include <stan/math/prim/fun/sign.hpp> #include <stan/math/prim/fun/fabs.hpp> #include <stan/math/prim/fun/log1m.hpp> template <typename T1, typename T2, typename T3, typename T4> inline typename boost::math::tools::promote_args<T1, T2, T3, T4>::type skew_de_cdf_test(const T1& y, const T2& mu, const T3& sigma, const T4& tau) { using stan::math::log1m; using std::exp; using std::log; if (y < mu) { return log(tau) - 2 / sigma * (1 - tau) * (mu - y); } else { return log1m((1 - tau) * exp(-2 / sigma * tau * (y - mu))); } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_computes_correct_gradients) { using stan::math::skew_double_exponential_lcdf; for (double ys : {-1.7, 0.2, 0.5, 0.9, 1.1, 3.2, 8.3}) { for (double mus : {-1.8, 0.1, 0.55, 0.89, 1.3, 4.2, 9.3}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { stan::math::var y = ys; stan::math::var mu = mus; stan::math::var sigma = sigmas; stan::math::var tau = taus; stan::math::var lp = skew_double_exponential_lcdf(y, mu, sigma, tau); std::vector<stan::math::var> theta; theta.push_back(y); theta.push_back(mu); theta.push_back(sigma); theta.push_back(tau); std::vector<double> grads; lp.grad(theta, grads); stan::math::var y_true = ys; stan::math::var mu_true = mus; stan::math::var sigma_true = sigmas; stan::math::var tau_true = taus; stan::math::var lp_test = skew_de_cdf_test(y_true, mu_true, sigma_true, tau_true); std::vector<stan::math::var> theta_true; theta_true.push_back(y_true); theta_true.push_back(mu_true); theta_true.push_back(sigma_true); theta_true.push_back(tau_true); std::vector<double> grads_true; lp_test.grad(theta_true, grads_true); EXPECT_NEAR(grads_true[0], grads[0], 0.001); EXPECT_NEAR(grads_true[1], grads[1], 0.001); EXPECT_NEAR(grads_true[2], grads[2], 0.001); EXPECT_NEAR(grads_true[3], grads[3], 0.001); } } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_scalar_arguments) { using stan::math::skew_double_exponential_lcdf; for (double ys : {0.2, 0.9, 1.1, 3.2}) { for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { EXPECT_NEAR(skew_de_cdf_test(ys, mus, sigmas, taus), skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vector_arguments) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1, 3.2}; for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (double y : ys) x += skew_de_cdf_test(y, mus, sigmas, taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_mu) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> mus{0.1, 1.3, 3.0}; for (double sigmas : {0.1, 1.1, 3.2}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus[i], sigmas, taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_sigma) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> sigmas{0.1, 1.1, 3.2}; for (double mus : {0.1, 1.3, 3.0}) { for (double taus : {0.01, 0.1, 0.5, 0.9, 0.99}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus, sigmas[i], taus); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_y_and_tau) { using stan::math::skew_double_exponential_lcdf; std::vector<double> ys{0.2, 0.9, 1.1}; std::vector<double> taus{0.1, 0.5, 0.9}; for (double mus : {0.1, 1.3, 3.0}) { for (double sigmas : {0.1, 1.1, 3.2}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys[i], mus, sigmas, taus[i]); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_works_on_vectorial_mu_sigma_and_tau) { using stan::math::skew_double_exponential_lcdf; std::vector<double> mus{0.1, 1.3, 3.0}; std::vector<double> sigmas{0.1, 1.1, 3.2}; std::vector<double> taus{0.1, 0.5, 0.9}; for (double ys : {0.1, 1.3, 3.0}) { double x = 0.0; for (int i = 0; i < 3; i++) x += skew_de_cdf_test(ys, mus[i], sigmas[i], taus[i]); EXPECT_NEAR(x, skew_double_exponential_lcdf(ys, mus, sigmas, taus), 0.001); } } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_errors) { using stan::math::skew_double_exponential_lcdf; static double inff = std::numeric_limits<double>::infinity(); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, -1, 0.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, 0.0, 0.1, -0.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(inff, 0.0, 0.1, 1.5), std::domain_error); EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, inff, 0.1, 1.5), std::domain_error); } TEST(ProbDistributionsSkewedDoubleExponential, lcdf_check_inconsistent_size) { using stan::math::skew_double_exponential_lcdf; std::vector<double> mus{0.1, 1.3, 3.0}; std::vector<double> sigmas{0.1, 1.1, 3.2, 1.0}; std::vector<double> taus{0.1, 0.5, 0.9}; EXPECT_THROW(stan::math::skew_double_exponential_lcdf(1.0, mus, sigmas, taus), std::invalid_argument); } TEST(ProbDistributionsSkewedDoubleExponential, cdf_log_matches_lcdf) { double y = 0.8; double mu = 2; double sigma = 2.3; double tau = 0.1; EXPECT_FLOAT_EQ( (stan::math::skew_double_exponential_lcdf(y, mu, sigma, tau)), (stan::math::skew_double_exponential_cdf_log(y, mu, sigma, tau))); EXPECT_FLOAT_EQ( (stan::math::skew_double_exponential_lcdf<double, double, double, double>( y, mu, sigma, tau)), (stan::math::skew_double_exponential_cdf_log<double, double, double, double>(y, mu, sigma, tau))); } <|endoftext|>
<commit_before>/*! ** \file Request.cpp ** \date Wed May 7 2008 ** \author Steve Sloan <[email protected]> ** Copyright (C) 2008 by Steve Sloan ** ** 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, you may access it via the web ** at http://www.gnu.org/copyleft/lesser.html . */ #include <string> #include <curl/curl.h> #include "Transfer.h" #include "Request.h" #include <iostream> using namespace std; using namespace Finagle; using namespace Transfer; inline void CURL_ASSERT( CURLcode res ) { if ( res != 0 ) throw Transfer::Exception( curl_easy_strerror( res ) ); } /*! ** \class Finagle::Transfer::Request ** \brief A single cURL request. ** ** */ Request::Request( URL const &url ) : _url( url ), _req( curl_easy_init() ), _reqAdded( false ), _res( 0 ), _firstFrag( true ) { if ( !_req ) throw Transfer::Exception( "Unable to create cURL easy instance" ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_URL, ((string const &) _url).c_str() ) ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_WRITEFUNCTION, onBodyFrag ) ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_WRITEDATA, (void *) this ) ); } Request::~Request( void ) { if ( !_req ) return; if ( _reqAdded ) Proc().remove( *this ); curl_easy_cleanup( _req ); } unsigned Request::result( void ) const { if ( !_res ) { long code; CURL_ASSERT( curl_easy_getinfo( _req, CURLINFO_RESPONSE_CODE, &code ) ); _res = (unsigned) code; } return _res; } void Request::perform( void ) { if ( !_req ) return; Proc().add( *this ); _reqAdded = true; } size_t Request::onBodyFrag( const char *data, size_t membSize, size_t membNum, Request *reqPtr ) { size_t size = membSize * membNum; if ( !size ) return 0; Request::Ptr req( reqPtr ); if ( req->_firstFrag ) { req->_firstFrag = false; if ( !req->recvBodyStart.empty() ) { char *type; double size; CURL_ASSERT( curl_easy_getinfo( req->_req, CURLINFO_CONTENT_TYPE, &type ) ); CURL_ASSERT( curl_easy_getinfo( req->_req, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size ) ); req->recvBodyStart( (String) type, (size_t) size ); } } req->recvBodyFrag( data, size ); return req->recvBodyFrag.empty() ? 0 : size; } <commit_msg>Net: fixed Request to handle unsized parts.<commit_after>/*! ** \file Request.cpp ** \date Wed May 7 2008 ** \author Steve Sloan <[email protected]> ** Copyright (C) 2008 by Steve Sloan ** ** 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, you may access it via the web ** at http://www.gnu.org/copyleft/lesser.html . */ #include <string> #include <curl/curl.h> #include "Transfer.h" #include "Request.h" #include <iostream> using namespace std; using namespace Finagle; using namespace Transfer; inline void CURL_ASSERT( CURLcode res ) { if ( res != 0 ) throw Transfer::Exception( curl_easy_strerror( res ) ); } /*! ** \class Finagle::Transfer::Request ** \brief A single cURL request. ** ** */ Request::Request( URL const &url ) : _url( url ), _req( curl_easy_init() ), _reqAdded( false ), _res( 0 ), _firstFrag( true ) { if ( !_req ) throw Transfer::Exception( "Unable to create cURL easy instance" ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_URL, ((string const &) _url).c_str() ) ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_WRITEFUNCTION, onBodyFrag ) ); CURL_ASSERT( curl_easy_setopt( _req, CURLOPT_WRITEDATA, (void *) this ) ); } Request::~Request( void ) { if ( !_req ) return; if ( _reqAdded ) Proc().remove( *this ); curl_easy_cleanup( _req ); } unsigned Request::result( void ) const { if ( !_res ) { long code; CURL_ASSERT( curl_easy_getinfo( _req, CURLINFO_RESPONSE_CODE, &code ) ); _res = (unsigned) code; } return _res; } void Request::perform( void ) { if ( !_req ) return; Proc().add( *this ); _reqAdded = true; } size_t Request::onBodyFrag( const char *data, size_t membSize, size_t membNum, Request *reqPtr ) { size_t size = membSize * membNum; if ( !size ) return 0; Request::Ptr req( reqPtr ); if ( req->_firstFrag ) { req->_firstFrag = false; if ( !req->recvBodyStart.empty() ) { char *type; double size; CURL_ASSERT( curl_easy_getinfo( req->_req, CURLINFO_CONTENT_TYPE, &type ) ); CURL_ASSERT( curl_easy_getinfo( req->_req, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size ) ); if ( size < 0.0 ) size = 0; req->recvBodyStart( (String) type, (size_t) size ); } } req->recvBodyFrag( data, size ); return req->recvBodyFrag.empty() ? 0 : size; } <|endoftext|>
<commit_before>#include <Core/Types.hpp> #include <Engine/Rendering/Renderer.hpp> #include <Engine/Scene/Light.hpp> #include <Gui/Utils/KeyMappingManager.hpp> #include <Gui/Viewer/RotateAroundCameraManipulator.hpp> #include <Gui/Viewer/Viewer.hpp> namespace Ra { namespace Gui { using namespace Ra::Core::Utils; using RotateAroundCameraMapping = KeyMappingManageable<RotateAroundCameraManipulator>; #define KMA_VALUE( XX ) KeyMappingManager::KeyMappingAction RotateAroundCameraManipulator::XX; KeyMappingRotateAroundCamera; #undef KMA_VALUE void RotateAroundCameraManipulator::configureKeyMapping_impl() { auto keyMappingManager = Gui::KeyMappingManager::getInstance(); thisKeyMapping::setContext( KeyMappingManager::getInstance()->getContext( "CameraContext" ) ); if ( thisKeyMapping::getContext().isInvalid() ) { LOG( logINFO ) << "CameraContext not defined (maybe the configuration file do not contains it)"; LOG( logERROR ) << "CameraContext all keymapping invalide !"; return; } #define KMA_VALUE( XX ) XX = keyMappingManager->getActionIndex( thisKeyMapping::getContext(), #XX ); KeyMappingRotateAroundCamera #undef KMA_VALUE } void rotateAroundPoint( Ra::Core::Asset::Camera* cam, Ra::Core::Vector3& target, Ra::Core::Quaternion& rotation, const Ra::Core::Vector3& point ) { Ra::Core::Vector3 t = cam->getPosition(); Scalar l = ( target - t ).norm(); Ra::Core::Transform inverseCamRotateAround; Ra::Core::AngleAxis aa0 {rotation}; Ra::Core::AngleAxis aa1 {aa0.angle(), ( cam->getFrame().linear() * aa0.axis() ).normalized()}; inverseCamRotateAround.setIdentity(); inverseCamRotateAround.rotate( aa1 ); cam->applyTransform( inverseCamRotateAround ); Ra::Core::Vector3 trans = point + inverseCamRotateAround * ( t - point ); cam->setPosition( trans ); target = cam->getPosition() + l * cam->getDirection(); return; } RotateAroundCameraManipulator::RotateAroundCameraManipulator( const CameraManipulator& cm, Ra::Gui::Viewer* viewer ) : TrackballCameraManipulator( cm ), m_viewer( viewer ) {} bool RotateAroundCameraManipulator::handleMouseMoveEvent( QMouseEvent* event, const Qt::MouseButtons& /*buttons*/, const Qt::KeyboardModifiers& /* modifiers*/, int /*key*/ ) { Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth(); Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight(); m_lastMouseX = event->pos().x(); m_lastMouseY = event->pos().y(); if ( event->modifiers().testFlag( Qt::AltModifier ) ) { m_quickCameraModifier = 10.0_ra; } else { m_quickCameraModifier = 2.0_ra; } if ( m_currentAction == TRACKBALLCAMERA_ROTATE ) { handleCameraRotate( event->pos().x(), event->pos().y() ); } else if ( m_currentAction == TRACKBALLCAMERA_PAN ) handleCameraPan( dx, dy ); else if ( m_currentAction == TRACKBALLCAMERA_ZOOM ) handleCameraZoom( dx, dy ); else if ( m_currentAction == TRACKBALLCAMERA_MOVE_FORWARD ) handleCameraMoveForward( dx, dy ); // { handleCameraForward( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) ); // } m_prevMouseX = m_lastMouseX; m_prevMouseY = m_lastMouseY; if ( m_light != nullptr ) { m_light->setPosition( m_camera->getPosition() ); m_light->setDirection( m_camera->getDirection() ); } return m_currentAction.isValid(); } bool RotateAroundCameraManipulator::handleKeyPressEvent( QKeyEvent* /*event*/, const Ra::Gui::KeyMappingManager::KeyMappingAction& action ) { if ( action == ROTATEAROUND_ALIGN_WITH_CLOSEST_AXIS ) { alignOnClosestAxis(); return true; } if ( action == ROTATEAROUND_SET_PIVOT ) { setPivotFromPixel( m_lastMouseX, m_lastMouseY ); return true; } return false; } void RotateAroundCameraManipulator::setPivot( Ra::Core::Vector3 pivot ) { m_pivot = pivot; } void RotateAroundCameraManipulator::setPivotFromPixel( Scalar x, Scalar y ) { m_viewer->makeCurrent(); Scalar z = m_viewer->getRenderer()->getDepth( x, m_viewer->height() - y ); setPivot( m_camera->unProjectFromScreen( Ra::Core::Vector3( x, y, z ) ) ); m_viewer->doneCurrent(); } void RotateAroundCameraManipulator::alignOnClosestAxis() { Ra::Core::Vector3 x( 1_ra, 0_ra, 0_ra ); Ra::Core::Vector3 y( 0_ra, 1_ra, 0_ra ); Ra::Core::Vector3 z( 0_ra, 0_ra, 1_ra ); Ra::Core::Vector3 oldDirection, newDirection = m_camera->getDirection(); Ra::Core::Vector3 newUpVector = m_camera->getUpVector(); // getFrame().inverse() is a transform we can apply on Vector3 Ra::Core::Vector3 pivotInCamSpace = m_camera->getFrame().inverse() * m_pivot; auto updateMaxAndAxis = []( Ra::Core::Vector3 ref, Ra::Core::Vector3 axis, Ra::Core::Vector3& out, Scalar& max ) { Scalar d = ref.dot( axis ); if ( d > max ) { max = d; out = axis; } }; Scalar max = 0_ra; Ra::Core::Vector3 ref = m_camera->getDirection(); for ( auto axis : std::vector<Ra::Core::Vector3> {-x, x, -y, y, -z, z} ) { updateMaxAndAxis( ref, axis, newDirection, max ); } m_camera->setDirection( newDirection ); max = 0_ra; ref = m_camera->getUpVector(); for ( auto axis : std::vector<Ra::Core::Vector3> {-x, x, -y, y, -z, z} ) { updateMaxAndAxis( ref, axis, newUpVector, max ); } m_camera->setUpVector( newUpVector ); Ra::Core::Vector3 newPivot = m_camera->getFrame() * pivotInCamSpace; Ra::Core::Vector3 trans = m_pivot - newPivot; m_camera->setPosition( m_camera->getPosition() + trans ); if ( m_light != nullptr ) { m_light->setPosition( m_camera->getPosition() ); m_light->setDirection( m_camera->getDirection() ); } } void RotateAroundCameraManipulator::handleCameraRotate( Scalar x, Scalar y ) { Ra::Core::Vector3 trans = m_camera->projectToScreen( m_pivot ); Ra::Core::Quaternion rot = deformedBallQuaternion( x, y, trans[0], trans[1] ); Ra::Core::Vector3 pivot = m_pivot; rotateAroundPoint( m_camera, m_target, rot, pivot ); } Scalar RotateAroundCameraManipulator::projectOnBall( Scalar x, Scalar y ) { const Scalar size = 1.0; const Scalar size2 = size * size; const Scalar size_limit = size2 * 0.5; const Scalar d = x * x + y * y; return d < size_limit ? sqrt( size2 - d ) : size_limit / sqrt( d ); } Ra::Core::Quaternion RotateAroundCameraManipulator::deformedBallQuaternion( Scalar x, Scalar y, Scalar cx, Scalar cy ) { // Points on the deformed ball Scalar px = m_cameraSensitivity * ( m_prevMouseX - cx ) / m_camera->getWidth(); Scalar py = m_cameraSensitivity * ( cy - m_prevMouseY ) / m_camera->getHeight(); Scalar dx = m_cameraSensitivity * ( x - cx ) / m_camera->getWidth(); Scalar dy = m_cameraSensitivity * ( cy - y ) / m_camera->getHeight(); const Ra::Core::Vector3 p1( px, py, projectOnBall( px, py ) ); const Ra::Core::Vector3 p2( dx, dy, projectOnBall( dx, dy ) ); // Approximation of rotation angle // Should be divided by the projectOnBall size, but it is 1.0 Ra::Core::Vector3 axis = p2.cross( p1 ); if ( axis.norm() > 10_ra * Ra::Core::Math::machineEps ) { const Scalar angle = 5.0 * asin( sqrt( axis.squaredNorm() / p1.squaredNorm() / p2.squaredNorm() ) ); return Ra::Core::Quaternion( Ra::Core::AngleAxis( angle, axis.normalized() ) ); } return Ra::Core::Quaternion {0_ra, 0_ra, 0_ra, 1_ra}; } void RotateAroundCameraManipulator::handleCameraForward( Scalar z ) { Ra::Core::Vector3 trans = m_camera->getDirection() * z; Ra::Core::Transform transfo( Ra::Core::Transform::Identity() ); transfo.translate( trans ); m_camera->applyTransform( transfo ); } void RotateAroundCameraManipulator::handleCameraPan( Scalar dx, Scalar dy ) { Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra; Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra; // Move camera and trackball center, keep the distance to the center Ra::Core::Vector3 R = -m_camera->getRightVector(); Ra::Core::Vector3 U = m_camera->getUpVector(); Ra::Core::Transform T( Ra::Core::Transform::Identity() ); Ra::Core::Vector3 t = x * R + y * U; T.translate( t ); m_target += t; m_camera->applyTransform( T ); } } // namespace Gui } // namespace Ra <commit_msg>[format][gui] fix StatementMacro indent.<commit_after>#include <Core/Types.hpp> #include <Engine/Rendering/Renderer.hpp> #include <Engine/Scene/Light.hpp> #include <Gui/Utils/KeyMappingManager.hpp> #include <Gui/Viewer/RotateAroundCameraManipulator.hpp> #include <Gui/Viewer/Viewer.hpp> namespace Ra { namespace Gui { using namespace Ra::Core::Utils; using RotateAroundCameraMapping = KeyMappingManageable<RotateAroundCameraManipulator>; #define KMA_VALUE( XX ) KeyMappingManager::KeyMappingAction RotateAroundCameraManipulator::XX; KeyMappingRotateAroundCamera #undef KMA_VALUE void RotateAroundCameraManipulator::configureKeyMapping_impl() { auto keyMappingManager = Gui::KeyMappingManager::getInstance(); thisKeyMapping::setContext( KeyMappingManager::getInstance()->getContext( "CameraContext" ) ); if ( thisKeyMapping::getContext().isInvalid() ) { LOG( logINFO ) << "CameraContext not defined (maybe the configuration file do not contains it)"; LOG( logERROR ) << "CameraContext all keymapping invalide !"; return; } #define KMA_VALUE( XX ) XX = keyMappingManager->getActionIndex( thisKeyMapping::getContext(), #XX ); KeyMappingRotateAroundCamera #undef KMA_VALUE } void rotateAroundPoint( Ra::Core::Asset::Camera* cam, Ra::Core::Vector3& target, Ra::Core::Quaternion& rotation, const Ra::Core::Vector3& point ) { Ra::Core::Vector3 t = cam->getPosition(); Scalar l = ( target - t ).norm(); Ra::Core::Transform inverseCamRotateAround; Ra::Core::AngleAxis aa0 {rotation}; Ra::Core::AngleAxis aa1 {aa0.angle(), ( cam->getFrame().linear() * aa0.axis() ).normalized()}; inverseCamRotateAround.setIdentity(); inverseCamRotateAround.rotate( aa1 ); cam->applyTransform( inverseCamRotateAround ); Ra::Core::Vector3 trans = point + inverseCamRotateAround * ( t - point ); cam->setPosition( trans ); target = cam->getPosition() + l * cam->getDirection(); return; } RotateAroundCameraManipulator::RotateAroundCameraManipulator( const CameraManipulator& cm, Ra::Gui::Viewer* viewer ) : TrackballCameraManipulator( cm ), m_viewer( viewer ) {} bool RotateAroundCameraManipulator::handleMouseMoveEvent( QMouseEvent* event, const Qt::MouseButtons& /*buttons*/, const Qt::KeyboardModifiers& /* modifiers*/, int /*key*/ ) { Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth(); Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight(); m_lastMouseX = event->pos().x(); m_lastMouseY = event->pos().y(); if ( event->modifiers().testFlag( Qt::AltModifier ) ) { m_quickCameraModifier = 10.0_ra; } else { m_quickCameraModifier = 2.0_ra; } if ( m_currentAction == TRACKBALLCAMERA_ROTATE ) { handleCameraRotate( event->pos().x(), event->pos().y() ); } else if ( m_currentAction == TRACKBALLCAMERA_PAN ) handleCameraPan( dx, dy ); else if ( m_currentAction == TRACKBALLCAMERA_ZOOM ) handleCameraZoom( dx, dy ); else if ( m_currentAction == TRACKBALLCAMERA_MOVE_FORWARD ) handleCameraMoveForward( dx, dy ); // { handleCameraForward( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) ); // } m_prevMouseX = m_lastMouseX; m_prevMouseY = m_lastMouseY; if ( m_light != nullptr ) { m_light->setPosition( m_camera->getPosition() ); m_light->setDirection( m_camera->getDirection() ); } return m_currentAction.isValid(); } bool RotateAroundCameraManipulator::handleKeyPressEvent( QKeyEvent* /*event*/, const Ra::Gui::KeyMappingManager::KeyMappingAction& action ) { if ( action == ROTATEAROUND_ALIGN_WITH_CLOSEST_AXIS ) { alignOnClosestAxis(); return true; } if ( action == ROTATEAROUND_SET_PIVOT ) { setPivotFromPixel( m_lastMouseX, m_lastMouseY ); return true; } return false; } void RotateAroundCameraManipulator::setPivot( Ra::Core::Vector3 pivot ) { m_pivot = pivot; } void RotateAroundCameraManipulator::setPivotFromPixel( Scalar x, Scalar y ) { m_viewer->makeCurrent(); Scalar z = m_viewer->getRenderer()->getDepth( x, m_viewer->height() - y ); setPivot( m_camera->unProjectFromScreen( Ra::Core::Vector3( x, y, z ) ) ); m_viewer->doneCurrent(); } void RotateAroundCameraManipulator::alignOnClosestAxis() { Ra::Core::Vector3 x( 1_ra, 0_ra, 0_ra ); Ra::Core::Vector3 y( 0_ra, 1_ra, 0_ra ); Ra::Core::Vector3 z( 0_ra, 0_ra, 1_ra ); Ra::Core::Vector3 oldDirection, newDirection = m_camera->getDirection(); Ra::Core::Vector3 newUpVector = m_camera->getUpVector(); // getFrame().inverse() is a transform we can apply on Vector3 Ra::Core::Vector3 pivotInCamSpace = m_camera->getFrame().inverse() * m_pivot; auto updateMaxAndAxis = []( Ra::Core::Vector3 ref, Ra::Core::Vector3 axis, Ra::Core::Vector3& out, Scalar& max ) { Scalar d = ref.dot( axis ); if ( d > max ) { max = d; out = axis; } }; Scalar max = 0_ra; Ra::Core::Vector3 ref = m_camera->getDirection(); for ( auto axis : std::vector<Ra::Core::Vector3> {-x, x, -y, y, -z, z} ) { updateMaxAndAxis( ref, axis, newDirection, max ); } m_camera->setDirection( newDirection ); max = 0_ra; ref = m_camera->getUpVector(); for ( auto axis : std::vector<Ra::Core::Vector3> {-x, x, -y, y, -z, z} ) { updateMaxAndAxis( ref, axis, newUpVector, max ); } m_camera->setUpVector( newUpVector ); Ra::Core::Vector3 newPivot = m_camera->getFrame() * pivotInCamSpace; Ra::Core::Vector3 trans = m_pivot - newPivot; m_camera->setPosition( m_camera->getPosition() + trans ); if ( m_light != nullptr ) { m_light->setPosition( m_camera->getPosition() ); m_light->setDirection( m_camera->getDirection() ); } } void RotateAroundCameraManipulator::handleCameraRotate( Scalar x, Scalar y ) { Ra::Core::Vector3 trans = m_camera->projectToScreen( m_pivot ); Ra::Core::Quaternion rot = deformedBallQuaternion( x, y, trans[0], trans[1] ); Ra::Core::Vector3 pivot = m_pivot; rotateAroundPoint( m_camera, m_target, rot, pivot ); } Scalar RotateAroundCameraManipulator::projectOnBall( Scalar x, Scalar y ) { const Scalar size = 1.0; const Scalar size2 = size * size; const Scalar size_limit = size2 * 0.5; const Scalar d = x * x + y * y; return d < size_limit ? sqrt( size2 - d ) : size_limit / sqrt( d ); } Ra::Core::Quaternion RotateAroundCameraManipulator::deformedBallQuaternion( Scalar x, Scalar y, Scalar cx, Scalar cy ) { // Points on the deformed ball Scalar px = m_cameraSensitivity * ( m_prevMouseX - cx ) / m_camera->getWidth(); Scalar py = m_cameraSensitivity * ( cy - m_prevMouseY ) / m_camera->getHeight(); Scalar dx = m_cameraSensitivity * ( x - cx ) / m_camera->getWidth(); Scalar dy = m_cameraSensitivity * ( cy - y ) / m_camera->getHeight(); const Ra::Core::Vector3 p1( px, py, projectOnBall( px, py ) ); const Ra::Core::Vector3 p2( dx, dy, projectOnBall( dx, dy ) ); // Approximation of rotation angle // Should be divided by the projectOnBall size, but it is 1.0 Ra::Core::Vector3 axis = p2.cross( p1 ); if ( axis.norm() > 10_ra * Ra::Core::Math::machineEps ) { const Scalar angle = 5.0 * asin( sqrt( axis.squaredNorm() / p1.squaredNorm() / p2.squaredNorm() ) ); return Ra::Core::Quaternion( Ra::Core::AngleAxis( angle, axis.normalized() ) ); } return Ra::Core::Quaternion {0_ra, 0_ra, 0_ra, 1_ra}; } void RotateAroundCameraManipulator::handleCameraForward( Scalar z ) { Ra::Core::Vector3 trans = m_camera->getDirection() * z; Ra::Core::Transform transfo( Ra::Core::Transform::Identity() ); transfo.translate( trans ); m_camera->applyTransform( transfo ); } void RotateAroundCameraManipulator::handleCameraPan( Scalar dx, Scalar dy ) { Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra; Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra; // Move camera and trackball center, keep the distance to the center Ra::Core::Vector3 R = -m_camera->getRightVector(); Ra::Core::Vector3 U = m_camera->getUpVector(); Ra::Core::Transform T( Ra::Core::Transform::Identity() ); Ra::Core::Vector3 t = x * R + y * U; T.translate( t ); m_target += t; m_camera->applyTransform( T ); } } // namespace Gui } // namespace Ra <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "boost/format.hpp" #include "maya/MSyntax.h" #include "maya/MArgParser.h" #include "maya/MStringArray.h" #include "maya/MFnDagNode.h" #include "maya/MSelectionList.h" #include "IECore/CompoundParameter.h" #include "IECore/AttributeBlock.h" #include "IECoreRI/Renderer.h" #include "IECoreRI/Convert.h" #include "IECoreMaya/DelightProceduralCacheCommand.h" #include "IECoreMaya/ProceduralHolder.h" #include "IECoreMaya/PythonCmd.h" #include "IECoreMaya/Convert.h" #include "ri.h" #define STRINGIFY( ARG ) STRINGIFY2( ARG ) #define STRINGIFY2( ARG ) #ARG using namespace boost::python; using namespace IECoreMaya; DelightProceduralCacheCommand::ProceduralMap DelightProceduralCacheCommand::g_procedurals; DelightProceduralCacheCommand::DelightProceduralCacheCommand() { } DelightProceduralCacheCommand::~DelightProceduralCacheCommand() { } void *DelightProceduralCacheCommand::creator() { return new DelightProceduralCacheCommand; } MSyntax DelightProceduralCacheCommand::newSyntax() { MSyntax syn; MStatus s; s = syn.addFlag( "-a", "-addstep" ); assert(s); s = syn.addFlag( "-e", "-emit" ); assert(s); s = syn.addFlag( "-f", "-flush" ); assert(s); s = syn.addFlag( "-r", "-remove" ); assert(s); s = syn.addFlag( "-l", "-list" ); assert(s); s = syn.addFlag( "-st", "-sampleTime", MSyntax::kDouble ); assert(s); syn.setObjectType( MSyntax::kStringObjects ); return syn; } MStatus DelightProceduralCacheCommand::doIt( const MArgList &args ) { MArgParser parser( syntax(), args ); MStatus s; if( parser.isFlagSet( "-a" ) ) { MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } MSelectionList sel; sel.add( objectNames[0] ); MObject oDepNode; s = sel.getDependNode( 0, oDepNode ); if( !s ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get dependency node for \"" + objectNames[0] + "\"." ); return s; } MFnDagNode fnDagNode( oDepNode ); IECoreMaya::ProceduralHolder *pHolder = dynamic_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() ); if( !pHolder ) { displayError( "DelightProceduralCacheCommand::doIt : \"" + objectNames[0] + "\" is not a procedural holder node." ); return MStatus::kFailure; } ProceduralMap::iterator pIt = g_procedurals.find( objectNames[0].asChar() ); if( pIt!=g_procedurals.end() ) { // we already got the procedural on the first sample, but we should expand the bounding box for this sample pIt->second.bound.extendBy( IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ) ); return MStatus::kSuccess; } else { pHolder->setParameterisedValues(); // we're relying on nothing setting different values between now and the time we emit the procedural CachedProcedural cachedProcedural; cachedProcedural.procedural = pHolder->getProcedural( &cachedProcedural.className, &cachedProcedural.classVersion ); if( !cachedProcedural.procedural ) { displayError( "DelightProceduralCacheCommand::doIt : failed to get procedural from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } cachedProcedural.bound = IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ); IECore::ObjectPtr values = cachedProcedural.procedural->parameters()->getValue(); if( !values ) { displayError( "DelightProceduralCacheCommand::doIt : failed to get parameter values from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } cachedProcedural.values = values->copy(); g_procedurals[objectNames[0].asChar()] = cachedProcedural; } return MStatus::kSuccess; } else if( parser.isFlagSet( "-l" ) ) { MStringArray result; for( ProceduralMap::const_iterator it=g_procedurals.begin(); it!=g_procedurals.end(); it++ ) { result.append( it->first.c_str() ); } setResult( result ); return MStatus::kSuccess; } else if( parser.isFlagSet( "-e" ) ) { // get the object name MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } // get the cached procedural ProceduralMap::const_iterator it = g_procedurals.find( objectNames[0].asChar() ); if( it==g_procedurals.end() ) { displayError( "DelightProceduralCacheCommand::doIt : unable to emit \"" + objectNames[0] + "\" as object has not been cached." ); return MS::kFailure; } // and output it try { IECore::ObjectPtr currentValues = it->second.procedural->parameters()->getValue(); it->second.procedural->parameters()->setValue( it->second.values ); std::string pythonString; try { // we first get an object referencing the serialise result and then make an extractor for it. // making the extractor directly from the return of the serialise call seems to result // in the python object dying before we properly extract the value, which results in corrupted // strings, and therefore malformed ribs. object serialisedResultObject = PythonCmd::globalContext()["IECore"].attr("ParameterParser")().attr("serialise")( it->second.procedural->parameters() ); extract<std::string> serialisedResultExtractor( serialisedResultObject ); std::string serialisedParameters = serialisedResultExtractor(); pythonString = boost::str( boost::format( "IECoreRI.executeProcedural( \"%s\", %d, \"%s\" )" ) % it->second.className % it->second.classVersion % serialisedParameters ); } catch( ... ) { // Make sure we don't lose the 'current' values if we except. it->second.procedural->parameters()->setValue( currentValues ); displayError( "DelightProceduralCacheCommand::doIt : could not get parameters from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } // Put the current values back. it->second.procedural->parameters()->setValue( currentValues ); if( it->second.bound.isEmpty() ) { displayWarning( "DelightProceduralCacheCommand::doIt : not outputting procedural \"" + objectNames[0] + "\" because it has an empty bounding box." ); return MS::kSuccess; } RtBound rtBound; IECore::convert( it->second.bound, rtBound ); IECore::RendererPtr renderer = new IECoreRI::Renderer(); IECore::AttributeBlock attributeBlock( renderer, 1 ); it->second.procedural->render( renderer.get(), false, true, false, false ); // tell 3delight we can't run multiple python procedurals concurrently int zero = 0; RiAttribute( "procedural", "integer reentrant", &zero, 0 ); const char **data = (const char **)malloc( sizeof( char * ) * 2 ); data[0] = STRINGIFY( IECORERI_RMANPROCEDURAL_NAME ); data[1] = pythonString.c_str(); RiProcedural( data, rtBound, RiProcDynamicLoad, RiProcFree ); } catch( error_already_set ) { PyErr_Print(); displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } catch( ... ) { displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } return MStatus::kSuccess; } else if( parser.isFlagSet( "-r" ) ) { MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } g_procedurals.erase( objectNames[0].asChar() ); return MStatus::kSuccess; } else if( parser.isFlagSet( "-f" ) ) { g_procedurals.clear(); return MStatus::kSuccess; } displayError( "DelightProceduralCacheCommand::doIt : No suitable flag specified." ); return MS::kFailure; } <commit_msg>Removed comment which is no longer true.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "boost/format.hpp" #include "maya/MSyntax.h" #include "maya/MArgParser.h" #include "maya/MStringArray.h" #include "maya/MFnDagNode.h" #include "maya/MSelectionList.h" #include "IECore/CompoundParameter.h" #include "IECore/AttributeBlock.h" #include "IECoreRI/Renderer.h" #include "IECoreRI/Convert.h" #include "IECoreMaya/DelightProceduralCacheCommand.h" #include "IECoreMaya/ProceduralHolder.h" #include "IECoreMaya/PythonCmd.h" #include "IECoreMaya/Convert.h" #include "ri.h" #define STRINGIFY( ARG ) STRINGIFY2( ARG ) #define STRINGIFY2( ARG ) #ARG using namespace boost::python; using namespace IECoreMaya; DelightProceduralCacheCommand::ProceduralMap DelightProceduralCacheCommand::g_procedurals; DelightProceduralCacheCommand::DelightProceduralCacheCommand() { } DelightProceduralCacheCommand::~DelightProceduralCacheCommand() { } void *DelightProceduralCacheCommand::creator() { return new DelightProceduralCacheCommand; } MSyntax DelightProceduralCacheCommand::newSyntax() { MSyntax syn; MStatus s; s = syn.addFlag( "-a", "-addstep" ); assert(s); s = syn.addFlag( "-e", "-emit" ); assert(s); s = syn.addFlag( "-f", "-flush" ); assert(s); s = syn.addFlag( "-r", "-remove" ); assert(s); s = syn.addFlag( "-l", "-list" ); assert(s); s = syn.addFlag( "-st", "-sampleTime", MSyntax::kDouble ); assert(s); syn.setObjectType( MSyntax::kStringObjects ); return syn; } MStatus DelightProceduralCacheCommand::doIt( const MArgList &args ) { MArgParser parser( syntax(), args ); MStatus s; if( parser.isFlagSet( "-a" ) ) { MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } MSelectionList sel; sel.add( objectNames[0] ); MObject oDepNode; s = sel.getDependNode( 0, oDepNode ); if( !s ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get dependency node for \"" + objectNames[0] + "\"." ); return s; } MFnDagNode fnDagNode( oDepNode ); IECoreMaya::ProceduralHolder *pHolder = dynamic_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() ); if( !pHolder ) { displayError( "DelightProceduralCacheCommand::doIt : \"" + objectNames[0] + "\" is not a procedural holder node." ); return MStatus::kFailure; } ProceduralMap::iterator pIt = g_procedurals.find( objectNames[0].asChar() ); if( pIt!=g_procedurals.end() ) { // we already got the procedural on the first sample, but we should expand the bounding box for this sample pIt->second.bound.extendBy( IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ) ); return MStatus::kSuccess; } else { pHolder->setParameterisedValues(); CachedProcedural cachedProcedural; cachedProcedural.procedural = pHolder->getProcedural( &cachedProcedural.className, &cachedProcedural.classVersion ); if( !cachedProcedural.procedural ) { displayError( "DelightProceduralCacheCommand::doIt : failed to get procedural from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } cachedProcedural.bound = IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ); IECore::ObjectPtr values = cachedProcedural.procedural->parameters()->getValue(); if( !values ) { displayError( "DelightProceduralCacheCommand::doIt : failed to get parameter values from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } cachedProcedural.values = values->copy(); g_procedurals[objectNames[0].asChar()] = cachedProcedural; } return MStatus::kSuccess; } else if( parser.isFlagSet( "-l" ) ) { MStringArray result; for( ProceduralMap::const_iterator it=g_procedurals.begin(); it!=g_procedurals.end(); it++ ) { result.append( it->first.c_str() ); } setResult( result ); return MStatus::kSuccess; } else if( parser.isFlagSet( "-e" ) ) { // get the object name MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } // get the cached procedural ProceduralMap::const_iterator it = g_procedurals.find( objectNames[0].asChar() ); if( it==g_procedurals.end() ) { displayError( "DelightProceduralCacheCommand::doIt : unable to emit \"" + objectNames[0] + "\" as object has not been cached." ); return MS::kFailure; } // and output it try { IECore::ObjectPtr currentValues = it->second.procedural->parameters()->getValue(); it->second.procedural->parameters()->setValue( it->second.values ); std::string pythonString; try { // we first get an object referencing the serialise result and then make an extractor for it. // making the extractor directly from the return of the serialise call seems to result // in the python object dying before we properly extract the value, which results in corrupted // strings, and therefore malformed ribs. object serialisedResultObject = PythonCmd::globalContext()["IECore"].attr("ParameterParser")().attr("serialise")( it->second.procedural->parameters() ); extract<std::string> serialisedResultExtractor( serialisedResultObject ); std::string serialisedParameters = serialisedResultExtractor(); pythonString = boost::str( boost::format( "IECoreRI.executeProcedural( \"%s\", %d, \"%s\" )" ) % it->second.className % it->second.classVersion % serialisedParameters ); } catch( ... ) { // Make sure we don't lose the 'current' values if we except. it->second.procedural->parameters()->setValue( currentValues ); displayError( "DelightProceduralCacheCommand::doIt : could not get parameters from \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } // Put the current values back. it->second.procedural->parameters()->setValue( currentValues ); if( it->second.bound.isEmpty() ) { displayWarning( "DelightProceduralCacheCommand::doIt : not outputting procedural \"" + objectNames[0] + "\" because it has an empty bounding box." ); return MS::kSuccess; } RtBound rtBound; IECore::convert( it->second.bound, rtBound ); IECore::RendererPtr renderer = new IECoreRI::Renderer(); IECore::AttributeBlock attributeBlock( renderer, 1 ); it->second.procedural->render( renderer.get(), false, true, false, false ); // tell 3delight we can't run multiple python procedurals concurrently int zero = 0; RiAttribute( "procedural", "integer reentrant", &zero, 0 ); const char **data = (const char **)malloc( sizeof( char * ) * 2 ); data[0] = STRINGIFY( IECORERI_RMANPROCEDURAL_NAME ); data[1] = pythonString.c_str(); RiProcedural( data, rtBound, RiProcDynamicLoad, RiProcFree ); } catch( error_already_set ) { PyErr_Print(); displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } catch( ... ) { displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." ); return MStatus::kFailure; } return MStatus::kSuccess; } else if( parser.isFlagSet( "-r" ) ) { MStringArray objectNames; s = parser.getObjects( objectNames ); if( !s || objectNames.length()!=1 ) { displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." ); return s; } g_procedurals.erase( objectNames[0].asChar() ); return MStatus::kSuccess; } else if( parser.isFlagSet( "-f" ) ) { g_procedurals.clear(); return MStatus::kSuccess; } displayError( "DelightProceduralCacheCommand::doIt : No suitable flag specified." ); return MS::kFailure; } <|endoftext|>
<commit_before>/**@file @brief Elements for Mobility Management messages, GSM 04.08 9.2. */ /* * Copyright 2008, 2014 Free Software Foundation, Inc. * Copyright 2010 Kestrel Signal Processing, Inc. * Copyright 2014 Range Networks, Inc. * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribuion. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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. */ #include <time.h> #include "GSML3MMElements.h" #include <Logger.h> using namespace std; using namespace GSM; void L3TimeZoneAndTime::writeV(L3Frame& dest, size_t& wp) const { // See GSM 03.40 9.2.3.11. // Convert from seconds since Jan 1, 1970 to calendar time. struct tm fields; const time_t seconds = mTime.sec(); if (mType == LOCAL_TIME) { localtime_r(&seconds,&fields); } else { gmtime_r(&seconds,&fields); } // Write the fields in BCD format. // year unsigned year = fields.tm_year % 100; dest.writeField(wp, year % 10, 4); dest.writeField(wp, year / 10, 4); // month unsigned month = fields.tm_mon + 1; dest.writeField(wp, month % 10, 4); dest.writeField(wp, month / 10, 4); // day dest.writeField(wp, fields.tm_mday % 10, 4); dest.writeField(wp, fields.tm_mday / 10, 4); // hour dest.writeField(wp, fields.tm_hour % 10, 4); dest.writeField(wp, fields.tm_hour / 10, 4); // minute dest.writeField(wp, fields.tm_min % 10, 4); dest.writeField(wp, fields.tm_min / 10, 4); // second dest.writeField(wp, fields.tm_sec % 10, 4); dest.writeField(wp, fields.tm_sec / 10, 4); // time zone, in 1/4 steps with a sign bit int zone; if (mType == LOCAL_TIME) { zone = fields.tm_gmtoff; } else { // At least under Linux gmtime_r() does not return timezone // information for some reason and we have to use localtime_r() // to reptrieve this information. struct tm fields_local; localtime_r(&seconds,&fields_local); zone = fields_local.tm_gmtoff; } zone = zone / (15*60); unsigned zoneSign = (zone < 0); zone = abs(zone); dest.writeField(wp, zone % 10, 4); dest.writeField(wp, zoneSign, 1); dest.writeField(wp, zone / 10, 3); LOG(DEBUG) << "year=" << year << " month=" << month << " day=" << fields.tm_mday << " hour=" << fields.tm_hour << " min=" << fields.tm_min << " sec=" << fields.tm_sec << " zone=" << (zoneSign?"-":"+") << zone; } void L3TimeZoneAndTime::parseV(const L3Frame& src, size_t& rp) { // See GSM 03.40 9.2.3.11. // Read it all into a localtime struct tm, // then covert to Unix seconds. struct tm fields; // year fields.tm_year = 2000 + src.readField(rp,4) + src.readField(rp,4)*10; // month fields.tm_mon = 1 + src.readField(rp,4) + src.readField(rp,4)*10; // day fields.tm_mday = src.readField(rp,4) + src.readField(rp,4)*10; // hour fields.tm_hour = src.readField(rp,4) + src.readField(rp,4)*10; // minute fields.tm_min = src.readField(rp,4) + src.readField(rp,4)*10; // second fields.tm_sec = src.readField(rp,4) + src.readField(rp,4)*10; // zone unsigned zone = src.readField(rp,4); unsigned zoneSign = src.readField(rp,1); zone += 10*src.readField(rp,4); if (zoneSign) zone = -zone; fields.tm_gmtoff = zone * 15 * 60; // convert mTime = Timeval(timegm(&fields),0); } void L3TimeZoneAndTime::text(ostream& os) const { //char timeStr[26]; const time_t seconds = mTime.sec(); std::string timeStr; Timeval::isoTime(seconds, timeStr, true); //ctime_r(&seconds,timeStr); //timeStr[24]='\0'; os << timeStr << " (local)"; } // vim: ts=4 sw=4 <commit_msg>fixes issue loading some 0-length SMS. Turns out that we were taking one extra bit off of the time field of the message incorrectly. Also resolved some time conversion issues in the same funcion.<commit_after>/**@file @brief Elements for Mobility Management messages, GSM 04.08 9.2. */ /* * Copyright 2008, 2014 Free Software Foundation, Inc. * Copyright 2010 Kestrel Signal Processing, Inc. * Copyright 2014 Range Networks, Inc. * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribuion. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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. */ #include <time.h> #include "GSML3MMElements.h" #include <Logger.h> using namespace std; using namespace GSM; void L3TimeZoneAndTime::writeV(L3Frame& dest, size_t& wp) const { // See GSM 03.40 9.2.3.11. // Convert from seconds since Jan 1, 1970 to calendar time. struct tm fields; const time_t seconds = mTime.sec(); if (mType == LOCAL_TIME) { localtime_r(&seconds,&fields); } else { gmtime_r(&seconds,&fields); } // Write the fields in BCD format. // year unsigned year = fields.tm_year % 100; dest.writeField(wp, year % 10, 4); dest.writeField(wp, year / 10, 4); // month unsigned month = fields.tm_mon + 1; dest.writeField(wp, month % 10, 4); dest.writeField(wp, month / 10, 4); // day dest.writeField(wp, fields.tm_mday % 10, 4); dest.writeField(wp, fields.tm_mday / 10, 4); // hour dest.writeField(wp, fields.tm_hour % 10, 4); dest.writeField(wp, fields.tm_hour / 10, 4); // minute dest.writeField(wp, fields.tm_min % 10, 4); dest.writeField(wp, fields.tm_min / 10, 4); // second dest.writeField(wp, fields.tm_sec % 10, 4); dest.writeField(wp, fields.tm_sec / 10, 4); // time zone, in 1/4 steps with a sign bit int zone; if (mType == LOCAL_TIME) { zone = fields.tm_gmtoff; } else { // At least under Linux gmtime_r() does not return timezone // information for some reason and we have to use localtime_r() // to reptrieve this information. struct tm fields_local; localtime_r(&seconds,&fields_local); zone = fields_local.tm_gmtoff; } zone = zone / (15*60); unsigned zoneSign = (zone < 0); zone = abs(zone); dest.writeField(wp, zone % 10, 4); dest.writeField(wp, zoneSign, 1); dest.writeField(wp, zone / 10, 3); LOG(DEBUG) << "year=" << year << " month=" << month << " day=" << fields.tm_mday << " hour=" << fields.tm_hour << " min=" << fields.tm_min << " sec=" << fields.tm_sec << " zone=" << (zoneSign?"-":"+") << zone; } void L3TimeZoneAndTime::parseV(const L3Frame& src, size_t& rp) { // See GSM 03.40 9.2.3.11. // Read it all into a localtime struct tm, // then covert to Unix seconds. struct tm fields; // years since 1900 fields.tm_year = 100 + src.readField(rp,4) + src.readField(rp,4)*10; // month fields.tm_mon = src.readField(rp,4) + src.readField(rp,4)*10; // day fields.tm_mday = src.readField(rp,4) + src.readField(rp,4)*10; // hour fields.tm_hour = src.readField(rp,4) + src.readField(rp,4)*10; // minute fields.tm_min = src.readField(rp,4) + src.readField(rp,4)*10; // second fields.tm_sec = src.readField(rp,4) + src.readField(rp,4)*10; // zone unsigned zone = src.readField(rp,4); unsigned zoneSign = src.readField(rp,1); zone += 10*src.readField(rp,3); if (zoneSign) zone = -zone; fields.tm_gmtoff = zone * 15 * 60; // convert mTime = Timeval(timegm(&fields),0); } void L3TimeZoneAndTime::text(ostream& os) const { //char timeStr[26]; const time_t seconds = mTime.sec(); std::string timeStr; Timeval::isoTime(seconds, timeStr, true); //ctime_r(&seconds,timeStr); //timeStr[24]='\0'; os << timeStr << " (local)"; } // vim: ts=4 sw=4 <|endoftext|>
<commit_before>#include "stdafx.h" #include "cartrige.h" struct rom_header { u8 start_vector[4]; u8 nintendo_logo[48]; u8 game_title[11]; u8 manufacturer_code[4]; u8 cgb_flag; u8 new_license_code[2]; u8 sgb_flag; u8 cartrige_type; u8 rom_size; u8 ram_size; u8 destination_code; u8 old_license_code; u8 rom_version; u8 checksum; u8 global_checksum[2]; }; bool in_range(u32 value, u32 begin, u32 end) { return (value >= begin) && (value <= end); } u32 get_ram_size(u8 val) { assert(val < 6); static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 }; return sizes[val]; } Cartrige::~Cartrige() { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); if (battery_ram) save_ram_callback(ram.get(), ram_size); if (in_range(header->cartrige_type, 0x0F, 0x10)) { memory_interface.reset(); //make sure that MBC3 update rtc_regs auto epoch = std::chrono::system_clock::now().time_since_epoch(); auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch); save_rtc_callback(cur_timestamp, rtc_regs, 5); } } bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc) { if (!cart.is_open()) return false; cart.seekg(0, std::ios_base::end); size_t size = cart.tellg(); cart.seekg(0, std::ios_base::beg); rom = std::make_unique<u8[]>(size); cart.read(reinterpret_cast<char*>(rom.get()), size); load_or_create_ram(ram); load_rtc(rtc); dispatch(); return true; } std::string Cartrige::get_name() const { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); return std::string(std::begin(header->game_title), std::end(header->game_title)); } void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save) { save_ram_callback = ram_save; save_rtc_callback = rtc_save; } void Cartrige::load_or_create_ram(std::ifstream& ram_file) { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); //MBC2 has always header->ram_size == 0, but it has 512 bytes actually! if (in_range(header->cartrige_type, 0x05, 0x06)) ram_size = 512; else ram_size = get_ram_size(header->ram_size); ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr; switch (header->cartrige_type) { case 0x03: case 0x06: case 0x09: case 0x0D: case 0x0F: case 0x10: case 0x13: case 0x1B: case 0x1E: battery_ram = true; break; default: battery_ram = false; break; } if (battery_ram && ram_file.is_open()) ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size); } void Cartrige::load_rtc(std::ifstream& rtc_file) { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); if (in_range(header->cartrige_type, 0x0F, 0x10) && rtc_file.is_open()) { i64 saved_timestamp; rtc_file >> saved_timestamp; rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); auto epoch = std::chrono::system_clock::now().time_since_epoch(); auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch); auto delta = cur_timestamp.count() - saved_timestamp; if (delta <= 0 || check_bit(rtc_regs[4], 6)) return; auto ns = rtc_regs[0] + delta; auto nm = rtc_regs[1] + ns / 60; auto nh = rtc_regs[2] + nm / 60; auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24; rtc_regs[0] = ns % 60; rtc_regs[1] = nm % 60; rtc_regs[2] = nh % 24; rtc_regs[3] = (nd % 512) & 0xFF; rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0); rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7); } } IMemory* Cartrige::get_memory_controller() const { return memory_interface.get(); } IDmaMemory* Cartrige::get_dma_controller() const { return dma_interface; } bool Cartrige::is_cgb_ready() const { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0); } void Cartrige::serialize(std::ostream& stream) { //TODO: update rtc regs before serialization stream << battery_ram << ram_size; stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size); stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); } void Cartrige::deserialize(std::istream & stream) { stream >> battery_ram >> ram_size; stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size); stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); } void Cartrige::dispatch() { rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); u8 type = header->cartrige_type; if (type == 0x00 || type == 0x08 || type == 0x09) { auto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x01, 0x03)) { auto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x05, 0x06)) { auto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x0F, 0x13)) { auto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr))); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x1A, 0x1E)) { auto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else memory_interface = nullptr; } <commit_msg>added new MBC5 code<commit_after>#include "stdafx.h" #include "cartrige.h" struct rom_header { u8 start_vector[4]; u8 nintendo_logo[48]; u8 game_title[11]; u8 manufacturer_code[4]; u8 cgb_flag; u8 new_license_code[2]; u8 sgb_flag; u8 cartrige_type; u8 rom_size; u8 ram_size; u8 destination_code; u8 old_license_code; u8 rom_version; u8 checksum; u8 global_checksum[2]; }; bool in_range(u32 value, u32 begin, u32 end) { return (value >= begin) && (value <= end); } u32 get_ram_size(u8 val) { assert(val < 6); static const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 }; return sizes[val]; } Cartrige::~Cartrige() { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); if (battery_ram) save_ram_callback(ram.get(), ram_size); if (in_range(header->cartrige_type, 0x0F, 0x10)) { memory_interface.reset(); //make sure that MBC3 update rtc_regs auto epoch = std::chrono::system_clock::now().time_since_epoch(); auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch); save_rtc_callback(cur_timestamp, rtc_regs, 5); } } bool Cartrige::load_cartrige(std::ifstream& cart, std::ifstream& ram, std::ifstream& rtc) { if (!cart.is_open()) return false; cart.seekg(0, std::ios_base::end); size_t size = cart.tellg(); cart.seekg(0, std::ios_base::beg); rom = std::make_unique<u8[]>(size); cart.read(reinterpret_cast<char*>(rom.get()), size); load_or_create_ram(ram); load_rtc(rtc); dispatch(); return true; } std::string Cartrige::get_name() const { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); return std::string(std::begin(header->game_title), std::end(header->game_title)); } void Cartrige::attach_endpoints(function<void(const u8*, u32)> ram_save, function<void(std::chrono::seconds, const u8*, u32)> rtc_save) { save_ram_callback = ram_save; save_rtc_callback = rtc_save; } void Cartrige::load_or_create_ram(std::ifstream& ram_file) { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); //MBC2 has always header->ram_size == 0, but it has 512 bytes actually! if (in_range(header->cartrige_type, 0x05, 0x06)) ram_size = 512; else ram_size = get_ram_size(header->ram_size); ram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr; switch (header->cartrige_type) { case 0x03: case 0x06: case 0x09: case 0x0D: case 0x0F: case 0x10: case 0x13: case 0x1B: case 0x1E: battery_ram = true; break; default: battery_ram = false; break; } if (battery_ram && ram_file.is_open()) ram_file.read(reinterpret_cast<char*>(ram.get()), ram_size); } void Cartrige::load_rtc(std::ifstream& rtc_file) { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); if (in_range(header->cartrige_type, 0x0F, 0x10) && rtc_file.is_open()) { i64 saved_timestamp; rtc_file >> saved_timestamp; rtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); auto epoch = std::chrono::system_clock::now().time_since_epoch(); auto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch); auto delta = cur_timestamp.count() - saved_timestamp; if (delta <= 0 || check_bit(rtc_regs[4], 6)) return; auto ns = rtc_regs[0] + delta; auto nm = rtc_regs[1] + ns / 60; auto nh = rtc_regs[2] + nm / 60; auto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh / 24; rtc_regs[0] = ns % 60; rtc_regs[1] = nm % 60; rtc_regs[2] = nh % 24; rtc_regs[3] = (nd % 512) & 0xFF; rtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0); rtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7); } } IMemory* Cartrige::get_memory_controller() const { return memory_interface.get(); } IDmaMemory* Cartrige::get_dma_controller() const { return dma_interface; } bool Cartrige::is_cgb_ready() const { const rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); return (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0); } void Cartrige::serialize(std::ostream& stream) { //TODO: update rtc regs before serialization stream << battery_ram << ram_size; stream.write(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size); stream.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); } void Cartrige::deserialize(std::istream & stream) { stream >> battery_ram >> ram_size; stream.read(reinterpret_cast<char*>(ram.get()), sizeof(u8) * ram_size); stream.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5); } void Cartrige::dispatch() { rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]); u8 type = header->cartrige_type; if (type == 0x00 || type == 0x08 || type == 0x09) { auto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x01, 0x03)) { auto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x05, 0x06)) { auto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x0F, 0x13)) { auto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr))); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else if (in_range(type, 0x19, 0x1E)) { auto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get())); dma_interface = tmp.get(); memory_interface = std::move(tmp); } else memory_interface = nullptr; } <|endoftext|>
<commit_before>/** * lambdak.tcc - * @author: Jonathan Beard * @version: Thu Oct 30 10:12:36 2014 * * Copyright 2014 Jonathan Beard * * 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. */ #ifndef _LAMBDAK_TCC_ #define _LAMBDAK_TCC_ 1 #include <functional> #include <utility> #include <typeinfo> #include <raft> namespace raft { /** TODO, this needs some more error checking before production **/ /** pre-declare recursive struct / functions **/ template < class... PORTSL > struct AddPorts; template < class... PORTSK > struct AddSamePorts; template < class... PORTS > class lambdak : public raft::kernel { public: typedef std::function< raft::kstatus ( Port &input, Port &output ) > lambdafunc_t; lambdak( const std::size_t inputs, const std::size_t outputs, lambdafunc_t func ) : raft::kernel(), run_func( func ) { add_ports< PORTS... >( inputs, outputs ); } //lambdak( const std::size_t inputs, // const std::size_t outputs, // const lambdafunc_t &&func ) : raft::kernel(), // run_func( func ) //{ // add_ports< PORTS... >( inputs, outputs ); //} virtual raft::kstatus run() { return( run_func( input /** input ports **/, output /** output ports **/) ); } private: /** lambda func passed by user **/ lambdafunc_t run_func; /** function **/ template < class... PORTSM > void add_ports( const std::size_t input_max, const std::size_t output_max ) { const auto num_types( sizeof... (PORTSM) ); if( num_types == 1 ) { /** everybody gets same type, add here **/ AddSamePorts< PORTSM... >::add( input_max /* count */, input /* in-port obj */, output_max /* count */, output /* out-port obj */ ); } /** no idea what type each port is, throw error **/ else if( num_types != (input_max + output_max ) ) { /** TODO, make exception for here **/ assert( false ); } /** multiple port type case **/ std::size_t input_index( 0 ); std::size_t output_index( 0 ); AddPorts< PORTSM... >::add( input_index, input_max, input /* ports */, output_index, output_max, output /* ports */); } }; /** end template lambdak **/ /** class recursion **/ template < class PORT, class... PORTSL > struct AddPorts< PORT, PORTSL...> { static void add( std::size_t &input_index, const std::size_t input_max, Port &input_ports, std::size_t &output_index, const std::size_t output_max, Port &output_ports ) { if( input_index < input_max ) { /** add ports in order, 0,1,2, etc. **/ input_ports.addPort< PORT >( std::to_string( input_index++ ) ); AddPorts< PORTSL... >::add( input_index, input_max, input_ports, output_index, output_max, output_ports ); } else if( output_index < output_max ) { /** add ports in order, 0, 1, 2, etc. **/ output_ports.addPort< PORT >( std::to_string( output_index++ ) ); AddPorts< PORTSL... >::add( input_index, input_max, input_ports, output_index, output_max, output_ports ); } else { /** * I think it'll be okay here simply to return, however * we might need the blank specialization below */ } return; } }; template <> struct AddPorts<> { static void add( std::size_t &input_index, const std::size_t input_max, Port &input_ports, std::size_t &output_index, const std::size_t output_max, Port &output_ports ) { return; } }; /** single class type, no recursion **/ template < class PORT, class... PORTSK > struct AddSamePorts< PORT, PORTSK... > { /** no recursion needed here **/ static void add( const std::size_t input_count, Port &inputs, const std::size_t output_count, Port &outputs ) { for( auto it( 0 ); it < input_count; it++ ) { inputs.addPort< PORT >( std::to_string( it ) ); } for( auto it( 0 ); it < output_count; it++ ) { outputs.addPort< PORT >( std::to_string( it ) ); } } }; template <> struct AddSamePorts<> { static void add( const std::size_t input_count, Port &inputs, const std::size_t output_count, Port &outputs ) { return; } }; } /* end namespace raft */ #endif /* END _LAMBDAK_TCC_ */ <commit_msg>updates<commit_after>/** * lambdak.tcc - * @author: Jonathan Beard * @version: Thu Oct 30 10:12:36 2014 * * Copyright 2014 Jonathan Beard * * 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. */ #ifndef _LAMBDAK_TCC_ #define _LAMBDAK_TCC_ 1 #include <functional> #include <utility> #include <typeinfo> #include <raft> namespace raft { /** TODO, this needs some more error checking before production **/ /** pre-declare recursive struct / functions **/ template < class... PORTSL > struct AddPorts; template < class... PORTSK > struct AddSamePorts; template < class... PORTS > class lambdak : public raft::kernel { public: typedef std::function< raft::kstatus ( Port &input, Port &output ) > lambdafunc_t; /** * constructor - * @param inputs - const std::size_t number of inputs to the kernel * @param outputs - const std::size_t number of outputs to the kernel * @param func - static or lambda function to execute. */ lambdak( const std::size_t inputs, const std::size_t outputs, lambdafunc_t func ) : raft::kernel(), run_func( func ) { add_ports< PORTS... >( inputs, outputs ); } /** * run - implement the run function for this kernel, */ virtual raft::kstatus run() { return( run_func( input /** input ports **/, output /** output ports **/) ); } private: /** lambda func passed by user **/ lambdafunc_t run_func; /** function **/ template < class... PORTSM > void add_ports( const std::size_t input_max, const std::size_t output_max ) { const auto num_types( sizeof... (PORTSM) ); if( num_types == 1 ) { /** everybody gets same type, add here **/ AddSamePorts< PORTSM... >::add( input_max /* count */, input /* in-port obj */, output_max /* count */, output /* out-port obj */ ); } /** no idea what type each port is, throw error **/ else if( num_types != (input_max + output_max ) ) { /** TODO, make exception for here **/ assert( false ); } /** multiple port type case **/ std::size_t input_index( 0 ); std::size_t output_index( 0 ); AddPorts< PORTSM... >::add( input_index, input_max, input /* ports */, output_index, output_max, output /* ports */); } }; /** end template lambdak **/ /** class recursion **/ template < class PORT, class... PORTSL > struct AddPorts< PORT, PORTSL...> { static void add( std::size_t &input_index, const std::size_t input_max, Port &input_ports, std::size_t &output_index, const std::size_t output_max, Port &output_ports ) { if( input_index < input_max ) { /** add ports in order, 0,1,2, etc. **/ input_ports.addPort< PORT >( std::to_string( input_index++ ) ); AddPorts< PORTSL... >::add( input_index, input_max, input_ports, output_index, output_max, output_ports ); } else if( output_index < output_max ) { /** add ports in order, 0, 1, 2, etc. **/ output_ports.addPort< PORT >( std::to_string( output_index++ ) ); AddPorts< PORTSL... >::add( input_index, input_max, input_ports, output_index, output_max, output_ports ); } else { /** * I think it'll be okay here simply to return, however * we might need the blank specialization below */ } return; } }; template <> struct AddPorts<> { static void add( std::size_t &input_index, const std::size_t input_max, Port &input_ports, std::size_t &output_index, const std::size_t output_max, Port &output_ports ) { return; } }; /** single class type, no recursion **/ template < class PORT, class... PORTSK > struct AddSamePorts< PORT, PORTSK... > { /** no recursion needed here **/ static void add( const std::size_t input_count, Port &inputs, const std::size_t output_count, Port &outputs ) { for( auto it( 0 ); it < input_count; it++ ) { inputs.addPort< PORT >( std::to_string( it ) ); } for( auto it( 0 ); it < output_count; it++ ) { outputs.addPort< PORT >( std::to_string( it ) ); } } }; template <> struct AddSamePorts<> { static void add( const std::size_t input_count, Port &inputs, const std::size_t output_count, Port &outputs ) { return; } }; } /* end namespace raft */ #endif /* END _LAMBDAK_TCC_ */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include "DataFmtTransl.hxx" #include <rtl/string.hxx> #include <osl/diagnose.h> #include <rtl/tencinfo.h> #include "../misc/ImplHelper.hxx" #include "../misc/WinClip.hxx" #include "MimeAttrib.hxx" #include "DTransHelper.hxx" #include <rtl/string.h> #include "Fetc.hxx" #if defined _MSC_VER #pragma warning(push,1) #pragma warning(disable:4917) #endif #include <windows.h> #if (_MSC_VER < 1300) && !defined(__MINGW32__) #include <olestd.h> #endif #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; using ::rtl::OUString; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; const OUString TEXT_PLAIN_CHARSET ("text/plain;charset="); const OUString HPNAME_OEM_ANSI_TEXT ("OEM/ANSI Text"); const OUString HTML_FORMAT_NAME_WINDOWS ("HTML Format"); const OUString HTML_FORMAT_NAME_SOFFICE ("HTML (HyperText Markup Language"); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString("com.sun.star.datatransfer.DataFormatTranslator") ), UNO_QUERY ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { if( m_XDataFormatTranslator.is( ) ) { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.hasValue( ) ) { if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_FAIL( "Wrong Any-Type detected" ); } } } catch( ... ) { OSL_FAIL( "Unexpected error" ); } return sal::static_int_cast<CFormatEtc>(getFormatEtcForClipformat( sal::static_int_cast<CLIPFORMAT>(cf) )); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const FORMATETC& aFormatEtc, LCID lcid ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextFormat( aClipformat ) ) { aFlavor.MimeType = TEXT_PLAIN_CHARSET; aFlavor.MimeType += getTextCharsetFromLCID( lcid, aClipformat ); aFlavor.HumanPresentableName = HPNAME_OEM_ANSI_TEXT; aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else if ( CF_INVALID != aClipformat ) { if ( m_XDataFormatTranslator.is( ) ) { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occurred or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } } catch( ... ) { OSL_FAIL( "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformatName( const OUString& aClipFmtName ) const { // check parameter if ( !aClipFmtName.getLength( ) ) return CFormatEtc( CF_INVALID ); CLIPFORMAT cf = sal::static_int_cast<CLIPFORMAT>(RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) )); return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, reinterpret_cast<LPWSTR>(wBuff), MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT ); switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL /*| TYMED_ISTREAM*/ ); } /* hack: in order to paste urls copied by Internet Explorer with "copy link" we set the lindex member to 0 but if we really want to support CFSTR_FILECONTENT and the accompany format CFSTR_FILEDESCRIPTOR (FileGroupDescriptor) the client of the clipboard service has to provide a id of which FileContents it wants to paste see MSDN: "Handling Shell Data Transfer Scenarios" */ if ( cf == RegisterClipboardFormatA( CFSTR_FILECONTENTS ) ) fetc.setLindex( 0 ); return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextFormat( CLIPFORMAT cf ) const { return ( (cf == CF_TEXT) || (cf == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isUnicodeTextFormat( CLIPFORMAT cf ) const { return ( cf == CF_UNICODETEXT ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextFormat( CLIPFORMAT cf ) const { return ( isOemOrAnsiTextFormat( cf ) || isUnicodeTextFormat( cf ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isHTMLFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName == HTML_FORMAT_NAME_WINDOWS ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextHtmlFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName.equalsIgnoreAsciiCase( HTML_FORMAT_NAME_SOFFICE ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextFormat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>I think, this is what was intended<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include "DataFmtTransl.hxx" #include <rtl/string.hxx> #include <osl/diagnose.h> #include <rtl/tencinfo.h> #include "../misc/ImplHelper.hxx" #include "../misc/WinClip.hxx" #include "MimeAttrib.hxx" #include "DTransHelper.hxx" #include <rtl/string.h> #include "Fetc.hxx" #if defined _MSC_VER #pragma warning(push,1) #pragma warning(disable:4917) #endif #include <windows.h> #if (_MSC_VER < 1300) && !defined(__MINGW32__) #include <olestd.h> #endif #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; using ::rtl::OUString; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; const OUString TEXT_PLAIN_CHARSET ("text/plain;charset="); const OUString HPNAME_OEM_ANSI_TEXT ("OEM/ANSI Text"); const OUString HTML_FORMAT_NAME_WINDOWS ("HTML Format"); const OUString HTML_FORMAT_NAME_SOFFICE ("HTML (HyperText Markup Language)"); //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString("com.sun.star.datatransfer.DataFormatTranslator") ), UNO_QUERY ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { if( m_XDataFormatTranslator.is( ) ) { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.hasValue( ) ) { if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_FAIL( "Wrong Any-Type detected" ); } } } catch( ... ) { OSL_FAIL( "Unexpected error" ); } return sal::static_int_cast<CFormatEtc>(getFormatEtcForClipformat( sal::static_int_cast<CLIPFORMAT>(cf) )); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const FORMATETC& aFormatEtc, LCID lcid ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextFormat( aClipformat ) ) { aFlavor.MimeType = TEXT_PLAIN_CHARSET; aFlavor.MimeType += getTextCharsetFromLCID( lcid, aClipformat ); aFlavor.HumanPresentableName = HPNAME_OEM_ANSI_TEXT; aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else if ( CF_INVALID != aClipformat ) { if ( m_XDataFormatTranslator.is( ) ) { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occurred or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } } catch( ... ) { OSL_FAIL( "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformatName( const OUString& aClipFmtName ) const { // check parameter if ( !aClipFmtName.getLength( ) ) return CFormatEtc( CF_INVALID ); CLIPFORMAT cf = sal::static_int_cast<CLIPFORMAT>(RegisterClipboardFormatW( reinterpret_cast<LPCWSTR>(aClipFmtName.getStr( )) )); return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, reinterpret_cast<LPWSTR>(wBuff), MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT ); switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL /*| TYMED_ISTREAM*/ ); } /* hack: in order to paste urls copied by Internet Explorer with "copy link" we set the lindex member to 0 but if we really want to support CFSTR_FILECONTENT and the accompany format CFSTR_FILEDESCRIPTOR (FileGroupDescriptor) the client of the clipboard service has to provide a id of which FileContents it wants to paste see MSDN: "Handling Shell Data Transfer Scenarios" */ if ( cf == RegisterClipboardFormatA( CFSTR_FILECONTENTS ) ) fetc.setLindex( 0 ); return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextFormat( CLIPFORMAT cf ) const { return ( (cf == CF_TEXT) || (cf == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isUnicodeTextFormat( CLIPFORMAT cf ) const { return ( cf == CF_UNICODETEXT ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextFormat( CLIPFORMAT cf ) const { return ( isOemOrAnsiTextFormat( cf ) || isUnicodeTextFormat( cf ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isHTMLFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName == HTML_FORMAT_NAME_WINDOWS ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CDataFormatTranslator::isTextHtmlFormat( CLIPFORMAT cf ) const { OUString clipFormatName = getClipboardFormatName( cf ); return ( clipFormatName.equalsIgnoreAsciiCase( HTML_FORMAT_NAME_SOFFICE ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromLCID( LCID lcid, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextFormat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "gcscpp_runner.h" #include <string> #include <thread> #include "absl/random/random.h" #include "absl/time/time.h" #include "google/cloud/storage/client.h" #include "google/cloud/storage/grpc_plugin.h" GcscppRunner::GcscppRunner(Parameters parameters, std::shared_ptr<RunnerWatcher> watcher) : parameters_(parameters), object_resolver_(parameters_.object, parameters_.object_format, parameters_.object_start, parameters_.object_stop), watcher_(watcher) {} static google::cloud::storage::Client CreateClient( const Parameters& parameters) { auto opts = google::cloud::Options{}; if (parameters.client == "gcscpp-grpc") { std::string target = parameters.host; if (parameters.td) { // TODO(veblush): Remove experimental suffix once this code is proven // stable. target = "google-c2p-experimental:///" + target; } return ::google::cloud::storage_experimental::DefaultGrpcClient( opts.set<google::cloud::storage_experimental::GrpcPluginOption>("media") .set<google::cloud::EndpointOption>(target)); } else { return ::google::cloud::storage::Client(); } } bool GcscppRunner::Run() { auto client = CreateClient(parameters_); // Spawns benchmark threads and waits until they're done. std::vector<std::thread> threads; std::vector<bool> returns(parameters_.threads); for (int i = 1; i <= parameters_.threads; i++) { int thread_id = i; threads.emplace_back([thread_id, client, &returns, this]() { returns[thread_id - 1] = this->DoOperation(thread_id, client); }); } std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); }); return std::all_of(returns.begin(), returns.end(), [](bool v) { return v; }); } bool GcscppRunner::DoOperation(int thread_id, google::cloud::storage::Client storage_client) { switch (parameters_.operation_type) { case OperationType::Read: return DoRead(thread_id, storage_client); case OperationType::RandomRead: return DoRandomRead(thread_id, storage_client); case OperationType::Write: return DoWrite(thread_id, storage_client); default: return false; } } std::string ExtractPeer( std::multimap<std::string, std::string> const& headers) { auto p = headers.find(":grpc-context-peer"); if (p == headers.end()) { p = headers.find(":curl-peer"); } return p == headers.end() ? "" : p->second; } bool GcscppRunner::DoRead(int thread_id, google::cloud::storage::Client storage_client) { std::vector<char> buffer(4 * 1024 * 1024); auto const buffer_size = static_cast<std::streamsize>(buffer.size()); for (int run = 0; run < parameters_.runs; run++) { std::string object = object_resolver_.Resolve(thread_id, run); absl::Time run_start = absl::Now(); auto reader = storage_client.ReadObject(parameters_.bucket, object); if (!reader) { std::cerr << "Error reading object: " << reader.status() << "\n"; return false; } int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); while (!reader.eof()) { reader.read(buffer.data(), buffer_size); int64_t content_size = reader.gcount(); RunnerWatcher::Chunk chunk = {absl::Now(), content_size}; chunks.push_back(chunk); total_bytes += content_size; } reader.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Read, thread_id, 0, ExtractPeer(reader.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, chunks); } return true; } bool GcscppRunner::DoRandomRead(int thread_id, google::cloud::storage::Client storage_client) { if (parameters_.read_limit <= 0) { std::cerr << "read_limit should be greater than 0." << std::endl; return false; } int64_t read_span = parameters_.read_limit - std::max(int64_t(0), parameters_.read_offset); if (read_span <= 0) { std::cerr << "read_limit should be greater than read_offset." << std::endl; return false; } if (parameters_.chunk_size == 0) { std::cerr << "chunk_size should be greater than 0." << std::endl; return false; } int64_t chunks = read_span / parameters_.chunk_size; if (chunks <= 0) { std::cerr << "read_limit should be greater than or equal to readable window." << std::endl; return false; } std::string object = object_resolver_.Resolve(thread_id, 0); absl::BitGen gen; std::vector<char> buffer(4 * 1024 * 1024); for (int run = 0; run < parameters_.runs; run++) { int64_t offset = absl::Uniform(gen, 0, chunks) * parameters_.chunk_size; absl::Time run_start = absl::Now(); auto reader = storage_client.ReadObject(parameters_.bucket, object, google::cloud::storage::ReadRange( offset, offset + parameters_.chunk_size)); if (!reader) { std::cerr << "Error reading object: " << reader.status() << "\n"; return false; } int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); while (total_bytes < parameters_.chunk_size) { reader.read(buffer.data(), std::min(buffer.size(), (size_t)parameters_.chunk_size)); int64_t content_size = reader.gcount(); RunnerWatcher::Chunk chunk = {absl::Now(), content_size}; chunks.push_back(chunk); total_bytes += content_size; } reader.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Read, thread_id, 0, ExtractPeer(reader.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, chunks); } return true; } static std::vector<char> GetRandomData(size_t size) { std::vector<char> content(size); int* const s = reinterpret_cast<int*>(&(*content.begin())); int* const e = reinterpret_cast<int*>(&(*content.rbegin())); for (int* c = s; c < e; c += 1) { *c = rand(); } return content; } bool GcscppRunner::DoWrite(int thread_id, google::cloud::storage::Client storage_client) { const int64_t max_chunk_size = (parameters_.chunk_size < 0) ? 2097152 : parameters_.chunk_size; const std::vector<char> content = GetRandomData(max_chunk_size); if (parameters_.object_stop > 0) { std::cerr << "write doesn't support object_stop" << std::endl; return false; } if (parameters_.write_size <= 0) { std::cerr << "write_size should be greater than 0." << std::endl; return false; } for (int run = 0; run < parameters_.runs; run++) { std::string object = object_resolver_.Resolve(thread_id, run); absl::Time run_start = absl::Now(); int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); auto writer = storage_client.WriteObject(parameters_.bucket, object); for (int64_t o = 0; o < parameters_.write_size; o += max_chunk_size) { int64_t chunk_size = std::min(max_chunk_size, parameters_.write_size - o); writer.write(content.data(), static_cast<std::streamsize>(chunk_size)); RunnerWatcher::Chunk chunk = {absl::Now(), chunk_size}; chunks.push_back(chunk); total_bytes += chunk_size; } writer.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Write, thread_id, 0, ExtractPeer(writer.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, std::move(chunks)); } return true; } <commit_msg>Added UploadBufferSizeOption><commit_after>#include "gcscpp_runner.h" #include <string> #include <thread> #include "absl/random/random.h" #include "absl/time/time.h" #include "google/cloud/storage/client.h" #include "google/cloud/storage/grpc_plugin.h" GcscppRunner::GcscppRunner(Parameters parameters, std::shared_ptr<RunnerWatcher> watcher) : parameters_(parameters), object_resolver_(parameters_.object, parameters_.object_format, parameters_.object_start, parameters_.object_stop), watcher_(watcher) {} static google::cloud::storage::Client CreateClient( const Parameters& parameters) { auto opts = google::cloud::Options{}; if (parameters.write_size > 0) { // Make a upload buffer big enough to make it done in a single rpc call. std::size_t upload_buffer_size = std::min<std::size_t>( 128 * 1024 * 1024, (std::size_t)parameters.write_size); opts.set<google::cloud::storage::UploadBufferSizeOption>( upload_buffer_size + 1); } if (parameters.client == "gcscpp-grpc") { std::string target = parameters.host; if (parameters.td) { // TODO(veblush): Remove experimental suffix once this code is proven // stable. target = "google-c2p-experimental:///" + target; } return ::google::cloud::storage_experimental::DefaultGrpcClient( opts.set<google::cloud::storage_experimental::GrpcPluginOption>("media") .set<google::cloud::EndpointOption>(target)); } else { return ::google::cloud::storage::Client(); } } bool GcscppRunner::Run() { auto client = CreateClient(parameters_); // Spawns benchmark threads and waits until they're done. std::vector<std::thread> threads; std::vector<bool> returns(parameters_.threads); for (int i = 1; i <= parameters_.threads; i++) { int thread_id = i; threads.emplace_back([thread_id, client, &returns, this]() { returns[thread_id - 1] = this->DoOperation(thread_id, client); }); } std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); }); return std::all_of(returns.begin(), returns.end(), [](bool v) { return v; }); } bool GcscppRunner::DoOperation(int thread_id, google::cloud::storage::Client storage_client) { switch (parameters_.operation_type) { case OperationType::Read: return DoRead(thread_id, storage_client); case OperationType::RandomRead: return DoRandomRead(thread_id, storage_client); case OperationType::Write: return DoWrite(thread_id, storage_client); default: return false; } } std::string ExtractPeer( std::multimap<std::string, std::string> const& headers) { auto p = headers.find(":grpc-context-peer"); if (p == headers.end()) { p = headers.find(":curl-peer"); } return p == headers.end() ? "" : p->second; } bool GcscppRunner::DoRead(int thread_id, google::cloud::storage::Client storage_client) { std::vector<char> buffer(4 * 1024 * 1024); auto const buffer_size = static_cast<std::streamsize>(buffer.size()); for (int run = 0; run < parameters_.runs; run++) { std::string object = object_resolver_.Resolve(thread_id, run); absl::Time run_start = absl::Now(); auto reader = storage_client.ReadObject(parameters_.bucket, object); if (!reader) { std::cerr << "Error reading object: " << reader.status() << "\n"; return false; } int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); while (!reader.eof()) { reader.read(buffer.data(), buffer_size); int64_t content_size = reader.gcount(); RunnerWatcher::Chunk chunk = {absl::Now(), content_size}; chunks.push_back(chunk); total_bytes += content_size; } reader.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Read, thread_id, 0, ExtractPeer(reader.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, chunks); } return true; } bool GcscppRunner::DoRandomRead(int thread_id, google::cloud::storage::Client storage_client) { if (parameters_.read_limit <= 0) { std::cerr << "read_limit should be greater than 0." << std::endl; return false; } int64_t read_span = parameters_.read_limit - std::max(int64_t(0), parameters_.read_offset); if (read_span <= 0) { std::cerr << "read_limit should be greater than read_offset." << std::endl; return false; } if (parameters_.chunk_size == 0) { std::cerr << "chunk_size should be greater than 0." << std::endl; return false; } int64_t chunks = read_span / parameters_.chunk_size; if (chunks <= 0) { std::cerr << "read_limit should be greater than or equal to readable window." << std::endl; return false; } std::string object = object_resolver_.Resolve(thread_id, 0); absl::BitGen gen; std::vector<char> buffer(4 * 1024 * 1024); for (int run = 0; run < parameters_.runs; run++) { int64_t offset = absl::Uniform(gen, 0, chunks) * parameters_.chunk_size; absl::Time run_start = absl::Now(); auto reader = storage_client.ReadObject(parameters_.bucket, object, google::cloud::storage::ReadRange( offset, offset + parameters_.chunk_size)); if (!reader) { std::cerr << "Error reading object: " << reader.status() << "\n"; return false; } int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); while (total_bytes < parameters_.chunk_size) { reader.read(buffer.data(), std::min(buffer.size(), (size_t)parameters_.chunk_size)); int64_t content_size = reader.gcount(); RunnerWatcher::Chunk chunk = {absl::Now(), content_size}; chunks.push_back(chunk); total_bytes += content_size; } reader.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Read, thread_id, 0, ExtractPeer(reader.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, chunks); } return true; } static std::vector<char> GetRandomData(size_t size) { std::vector<char> content(size); int* const s = reinterpret_cast<int*>(&(*content.begin())); int* const e = reinterpret_cast<int*>(&(*content.rbegin())); for (int* c = s; c < e; c += 1) { *c = rand(); } return content; } bool GcscppRunner::DoWrite(int thread_id, google::cloud::storage::Client storage_client) { const int64_t max_chunk_size = (parameters_.chunk_size < 0) ? 2097152 : parameters_.chunk_size; const std::vector<char> content = GetRandomData(max_chunk_size); if (parameters_.object_stop > 0) { std::cerr << "write doesn't support object_stop" << std::endl; return false; } if (parameters_.write_size <= 0) { std::cerr << "write_size should be greater than 0." << std::endl; return false; } for (int run = 0; run < parameters_.runs; run++) { std::string object = object_resolver_.Resolve(thread_id, run); absl::Time run_start = absl::Now(); int64_t total_bytes = 0; std::vector<RunnerWatcher::Chunk> chunks; chunks.reserve(256); auto writer = storage_client.WriteObject(parameters_.bucket, object); for (int64_t o = 0; o < parameters_.write_size; o += max_chunk_size) { int64_t chunk_size = std::min(max_chunk_size, parameters_.write_size - o); writer.write(content.data(), static_cast<std::streamsize>(chunk_size)); RunnerWatcher::Chunk chunk = {absl::Now(), chunk_size}; chunks.push_back(chunk); total_bytes += chunk_size; } writer.Close(); absl::Time run_end = absl::Now(); watcher_->NotifyCompleted(OperationType::Write, thread_id, 0, ExtractPeer(writer.headers()), parameters_.bucket, object, grpc::Status::OK, total_bytes, run_start, run_end - run_start, std::move(chunks)); } return true; } <|endoftext|>
<commit_before>// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Pixels Implementation // #define MAGICKCORE_IMPLEMENTATION 1 #define MAGICK_PLUSPLUS_IMPLEMENTATION 1 #include <cstring> #include "Magick++/Include.h" #include <string> // This is here to compile with Visual C++ #include "Magick++/Thread.h" #include "Magick++/Exception.h" #include "Magick++/Pixels.h" Magick::Pixels::Pixels(Magick::Image &image_) : _image(image_), _x(0), _y(0), _columns(0), _rows(0) { GetPPException; _view=AcquireVirtualCacheView(_image.image(),exceptionInfo), ThrowPPException; } Magick::Pixels::~Pixels(void) { if (_view) _view=DestroyCacheView(_view); } Magick::Quantum* Magick::Pixels::get(const ssize_t x_,const ssize_t y_, const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; Quantum* pixels=GetCacheViewAuthenticPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } const Magick::Quantum* Magick::Pixels::getConst(const ssize_t x_, const ssize_t y_,const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; const Quantum* pixels=GetCacheViewVirtualPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } ssize_t Magick::Pixels::offset(PixelChannel channel) const { if (_image.constImage()->channel_map[channel].traits == UndefinedPixelTrait) return -1; return _image.constImage()->channel_map[channel].offset; } Magick::Quantum* Magick::Pixels::set(const ssize_t x_,const ssize_t y_, const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; Quantum* pixels=QueueCacheViewAuthenticPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } void Magick::Pixels::sync(void) { GetPPException; SyncCacheViewAuthenticPixels(_view,exceptionInfo); ThrowPPException; } // Return pixel colormap index array /* Magick::void* Magick::Pixels::metacontent(void) { void* pixel_metacontent=GetCacheViewAuthenticMetacontent(_view); if (!pixel_metacontent) _image.throwImageException(); return pixel_metacontent; } */ Magick::PixelData::PixelData(Magick::Image &image_,std::string map_, const StorageType type_) { init(image_,0,0,image_.columns(),image_.rows(),map_,type_); } Magick::PixelData::PixelData(Magick::Image &image_,const ::ssize_t x_, const ::ssize_t y_,const size_t width_,const size_t height_,std::string map_, const StorageType type_) { init(image_,x_,y_,width_,height_,map_,type_); } Magick::PixelData::~PixelData(void) { relinquish(); } const void *Magick::PixelData::data(void) const { return(_data); } const ::ssize_t Magick::PixelData::length(void) const { return(_length); } const ::ssize_t Magick::PixelData::size(void) const { return(_size); } void Magick::PixelData::init(Magick::Image &image_,const ::ssize_t x_, const ::ssize_t y_,const size_t width_,const size_t height_, std::string map_,const StorageType type_) { size_t size; _data=(void *) NULL; _length=0; _size=0; if ((x_ < 0) || (width_ == 0) || (y_ < 0) || (height_ == 0) || (x_ > image_.columns()) || ((width_ + x_) > (::ssize_t)image_.columns()) || (y_ > image_.rows()) || ((height_ + y_) > (::ssize_t)image_.rows()) || (map_.length() == 0)) return; switch(type_) { case CharPixel: size=sizeof(unsigned char); break; case DoublePixel: size=sizeof(double); break; case FloatPixel: size=sizeof(float); break; case LongPixel: size=sizeof(unsigned int); break; case LongLongPixel: size=sizeof(MagickSizeType); break; case QuantumPixel: size=sizeof(Quantum); break; case ShortPixel: size=sizeof(unsigned short); break; default: throwExceptionExplicit(OptionError,"Invalid type"); return; } _length=width_*height_*map_.length(); _size=_length*size; _data=AcquireMagickMemory(_size); GetPPException; MagickCore::ExportImagePixels(image_.image(),x_,y_,width_,height_, map_.c_str(),type_,_data,exceptionInfo); if (exceptionInfo->severity != UndefinedException) relinquish(); ThrowPPException; } void Magick::PixelData::relinquish(void) throw() { if (_data != (void *)NULL) _data=RelinquishMagickMemory(_data); _length=0; _size=0; } <commit_msg>Build fix.<commit_after>// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Pixels Implementation // #define MAGICKCORE_IMPLEMENTATION 1 #define MAGICK_PLUSPLUS_IMPLEMENTATION 1 #include <cstring> #include "Magick++/Include.h" #include <string> // This is here to compile with Visual C++ #include "Magick++/Thread.h" #include "Magick++/Exception.h" #include "Magick++/Pixels.h" Magick::Pixels::Pixels(Magick::Image &image_) : _image(image_), _x(0), _y(0), _columns(0), _rows(0) { GetPPException; _view=AcquireVirtualCacheView(_image.image(),exceptionInfo), ThrowPPException; } Magick::Pixels::~Pixels(void) { if (_view) _view=DestroyCacheView(_view); } Magick::Quantum* Magick::Pixels::get(const ssize_t x_,const ssize_t y_, const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; Quantum* pixels=GetCacheViewAuthenticPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } const Magick::Quantum* Magick::Pixels::getConst(const ssize_t x_, const ssize_t y_,const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; const Quantum* pixels=GetCacheViewVirtualPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } ssize_t Magick::Pixels::offset(PixelChannel channel) const { if (_image.constImage()->channel_map[channel].traits == UndefinedPixelTrait) return -1; return _image.constImage()->channel_map[channel].offset; } Magick::Quantum* Magick::Pixels::set(const ssize_t x_,const ssize_t y_, const size_t columns_,const size_t rows_) { _x=x_; _y=y_; _columns=columns_; _rows=rows_; GetPPException; Quantum* pixels=QueueCacheViewAuthenticPixels(_view,x_,y_,columns_,rows_, exceptionInfo); ThrowPPException; return pixels; } void Magick::Pixels::sync(void) { GetPPException; SyncCacheViewAuthenticPixels(_view,exceptionInfo); ThrowPPException; } // Return pixel colormap index array /* Magick::void* Magick::Pixels::metacontent(void) { void* pixel_metacontent=GetCacheViewAuthenticMetacontent(_view); if (!pixel_metacontent) _image.throwImageException(); return pixel_metacontent; } */ Magick::PixelData::PixelData(Magick::Image &image_,std::string map_, const StorageType type_) { init(image_,0,0,image_.columns(),image_.rows(),map_,type_); } Magick::PixelData::PixelData(Magick::Image &image_,const ::ssize_t x_, const ::ssize_t y_,const size_t width_,const size_t height_,std::string map_, const StorageType type_) { init(image_,x_,y_,width_,height_,map_,type_); } Magick::PixelData::~PixelData(void) { relinquish(); } const void *Magick::PixelData::data(void) const { return(_data); } ::ssize_t Magick::PixelData::length(void) const { return(_length); } ::ssize_t Magick::PixelData::size(void) const { return(_size); } void Magick::PixelData::init(Magick::Image &image_,const ::ssize_t x_, const ::ssize_t y_,const size_t width_,const size_t height_, std::string map_,const StorageType type_) { size_t size; _data=(void *) NULL; _length=0; _size=0; if ((x_ < 0) || (width_ == 0) || (y_ < 0) || (height_ == 0) || (x_ > image_.columns()) || ((width_ + x_) > (::ssize_t)image_.columns()) || (y_ > image_.rows()) || ((height_ + y_) > (::ssize_t)image_.rows()) || (map_.length() == 0)) return; switch(type_) { case CharPixel: size=sizeof(unsigned char); break; case DoublePixel: size=sizeof(double); break; case FloatPixel: size=sizeof(float); break; case LongPixel: size=sizeof(unsigned int); break; case LongLongPixel: size=sizeof(MagickSizeType); break; case QuantumPixel: size=sizeof(Quantum); break; case ShortPixel: size=sizeof(unsigned short); break; default: throwExceptionExplicit(OptionError,"Invalid type"); return; } _length=width_*height_*map_.length(); _size=_length*size; _data=AcquireMagickMemory(_size); GetPPException; MagickCore::ExportImagePixels(image_.image(),x_,y_,width_,height_, map_.c_str(),type_,_data,exceptionInfo); if (exceptionInfo->severity != UndefinedException) relinquish(); ThrowPPException; } void Magick::PixelData::relinquish(void) throw() { if (_data != (void *)NULL) _data=RelinquishMagickMemory(_data); _length=0; _size=0; } <|endoftext|>
<commit_before>#include <UWP/UWP.hpp> #include <Windows.h> #include <ShlObj.h> #include <appmodel.h> #include <AppxPackaging.h> #include <memory> namespace { template< typename T > void FreeDeleter(T* Data) { free(Data); } std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)> GetPackageIdentifier() { std::uint32_t Size = 0; GetCurrentPackageId(&Size, nullptr); if( Size ) { std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)> PackageID( reinterpret_cast<PACKAGE_ID*>(malloc(Size)), FreeDeleter<PACKAGE_ID> ); GetCurrentPackageId( &Size, reinterpret_cast<std::uint8_t*>(PackageID.get()) ); return PackageID; } return std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)>( nullptr, FreeDeleter<PACKAGE_ID> ); } std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)> GetPackageInfo() { std::uint32_t Size = 0; std::uint32_t Count = 0; GetCurrentPackageInfo(PACKAGE_FILTER_HEAD, &Size, nullptr, &Count); if( Size ) { std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)> PackageInfo( reinterpret_cast<PACKAGE_INFO*>(malloc(Size)), [](PACKAGE_INFO* PackageID) { free(PackageID); } ); GetCurrentPackageInfo( PACKAGE_FILTER_HEAD, &Size, reinterpret_cast<std::uint8_t*>(PackageInfo.get()), &Count ); return PackageInfo; } return std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)>( nullptr, FreeDeleter<PACKAGE_INFO> ); } } std::wstring UWP::Current::GetFamilyName() { std::wstring FamilyName; std::uint32_t FamilyNameSize = 0; GetCurrentPackageFamilyName(&FamilyNameSize, nullptr); FamilyName.resize(FamilyNameSize - 1); GetCurrentPackageFamilyName(&FamilyNameSize, &FamilyName[0]); return FamilyName; } std::wstring UWP::Current::GetFullName() { std::wstring FullName; std::uint32_t FullNameSize = 0; GetCurrentPackageFullName(&FullNameSize, nullptr); FullName.resize(FullNameSize - 1); GetCurrentPackageFullName(&FullNameSize, &FullName[0]); return FullName; } std::wstring UWP::Current::GetArchitecture() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { switch( PackageID->processorArchitecture ) { case APPX_PACKAGE_ARCHITECTURE_ARM: { return L"ARM"; } case APPX_PACKAGE_ARCHITECTURE_X86: { return L"x86"; } case APPX_PACKAGE_ARCHITECTURE_X64: { return L"x64"; } case APPX_PACKAGE_ARCHITECTURE_NEUTRAL: { return L"Neutral"; } } } return L""; } std::wstring UWP::Current::GetPublisher() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { return std::wstring(PackageID->publisher); } return L""; } std::wstring UWP::Current::GetPublisherID() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { return std::wstring(PackageID->publisherId); } return L""; } std::wstring UWP::Current::GetPackagePath() { std::wstring Path; std::uint32_t PathSize = 0; GetCurrentPackagePath(&PathSize, nullptr); Path.resize(PathSize - 1); GetCurrentPackagePath(&PathSize, &Path[0]); return Path; } std::wstring UWP::Current::Storage::GetPublisherPath() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { wchar_t UserPath[MAX_PATH] = {0}; SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false); std::wstring PublisherPath(UserPath); PublisherPath += L"\\AppData\\Local\\Publishers\\"; PublisherPath += PackageID->publisherId; return PublisherPath; } return L""; } std::wstring UWP::Current::Storage::GetStoragePath() { wchar_t UserPath[MAX_PATH] = {0}; SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false); std::wstring StoragePath(UserPath); StoragePath += L"\\AppData\\Local\\Packages\\" + GetFamilyName(); return StoragePath; } std::wstring UWP::Current::Storage::GetLocalCachePath() { return GetStoragePath() + L"\\LocalCache"; } std::wstring UWP::Current::Storage::GetLocalPath() { return GetStoragePath() + L"\\LocalState"; } std::wstring UWP::Current::Storage::GetRoamingPath() { return GetStoragePath() + L"\\RoamingState"; } std::wstring UWP::Current::Storage::GetTempStatePath() { return GetStoragePath() + L"\\TempState"; } <commit_msg>Add template FreeDeleter to for PACKAGE_INFO<commit_after>#include <UWP/UWP.hpp> #include <Windows.h> #include <ShlObj.h> #include <appmodel.h> #include <AppxPackaging.h> #include <memory> namespace { template< typename T > void FreeDeleter(T* Data) { free(Data); } std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)> GetPackageIdentifier() { std::uint32_t Size = 0; GetCurrentPackageId(&Size, nullptr); if( Size ) { std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)> PackageID( reinterpret_cast<PACKAGE_ID*>(malloc(Size)), FreeDeleter<PACKAGE_ID> ); GetCurrentPackageId( &Size, reinterpret_cast<std::uint8_t*>(PackageID.get()) ); return PackageID; } return std::unique_ptr<PACKAGE_ID, decltype(&FreeDeleter<PACKAGE_ID>)>( nullptr, FreeDeleter<PACKAGE_ID> ); } std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)> GetPackageInfo() { std::uint32_t Size = 0; std::uint32_t Count = 0; GetCurrentPackageInfo(PACKAGE_FILTER_HEAD, &Size, nullptr, &Count); if( Size ) { std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)> PackageInfo( reinterpret_cast<PACKAGE_INFO*>(malloc(Size)), FreeDeleter<PACKAGE_INFO> ); GetCurrentPackageInfo( PACKAGE_FILTER_HEAD, &Size, reinterpret_cast<std::uint8_t*>(PackageInfo.get()), &Count ); return PackageInfo; } return std::unique_ptr<PACKAGE_INFO, decltype(&FreeDeleter<PACKAGE_INFO>)>( nullptr, FreeDeleter<PACKAGE_INFO> ); } } std::wstring UWP::Current::GetFamilyName() { std::wstring FamilyName; std::uint32_t FamilyNameSize = 0; GetCurrentPackageFamilyName(&FamilyNameSize, nullptr); FamilyName.resize(FamilyNameSize - 1); GetCurrentPackageFamilyName(&FamilyNameSize, &FamilyName[0]); return FamilyName; } std::wstring UWP::Current::GetFullName() { std::wstring FullName; std::uint32_t FullNameSize = 0; GetCurrentPackageFullName(&FullNameSize, nullptr); FullName.resize(FullNameSize - 1); GetCurrentPackageFullName(&FullNameSize, &FullName[0]); return FullName; } std::wstring UWP::Current::GetArchitecture() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { switch( PackageID->processorArchitecture ) { case APPX_PACKAGE_ARCHITECTURE_ARM: { return L"ARM"; } case APPX_PACKAGE_ARCHITECTURE_X86: { return L"x86"; } case APPX_PACKAGE_ARCHITECTURE_X64: { return L"x64"; } case APPX_PACKAGE_ARCHITECTURE_NEUTRAL: { return L"Neutral"; } } } return L""; } std::wstring UWP::Current::GetPublisher() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { return std::wstring(PackageID->publisher); } return L""; } std::wstring UWP::Current::GetPublisherID() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { return std::wstring(PackageID->publisherId); } return L""; } std::wstring UWP::Current::GetPackagePath() { std::wstring Path; std::uint32_t PathSize = 0; GetCurrentPackagePath(&PathSize, nullptr); Path.resize(PathSize - 1); GetCurrentPackagePath(&PathSize, &Path[0]); return Path; } std::wstring UWP::Current::Storage::GetPublisherPath() { auto PackageID = GetPackageIdentifier(); if( PackageID ) { wchar_t UserPath[MAX_PATH] = {0}; SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false); std::wstring PublisherPath(UserPath); PublisherPath += L"\\AppData\\Local\\Publishers\\"; PublisherPath += PackageID->publisherId; return PublisherPath; } return L""; } std::wstring UWP::Current::Storage::GetStoragePath() { wchar_t UserPath[MAX_PATH] = {0}; SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false); std::wstring StoragePath(UserPath); StoragePath += L"\\AppData\\Local\\Packages\\" + GetFamilyName(); return StoragePath; } std::wstring UWP::Current::Storage::GetLocalCachePath() { return GetStoragePath() + L"\\LocalCache"; } std::wstring UWP::Current::Storage::GetLocalPath() { return GetStoragePath() + L"\\LocalState"; } std::wstring UWP::Current::Storage::GetRoamingPath() { return GetStoragePath() + L"\\RoamingState"; } std::wstring UWP::Current::Storage::GetTempStatePath() { return GetStoragePath() + L"\\TempState"; } <|endoftext|>
<commit_before>/* Copyright 2013-2016 CyberTech Labs 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 "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLineEdit> #include <twoDModel/engine/twoDModelEngineFacade.h> #include <qrkernel/settingsManager.h> #include <qrkernel/settingsListener.h> #include <qrgui/textEditor/qscintillaTextEdit.h> #include <qrgui/textEditor/languageInfo.h> using namespace trik; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() : mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr) { } TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase (robotModel::TrikRobotModelBase * const realRobotModel , robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel , blocks::TrikBlocksFactoryBase * const blocksFactory ) { mRealRobotModel.reset(realRobotModel); mTwoDRobotModel.reset(twoDRobotModel); mBlocksFactory = blocksFactory; const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel); mTwoDRobotModel->setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =( mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() }); mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel)); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code) { emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScript(code); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs) { // we are in exercise mode (maybe rename it later) emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScriptExercise(code, inputs); } TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const { return mQtsInterpreter.data(); } void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer) { connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurer.qRealConfigurator().mainWindowInterpretersInterface(); mProjectManager = &configurer.qRealConfigurator().projectManager(); mTwoDModel->init(configurer.eventsForKitPlugin() , configurer.qRealConfigurator().systemEvents() , configurer.qRealConfigurator().logicalModelApi() , configurer.qRealConfigurator().controller() , interpretersInterface , configurer.qRealConfigurator().mainWindowDockInterface() , configurer.qRealConfigurator().projectManager() , configurer.interpreterControl()); mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter()); mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface(); mSystemEvents = &configurer.qRealConfigurator().systemEvents(); /// @todo: refactor? mStart.setObjectName("runQts"); mStart.setText(tr("Run program")); mStart.setIcon(QIcon(":/trik/qts/images/run.png")); mStop.setObjectName("stopQts"); mStop.setText(tr("Stop robot")); mStop.setIcon(QIcon(":/trik/qts/images/stop.png")); mStop.setVisible(false); mStart.setVisible(false); connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretCode , [this](const QString &code, const QString &inputs){ if (mIsModelSelected) { startJSInterpretation(code, inputs); } }); connect(&configurer.robotModelManager() , &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , [this](kitBase::robotModel::RobotModelInterface &model){ mIsModelSelected = robotModels().contains(&model); /// @todo: would probably make sense to make the current opened tab info available globally somewhere bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); mStart.setVisible(mIsModelSelected && isCodeTabOpen); mStop.setVisible(false); // interpretation should always stop when switching models? }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::stopAllInterpretation , [this](qReal::interpretation::StopReason) { if (mQtsInterpreter->isRunning()) { testStop(); } }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::startJsInterpretation , [this]() { if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary testStart(); } }); connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart); connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop); connect(mQtsInterpreter.data() , &TrikQtsInterpreter::completed , this , &TrikKitInterpreterPluginBase::testStop); // refactor? connect(this , &TrikKitInterpreterPluginBase::started , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted ); connect(this , &TrikKitInterpreterPluginBase::stopped , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped ); // connect(&configurer.qRealConfigurator().systemEvents(), // &kitBase::EventsForKitPluginInterface:) connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted , [this](){ /// @todo const bool isQtsInt = mQtsInterpreter->isRunning(); mStart.setEnabled(isQtsInt); mStop.setEnabled(isQtsInt); } ); QObject::connect( this , &TrikKitInterpreterPluginBase::codeInterpretationStarted , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::codeInterpretationStarted ); QObject::connect( &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped , [this](qReal::interpretation::StopReason reason){ /// @todo Q_UNUSED(reason); mStart.setEnabled(true); mStop.setEnabled(true); } ); connect(mSystemEvents , &qReal::SystemEvents::activeTabChanged , this , &TrikKitInterpreterPluginBase::onTabChanged); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings); } QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels() { return {mRealRobotModel.data(), mTwoDRobotModel.data()}; } kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel() { return mTwoDRobotModel.data(); } QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model) { return model.name().toLower().contains("twod") ? nullptr : produceIpAddressConfigurer(); } QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions() { return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") }; } QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions() { return {}; } QString TrikKitInterpreterPluginBase::defaultSettingsFile() const { return ":/trikDefaultSettings.ini"; } QIcon TrikKitInterpreterPluginBase::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == mRealRobotModel.data() ? QIcon(":/icons/switch-real-trik.svg") : &robotModel == mTwoDRobotModel.data() ? QIcon(":/icons/switch-2d.svg") : QIcon(); } kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer() { QLineEdit * const quickPreferences = new QLineEdit; quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here...")); const auto updateQuickPreferences = [quickPreferences]() { const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString(); if (quickPreferences->text() != ip) { quickPreferences->setText(ip); } }; updateQuickPreferences(); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences); qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this); connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) { qReal::SettingsManager::setValue("TrikTcpServer", text); }); connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; }); return quickPreferences; } void TrikKitInterpreterPluginBase::testStart() { mStop.setVisible(true); mStart.setVisible(false); /// todo: bad auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; }; if (texttab && isJS(texttab->currentLanguage().extension)) { startJSInterpretation(texttab->text()); } else { qDebug("wrong tab selected"); mStop.setVisible(false); mStart.setVisible(true); /// todo: refactor the whole button shenanigans } } void TrikKitInterpreterPluginBase::testStop() { mStop.setVisible(false); mStart.setVisible(true); qtsInterpreter()->abort(); mTwoDRobotModel->stopRobot(); emit stopped(qReal::interpretation::StopReason::userStop); } void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info) { if (!mIsModelSelected) { return; } const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code; mStart.setEnabled(isCodeTab); mStop.setEnabled(isCodeTab); if (mQtsInterpreter->isRunning()) { mStop.trigger(); // Should interpretation should always stops at the change of tabs or not? } if (isCodeTab) { mStart.setVisible(true); mStop.setVisible(false); } else { mStart.setVisible(false); mStop.setVisible(false); } } <commit_msg>Fix crash on exit<commit_after>/* Copyright 2013-2016 CyberTech Labs 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 "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLineEdit> #include <twoDModel/engine/twoDModelEngineFacade.h> #include <qrkernel/settingsManager.h> #include <qrkernel/settingsListener.h> #include <qrgui/textEditor/qscintillaTextEdit.h> #include <qrgui/textEditor/languageInfo.h> using namespace trik; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() : mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr) { } TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase (robotModel::TrikRobotModelBase * const realRobotModel , robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel , blocks::TrikBlocksFactoryBase * const blocksFactory ) { mRealRobotModel.reset(realRobotModel); mTwoDRobotModel.reset(twoDRobotModel); mBlocksFactory = blocksFactory; const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel); mTwoDRobotModel->setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =( mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() }); mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel)); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code) { emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScript(code); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs) { // we are in exercise mode (maybe rename it later) emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScriptExercise(code, inputs); } TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const { return mQtsInterpreter.data(); } void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer) { connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurer.qRealConfigurator().mainWindowInterpretersInterface(); mProjectManager = &configurer.qRealConfigurator().projectManager(); mTwoDModel->init(configurer.eventsForKitPlugin() , configurer.qRealConfigurator().systemEvents() , configurer.qRealConfigurator().logicalModelApi() , configurer.qRealConfigurator().controller() , interpretersInterface , configurer.qRealConfigurator().mainWindowDockInterface() , configurer.qRealConfigurator().projectManager() , configurer.interpreterControl()); mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter()); mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface(); mSystemEvents = &configurer.qRealConfigurator().systemEvents(); /// @todo: refactor? mStart.setObjectName("runQts"); mStart.setText(tr("Run program")); mStart.setIcon(QIcon(":/trik/qts/images/run.png")); mStop.setObjectName("stopQts"); mStop.setText(tr("Stop robot")); mStop.setIcon(QIcon(":/trik/qts/images/stop.png")); mStop.setVisible(false); mStart.setVisible(false); connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretCode , [this](const QString &code, const QString &inputs){ if (mIsModelSelected) { startJSInterpretation(code, inputs); } }); connect(&configurer.robotModelManager() , &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , [this](kitBase::robotModel::RobotModelInterface &model){ mIsModelSelected = robotModels().contains(&model); /// @todo: would probably make sense to make the current opened tab info available globally somewhere bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); mStart.setVisible(mIsModelSelected && isCodeTabOpen); mStop.setVisible(false); // interpretation should always stop when switching models? }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::stopAllInterpretation , this , [this](qReal::interpretation::StopReason) { if (mQtsInterpreter->isRunning()) { testStop(); } }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::startJsInterpretation , this , [this]() { if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary testStart(); } }); connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart); connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop); connect(mQtsInterpreter.data() , &TrikQtsInterpreter::completed , this , &TrikKitInterpreterPluginBase::testStop); // refactor? connect(this , &TrikKitInterpreterPluginBase::started , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted ); connect(this , &TrikKitInterpreterPluginBase::stopped , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped ); // connect(&configurer.qRealConfigurator().systemEvents(), // &kitBase::EventsForKitPluginInterface:) connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted , [this](){ /// @todo const bool isQtsInt = mQtsInterpreter->isRunning(); mStart.setEnabled(isQtsInt); mStop.setEnabled(isQtsInt); } ); QObject::connect( this , &TrikKitInterpreterPluginBase::codeInterpretationStarted , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::codeInterpretationStarted ); QObject::connect( &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped , [this](qReal::interpretation::StopReason reason){ /// @todo Q_UNUSED(reason); mStart.setEnabled(true); mStop.setEnabled(true); } ); connect(mSystemEvents , &qReal::SystemEvents::activeTabChanged , this , &TrikKitInterpreterPluginBase::onTabChanged); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings); } QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels() { return {mRealRobotModel.data(), mTwoDRobotModel.data()}; } kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel() { return mTwoDRobotModel.data(); } QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model) { return model.name().toLower().contains("twod") ? nullptr : produceIpAddressConfigurer(); } QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions() { return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") }; } QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions() { return {}; } QString TrikKitInterpreterPluginBase::defaultSettingsFile() const { return ":/trikDefaultSettings.ini"; } QIcon TrikKitInterpreterPluginBase::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == mRealRobotModel.data() ? QIcon(":/icons/switch-real-trik.svg") : &robotModel == mTwoDRobotModel.data() ? QIcon(":/icons/switch-2d.svg") : QIcon(); } kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer() { QLineEdit * const quickPreferences = new QLineEdit; quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here...")); const auto updateQuickPreferences = [quickPreferences]() { const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString(); if (quickPreferences->text() != ip) { quickPreferences->setText(ip); } }; updateQuickPreferences(); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences); qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this); connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) { qReal::SettingsManager::setValue("TrikTcpServer", text); }); connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; }); return quickPreferences; } void TrikKitInterpreterPluginBase::testStart() { mStop.setVisible(true); mStart.setVisible(false); /// todo: bad auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; }; if (texttab && isJS(texttab->currentLanguage().extension)) { startJSInterpretation(texttab->text()); } else { qDebug("wrong tab selected"); mStop.setVisible(false); mStart.setVisible(true); /// todo: refactor the whole button shenanigans } } void TrikKitInterpreterPluginBase::testStop() { mStop.setVisible(false); mStart.setVisible(true); qtsInterpreter()->abort(); mTwoDRobotModel->stopRobot(); emit stopped(qReal::interpretation::StopReason::userStop); } void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info) { if (!mIsModelSelected) { return; } const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code; mStart.setEnabled(isCodeTab); mStop.setEnabled(isCodeTab); if (mQtsInterpreter->isRunning()) { mStop.trigger(); // Should interpretation should always stops at the change of tabs or not? } if (isCodeTab) { mStart.setVisible(true); mStop.setVisible(false); } else { mStart.setVisible(false); mStop.setVisible(false); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2006 George Staikos <[email protected]> * Copyright (C) 2006 Dirk Mueller <[email protected]> * Copyright (C) 2006 Zack Rusin <[email protected]> * Copyright (C) 2006 Simon Hausmann <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 <qwebpage.h> #include <qwebframe.h> #include <qwebsettings.h> #include <QtGui> #include <QDebug> class InfoWidget :public QProgressBar { Q_OBJECT public: InfoWidget(QWidget *parent) : QProgressBar(parent), m_progress(0) { setMinimum(0); setMaximum(100); } QSize sizeHint() const { QSize size(100, 20); return size; } public slots: void startLoad() { setValue(m_progress); show(); } void changeLoad(int change) { m_progress = change; setValue(change); } void endLoad() { QTimer::singleShot(1000, this, SLOT(hide())); m_progress = 0; } protected: int m_progress; }; class HoverLabel : public QWidget { Q_OBJECT public: HoverLabel(QWidget *parent=0) : QWidget(parent), m_animating(false), m_percent(0) { m_timer.setInterval(1000/30); m_hideTimer.setInterval(500); m_hideTimer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); connect(&m_hideTimer, SIGNAL(timeout()), this, SLOT(hide())); } public slots: void setHoverLink(const QString &link) { m_link = link; if (m_link.isEmpty()) { m_hideTimer.start(); } else { m_hideTimer.stop(); m_oldSize = m_newSize; m_newSize = sizeForFont(); resetAnimation(); updateSize(); show(); repaint(); } } QSize sizeForFont() const { QFont f = font(); QFontMetrics fm(f); return QSize(fm.width(m_link) + 10, fm.height() + 6); } QSize sizeHint() const { if (!m_animating) return sizeForFont(); else return (m_newSize.width() > m_oldSize.width()) ? m_newSize : m_oldSize; } void updateSize() { QRect r = geometry(); QSize newSize = sizeHint(); r = QRect(r.x(), r.y(), newSize.width(), newSize.height()); setGeometry(r); } void resetAnimation() { m_animating = true; m_percent = 0; if (!m_timer.isActive()) m_timer.start(); } protected: void paintEvent(QPaintEvent *e) { QPainter p(this); p.setClipRect(e->rect()); p.setPen(QPen(Qt::black, 1)); QLinearGradient gradient(rect().topLeft(), rect().bottomLeft()); gradient.setColorAt(0, QColor(255, 255, 255, 220)); gradient.setColorAt(1, QColor(193, 193, 193, 220)); p.setBrush(QBrush(gradient)); QSize size; { //draw a nicely rounded corner rectangle. to avoid unwanted // borders we move the coordinates outsize the our clip region size = interpolate(m_oldSize, m_newSize, m_percent); QRect r(-1, 0, size.width(), size.height()+2); const int roundness = 20; QPainterPath path; path.moveTo(r.x(), r.y()); path.lineTo(r.topRight().x()-roundness, r.topRight().y()); path.cubicTo(r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y() + roundness); path.lineTo(r.bottomRight()); path.lineTo(r.bottomLeft()); path.closeSubpath(); p.setRenderHint(QPainter::Antialiasing); p.drawPath(path); } if (m_animating) { if (qFuzzyCompare(m_percent, 1)) { m_animating = false; m_percent = 0; m_timer.stop(); } else { m_percent += 0.1; if (m_percent >= 0.99) { m_percent = 1; } } } QString txt; QFontMetrics fm(fontMetrics()); txt = fm.elidedText(m_link, Qt::ElideRight, size.width()-5); p.drawText(5, height()-6, txt); } private: QSize interpolate(const QSize &src, const QSize &dst, qreal percent) { int widthDiff = int((dst.width() - src.width()) * percent); int heightDiff = int((dst.height() - src.height()) * percent); return QSize(src.width() + widthDiff, src.height() + heightDiff); } QString m_link; bool m_animating; QTimer m_timer; QTimer m_hideTimer; QSize m_oldSize; QSize m_newSize; qreal m_percent; }; class SearchEdit; class ClearButton : public QPushButton { Q_OBJECT public: ClearButton(QWidget *w) : QPushButton(w) { setMinimumSize(24, 24); setFixedSize(24, 24); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); int height = parentWidget()->geometry().height(); int width = height; //parentWidget()->geometry().width(); painter.setRenderHint(QPainter::Antialiasing, true); painter.setPen(Qt::lightGray); painter.setBrush(isDown() ? QColor(140, 140, 190) : underMouse() ? QColor(220, 220, 255) : QColor(200, 200, 230) ); painter.drawEllipse(4, 4, width - 8, height - 8); painter.setPen(Qt::white); int border = 8; painter.drawLine(border, border, width - border, height - border); painter.drawLine(border, height - border, width - border, border); } }; class SearchEdit : public QLineEdit { Q_OBJECT public: SearchEdit(const QString &str, QWidget *parent = 0) : QLineEdit(str, parent) { setMinimumSize(QSize(400, 24)); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setStyleSheet(":enabled { padding-right: 27px }"); clearButton = new ClearButton(this); clearButton->setGeometry(QRect(geometry().right() - 27, geometry().top() - 2, geometry().right(), geometry().bottom())); clearButton->setVisible(true); clearButton->setCursor(Qt::ArrowCursor); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); clearButton->setToolTip("Clear"); } ~SearchEdit() { } protected: virtual void paintEvent(QPaintEvent *e) { QLineEdit::paintEvent(e); if(text().isEmpty()) clearButton->setVisible(false); else clearButton->setVisible(true); } virtual void resizeEvent(QResizeEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 0, 24, 24)); } virtual void moveEvent(QMoveEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 1, 24, 24)); } QPushButton *clearButton; }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(const QUrl &url) { page = new QWebPage(this); InfoWidget *info = new InfoWidget(page); info->setGeometry(20, 20, info->sizeHint().width(), info->sizeHint().height()); connect(page, SIGNAL(loadStarted(QWebFrame*)), info, SLOT(startLoad())); connect(page, SIGNAL(loadProgressChanged(int)), info, SLOT(changeLoad(int))); connect(page, SIGNAL(loadFinished(QWebFrame*)), info, SLOT(endLoad())); connect(page, SIGNAL(loadFinished(QWebFrame*)), this, SLOT(loadFinished())); connect(page, SIGNAL(titleChanged(const QString&)), this, SLOT(setWindowTitle(const QString&))); connect(page, SIGNAL(hoveringOverLink(const QString&, const QString&)), this, SLOT(showLinkHover(const QString&, const QString&))); setCentralWidget(page); QToolBar *bar = addToolBar("Navigation"); urlEdit = new SearchEdit(url.toString()); connect(urlEdit, SIGNAL(returnPressed()), SLOT(changeLocation())); bar->addAction("Go back", page, SLOT(goBack())); bar->addAction("Stop", page, SLOT(stop())); bar->addAction("Go forward", page, SLOT(goForward())); bar->addWidget(urlEdit); hoverLabel = new HoverLabel(this); hoverLabel->hide(); page->open(url); info->raise(); } protected slots: void changeLocation() { QUrl url(urlEdit->text()); page->open(url); } void loadFinished() { urlEdit->setText(page->url().toString()); } void showLinkHover(const QString &link, const QString &toolTip) { //statusBar()->showMessage(link); hoverLabel->setHoverLink(link); if (!toolTip.isEmpty()) QToolTip::showText(QCursor::pos(), toolTip); } protected: void resizeEvent(QResizeEvent *) { QSize hoverSize = hoverLabel->sizeHint(); hoverLabel->setGeometry(0, height()-hoverSize.height(), 300, hoverSize.height()); } private: QWebPage *page; QLineEdit *urlEdit; HoverLabel *hoverLabel; }; #include "main.moc" int main(int argc, char **argv) { QString url = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); QApplication app(argc, argv); QWebSettings settings = QWebSettings::global(); settings.setAttribute(QWebSettings::PluginsEnabled); QWebSettings::setGlobal(settings); const QStringList args = app.arguments(); if (args.count() > 1) url = args.at(1); MainWindow window(url); window.show(); return app.exec(); } <commit_msg>Missed this file as part of #23832<commit_after>/* * Copyright (C) 2006 George Staikos <[email protected]> * Copyright (C) 2006 Dirk Mueller <[email protected]> * Copyright (C) 2006 Zack Rusin <[email protected]> * Copyright (C) 2006 Simon Hausmann <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 <qwebpage.h> #include <qwebframe.h> #include <qwebsettings.h> #include <QtGui> #include <QDebug> class InfoWidget :public QProgressBar { Q_OBJECT public: InfoWidget(QWidget *parent) : QProgressBar(parent), m_progress(0) { setMinimum(0); setMaximum(100); } QSize sizeHint() const { QSize size(100, 20); return size; } public slots: void startLoad() { setValue(m_progress); show(); } void changeLoad(int change) { m_progress = change; setValue(change); } void endLoad() { QTimer::singleShot(1000, this, SLOT(hide())); m_progress = 0; } protected: int m_progress; }; class HoverLabel : public QWidget { Q_OBJECT public: HoverLabel(QWidget *parent=0) : QWidget(parent), m_animating(false), m_percent(0) { m_timer.setInterval(1000/30); m_hideTimer.setInterval(500); m_hideTimer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); connect(&m_hideTimer, SIGNAL(timeout()), this, SLOT(hide())); } public slots: void setHoverLink(const QString &link) { m_link = link; if (m_link.isEmpty()) { m_hideTimer.start(); } else { m_hideTimer.stop(); m_oldSize = m_newSize; m_newSize = sizeForFont(); resetAnimation(); updateSize(); show(); repaint(); } } QSize sizeForFont() const { QFont f = font(); QFontMetrics fm(f); return QSize(fm.width(m_link) + 10, fm.height() + 6); } QSize sizeHint() const { if (!m_animating) return sizeForFont(); else return (m_newSize.width() > m_oldSize.width()) ? m_newSize : m_oldSize; } void updateSize() { QRect r = geometry(); QSize newSize = sizeHint(); r = QRect(r.x(), r.y(), newSize.width(), newSize.height()); setGeometry(r); } void resetAnimation() { m_animating = true; m_percent = 0; if (!m_timer.isActive()) m_timer.start(); } protected: void paintEvent(QPaintEvent *e) { QPainter p(this); p.setClipRect(e->rect()); p.setPen(QPen(Qt::black, 1)); QLinearGradient gradient(rect().topLeft(), rect().bottomLeft()); gradient.setColorAt(0, QColor(255, 255, 255, 220)); gradient.setColorAt(1, QColor(193, 193, 193, 220)); p.setBrush(QBrush(gradient)); QSize size; { //draw a nicely rounded corner rectangle. to avoid unwanted // borders we move the coordinates outsize the our clip region size = interpolate(m_oldSize, m_newSize, m_percent); QRect r(-1, 0, size.width(), size.height()+2); const int roundness = 20; QPainterPath path; path.moveTo(r.x(), r.y()); path.lineTo(r.topRight().x()-roundness, r.topRight().y()); path.cubicTo(r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y(), r.topRight().x(), r.topRight().y() + roundness); path.lineTo(r.bottomRight()); path.lineTo(r.bottomLeft()); path.closeSubpath(); p.setRenderHint(QPainter::Antialiasing); p.drawPath(path); } if (m_animating) { if (qFuzzyCompare(m_percent, 1)) { m_animating = false; m_percent = 0; m_timer.stop(); } else { m_percent += 0.1; if (m_percent >= 0.99) { m_percent = 1; } } } QString txt; QFontMetrics fm(fontMetrics()); txt = fm.elidedText(m_link, Qt::ElideRight, size.width()-5); p.drawText(5, height()-6, txt); } private: QSize interpolate(const QSize &src, const QSize &dst, qreal percent) { int widthDiff = int((dst.width() - src.width()) * percent); int heightDiff = int((dst.height() - src.height()) * percent); return QSize(src.width() + widthDiff, src.height() + heightDiff); } QString m_link; bool m_animating; QTimer m_timer; QTimer m_hideTimer; QSize m_oldSize; QSize m_newSize; qreal m_percent; }; class SearchEdit; class ClearButton : public QPushButton { Q_OBJECT public: ClearButton(QWidget *w) : QPushButton(w) { setMinimumSize(24, 24); setFixedSize(24, 24); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); int height = parentWidget()->geometry().height(); int width = height; //parentWidget()->geometry().width(); painter.setRenderHint(QPainter::Antialiasing, true); painter.setPen(Qt::lightGray); painter.setBrush(isDown() ? QColor(140, 140, 190) : underMouse() ? QColor(220, 220, 255) : QColor(200, 200, 230) ); painter.drawEllipse(4, 4, width - 8, height - 8); painter.setPen(Qt::white); int border = 8; painter.drawLine(border, border, width - border, height - border); painter.drawLine(border, height - border, width - border, border); } }; class SearchEdit : public QLineEdit { Q_OBJECT public: SearchEdit(const QString &str, QWidget *parent = 0) : QLineEdit(str, parent) { setMinimumSize(QSize(400, 24)); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setStyleSheet(":enabled { padding-right: 27px }"); clearButton = new ClearButton(this); clearButton->setGeometry(QRect(geometry().right() - 27, geometry().top() - 2, geometry().right(), geometry().bottom())); clearButton->setVisible(true); #ifndef QT_NO_CURSOR clearButton->setCursor(Qt::ArrowCursor); #endif #ifndef QT_NO_TOOLTIP clearButton->setToolTip("Clear"); #endif connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); } ~SearchEdit() { } protected: virtual void paintEvent(QPaintEvent *e) { QLineEdit::paintEvent(e); if(text().isEmpty()) clearButton->setVisible(false); else clearButton->setVisible(true); } virtual void resizeEvent(QResizeEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 0, 24, 24)); } virtual void moveEvent(QMoveEvent *) { clearButton->setParent(this); clearButton->setGeometry(QRect(width()-27, 1, 24, 24)); } QPushButton *clearButton; }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(const QUrl &url) { page = new QWebPage(this); InfoWidget *info = new InfoWidget(page); info->setGeometry(20, 20, info->sizeHint().width(), info->sizeHint().height()); connect(page, SIGNAL(loadStarted(QWebFrame*)), info, SLOT(startLoad())); connect(page, SIGNAL(loadProgressChanged(int)), info, SLOT(changeLoad(int))); connect(page, SIGNAL(loadFinished(QWebFrame*)), info, SLOT(endLoad())); connect(page, SIGNAL(loadFinished(QWebFrame*)), this, SLOT(loadFinished())); connect(page, SIGNAL(titleChanged(const QString&)), this, SLOT(setWindowTitle(const QString&))); connect(page, SIGNAL(hoveringOverLink(const QString&, const QString&)), this, SLOT(showLinkHover(const QString&, const QString&))); setCentralWidget(page); QToolBar *bar = addToolBar("Navigation"); urlEdit = new SearchEdit(url.toString()); connect(urlEdit, SIGNAL(returnPressed()), SLOT(changeLocation())); bar->addAction("Go back", page, SLOT(goBack())); bar->addAction("Stop", page, SLOT(stop())); bar->addAction("Go forward", page, SLOT(goForward())); bar->addWidget(urlEdit); hoverLabel = new HoverLabel(this); hoverLabel->hide(); page->open(url); info->raise(); } protected slots: void changeLocation() { QUrl url(urlEdit->text()); page->open(url); } void loadFinished() { urlEdit->setText(page->url().toString()); } void showLinkHover(const QString &link, const QString &toolTip) { //statusBar()->showMessage(link); hoverLabel->setHoverLink(link); #ifndef QT_NO_TOOLTIP if (!toolTip.isEmpty()) QToolTip::showText(QCursor::pos(), toolTip); #endif } protected: void resizeEvent(QResizeEvent *) { QSize hoverSize = hoverLabel->sizeHint(); hoverLabel->setGeometry(0, height()-hoverSize.height(), 300, hoverSize.height()); } private: QWebPage *page; QLineEdit *urlEdit; HoverLabel *hoverLabel; }; #include "main.moc" int main(int argc, char **argv) { QString url = QString("%1/%2").arg(QDir::homePath()).arg(QLatin1String("index.html")); QApplication app(argc, argv); QWebSettings settings = QWebSettings::global(); settings.setAttribute(QWebSettings::PluginsEnabled); QWebSettings::setGlobal(settings); const QStringList args = app.arguments(); if (args.count() > 1) url = args.at(1); MainWindow window(url); window.show(); return app.exec(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX #define INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX #include <sal/types.h> #if defined __GNUC__ #if HAVE_GCC_PRAGMA_DIAGNOSTIC_MODIFY # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" #endif #elif defined __SUNPRO_CC #pragma disable_warn #elif defined _MSC_VER #pragma warning(push, 1) #endif #include "GfxState.h" #include "GfxFont.h" #include "UnicodeMap.h" #include "Link.h" #include "Object.h" #include "OutputDev.h" #include "GlobalParams.h" #include "PDFDoc.h" #if defined __GNUC__ #if HAVE_GCC_PRAGMA_DIAGNOSTIC_MODIFY # pragma GCC diagnostic pop #endif #elif defined __SUNPRO_CC #pragma enable_warn #elif defined _MSC_VER #pragma warning(pop) #endif #include <boost/unordered_map.hpp> #include <vector> class GfxPath; class GfxFont; class PDFDoc; #include <cpp/poppler-version.h> #define POPPLER_CHECK_VERSION(major,minor,micro) \ (POPPLER_VERSION_MAJOR > (major) || \ (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR > (minor)) || \ (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR == (minor) && POPPLER_VERSION_MICRO >= (micro))) namespace pdfi { struct FontAttributes { FontAttributes( const GooString& familyName_, bool isEmbedded_, bool isBold_, bool isItalic_, bool isUnderline_, double size_ ) : familyName(), isEmbedded(isEmbedded_), isBold(isBold_), isItalic(isItalic_), isUnderline(isUnderline_), size(size_) { familyName.append(const_cast<GooString*>(&familyName_)); } FontAttributes() : familyName(), isEmbedded(false), isBold(false), isItalic(false), isUnderline(false), size(0.0) {} // xdpf goo stuff is so totally borked... // ...need to hand-code assignment FontAttributes( const FontAttributes& rSrc ) : familyName(), isEmbedded(rSrc.isEmbedded), isBold(rSrc.isBold), isItalic(rSrc.isItalic), isUnderline(rSrc.isUnderline), size(rSrc.size) { familyName.append(const_cast<GooString*>(&rSrc.familyName)); } FontAttributes& operator=( const FontAttributes& rSrc ) { familyName.clear(); familyName.append(const_cast<GooString*>(&rSrc.familyName)); isEmbedded = rSrc.isEmbedded; isBold = rSrc.isBold; isItalic = rSrc.isItalic; isUnderline = rSrc.isUnderline; size = rSrc.size; return *this; } bool operator==(const FontAttributes& rFont) const { return const_cast<GooString*>(&familyName)->cmp( const_cast<GooString*>(&rFont.familyName))==0 && isEmbedded == rFont.isEmbedded && isBold == rFont.isBold && isItalic == rFont.isItalic && isUnderline == rFont.isUnderline && size == rFont.size; } GooString familyName; bool isEmbedded; bool isBold; bool isItalic; bool isUnderline; double size; }; class PDFOutDev : public OutputDev { // not owned by this class PDFDoc* m_pDoc; mutable boost::unordered_map< long long, FontAttributes > m_aFontMap; UnicodeMap* m_pUtf8Map; int parseFont( long long nNewId, GfxFont* pFont, GfxState* state ) const; void writeFontFile( GfxFont* gfxFont ) const; void printPath( GfxPath* pPath ) const; public: explicit PDFOutDev( PDFDoc* pDoc ); ~PDFOutDev(); //----- get info about output device // Does this device use upside-down coordinates? // (Upside-down means (0,0) is the top left corner of the page.) virtual GBool upsideDown() SAL_OVERRIDE { return gTrue; } // Does this device use drawChar() or drawString()? virtual GBool useDrawChar() SAL_OVERRIDE { return gTrue; } // Does this device use beginType3Char/endType3Char? Otherwise, // text in Type 3 fonts will be drawn with drawChar/drawString. virtual GBool interpretType3Chars() SAL_OVERRIDE { return gFalse; } // Does this device need non-text content? virtual GBool needNonText() SAL_OVERRIDE { return gTrue; } //----- initialization and control // Set default transform matrix. virtual void setDefaultCTM(double *ctm) SAL_OVERRIDE; // Start a page. virtual void startPage(int pageNum, GfxState *state #if POPPLER_CHECK_VERSION(0, 23, 0) || POPPLER_CHECK_VERSION(0, 24, 0) , XRef *xref #endif ) SAL_OVERRIDE; // End a page. virtual void endPage() SAL_OVERRIDE; //----- link borders #if POPPLER_CHECK_VERSION(0, 19, 0) virtual void processLink(AnnotLink *link) SAL_OVERRIDE; #elif POPPLER_CHECK_VERSION(0, 17, 0) virtual void processLink(AnnotLink *link, Catalog *catalog) SAL_OVERRIDE; #else virtual void processLink(Link *link, Catalog *catalog) SAL_OVERRIDE; #endif //----- save/restore graphics state virtual void saveState(GfxState *state) SAL_OVERRIDE; virtual void restoreState(GfxState *state) SAL_OVERRIDE; //----- update graphics state virtual void updateCTM(GfxState *state, double m11, double m12, double m21, double m22, double m31, double m32) SAL_OVERRIDE; virtual void updateLineDash(GfxState *state) SAL_OVERRIDE; virtual void updateFlatness(GfxState *state) SAL_OVERRIDE; virtual void updateLineJoin(GfxState *state) SAL_OVERRIDE; virtual void updateLineCap(GfxState *state) SAL_OVERRIDE; virtual void updateMiterLimit(GfxState *state) SAL_OVERRIDE; virtual void updateLineWidth(GfxState *state) SAL_OVERRIDE; virtual void updateFillColor(GfxState *state) SAL_OVERRIDE; virtual void updateStrokeColor(GfxState *state) SAL_OVERRIDE; virtual void updateFillOpacity(GfxState *state) SAL_OVERRIDE; virtual void updateStrokeOpacity(GfxState *state) SAL_OVERRIDE; virtual void updateBlendMode(GfxState *state) SAL_OVERRIDE; //----- update text state virtual void updateFont(GfxState *state) SAL_OVERRIDE; virtual void updateRender(GfxState *state) SAL_OVERRIDE; //----- path painting virtual void stroke(GfxState *state) SAL_OVERRIDE; virtual void fill(GfxState *state) SAL_OVERRIDE; virtual void eoFill(GfxState *state) SAL_OVERRIDE; //----- path clipping virtual void clip(GfxState *state) SAL_OVERRIDE; virtual void eoClip(GfxState *state) SAL_OVERRIDE; //----- text drawing virtual void drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, CharCode code, int nBytes, Unicode *u, int uLen) SAL_OVERRIDE; virtual void drawString(GfxState *state, GooString *s) SAL_OVERRIDE; virtual void endTextObject(GfxState *state) SAL_OVERRIDE; //----- image drawing virtual void drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif GBool inlineImg) SAL_OVERRIDE; virtual void drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif int *maskColors, GBool inlineImg) SAL_OVERRIDE; virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert #if POPPLER_CHECK_VERSION(0, 12, 0) , GBool maskInterpolate #endif ) SAL_OVERRIDE; virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap #if POPPLER_CHECK_VERSION(0, 12, 0) , GBool maskInterpolate #endif ) SAL_OVERRIDE; void setPageNum( int nNumPages ); }; } extern FILE* g_binary_out; // note: if you ever hcange Output_t, please keep in mind that the current code // relies on it being of 8 bit size typedef Guchar Output_t; typedef std::vector< Output_t > OutputBuffer; #endif // INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>GCC diagnostic push / pop requires HAVE_GCC_PRAGMA_DIAGNOSTIC_SCOPE<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX #define INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX #include <sal/types.h> #if defined __GNUC__ #if HAVE_GCC_PRAGMA_DIAGNOSTIC_SCOPE # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" #endif #elif defined __SUNPRO_CC #pragma disable_warn #elif defined _MSC_VER #pragma warning(push, 1) #endif #include "GfxState.h" #include "GfxFont.h" #include "UnicodeMap.h" #include "Link.h" #include "Object.h" #include "OutputDev.h" #include "GlobalParams.h" #include "PDFDoc.h" #if defined __GNUC__ #if HAVE_GCC_PRAGMA_DIAGNOSTIC_SCOPE # pragma GCC diagnostic pop #endif #elif defined __SUNPRO_CC #pragma enable_warn #elif defined _MSC_VER #pragma warning(pop) #endif #include <boost/unordered_map.hpp> #include <vector> class GfxPath; class GfxFont; class PDFDoc; #include <cpp/poppler-version.h> #define POPPLER_CHECK_VERSION(major,minor,micro) \ (POPPLER_VERSION_MAJOR > (major) || \ (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR > (minor)) || \ (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR == (minor) && POPPLER_VERSION_MICRO >= (micro))) namespace pdfi { struct FontAttributes { FontAttributes( const GooString& familyName_, bool isEmbedded_, bool isBold_, bool isItalic_, bool isUnderline_, double size_ ) : familyName(), isEmbedded(isEmbedded_), isBold(isBold_), isItalic(isItalic_), isUnderline(isUnderline_), size(size_) { familyName.append(const_cast<GooString*>(&familyName_)); } FontAttributes() : familyName(), isEmbedded(false), isBold(false), isItalic(false), isUnderline(false), size(0.0) {} // xdpf goo stuff is so totally borked... // ...need to hand-code assignment FontAttributes( const FontAttributes& rSrc ) : familyName(), isEmbedded(rSrc.isEmbedded), isBold(rSrc.isBold), isItalic(rSrc.isItalic), isUnderline(rSrc.isUnderline), size(rSrc.size) { familyName.append(const_cast<GooString*>(&rSrc.familyName)); } FontAttributes& operator=( const FontAttributes& rSrc ) { familyName.clear(); familyName.append(const_cast<GooString*>(&rSrc.familyName)); isEmbedded = rSrc.isEmbedded; isBold = rSrc.isBold; isItalic = rSrc.isItalic; isUnderline = rSrc.isUnderline; size = rSrc.size; return *this; } bool operator==(const FontAttributes& rFont) const { return const_cast<GooString*>(&familyName)->cmp( const_cast<GooString*>(&rFont.familyName))==0 && isEmbedded == rFont.isEmbedded && isBold == rFont.isBold && isItalic == rFont.isItalic && isUnderline == rFont.isUnderline && size == rFont.size; } GooString familyName; bool isEmbedded; bool isBold; bool isItalic; bool isUnderline; double size; }; class PDFOutDev : public OutputDev { // not owned by this class PDFDoc* m_pDoc; mutable boost::unordered_map< long long, FontAttributes > m_aFontMap; UnicodeMap* m_pUtf8Map; int parseFont( long long nNewId, GfxFont* pFont, GfxState* state ) const; void writeFontFile( GfxFont* gfxFont ) const; void printPath( GfxPath* pPath ) const; public: explicit PDFOutDev( PDFDoc* pDoc ); ~PDFOutDev(); //----- get info about output device // Does this device use upside-down coordinates? // (Upside-down means (0,0) is the top left corner of the page.) virtual GBool upsideDown() SAL_OVERRIDE { return gTrue; } // Does this device use drawChar() or drawString()? virtual GBool useDrawChar() SAL_OVERRIDE { return gTrue; } // Does this device use beginType3Char/endType3Char? Otherwise, // text in Type 3 fonts will be drawn with drawChar/drawString. virtual GBool interpretType3Chars() SAL_OVERRIDE { return gFalse; } // Does this device need non-text content? virtual GBool needNonText() SAL_OVERRIDE { return gTrue; } //----- initialization and control // Set default transform matrix. virtual void setDefaultCTM(double *ctm) SAL_OVERRIDE; // Start a page. virtual void startPage(int pageNum, GfxState *state #if POPPLER_CHECK_VERSION(0, 23, 0) || POPPLER_CHECK_VERSION(0, 24, 0) , XRef *xref #endif ) SAL_OVERRIDE; // End a page. virtual void endPage() SAL_OVERRIDE; //----- link borders #if POPPLER_CHECK_VERSION(0, 19, 0) virtual void processLink(AnnotLink *link) SAL_OVERRIDE; #elif POPPLER_CHECK_VERSION(0, 17, 0) virtual void processLink(AnnotLink *link, Catalog *catalog) SAL_OVERRIDE; #else virtual void processLink(Link *link, Catalog *catalog) SAL_OVERRIDE; #endif //----- save/restore graphics state virtual void saveState(GfxState *state) SAL_OVERRIDE; virtual void restoreState(GfxState *state) SAL_OVERRIDE; //----- update graphics state virtual void updateCTM(GfxState *state, double m11, double m12, double m21, double m22, double m31, double m32) SAL_OVERRIDE; virtual void updateLineDash(GfxState *state) SAL_OVERRIDE; virtual void updateFlatness(GfxState *state) SAL_OVERRIDE; virtual void updateLineJoin(GfxState *state) SAL_OVERRIDE; virtual void updateLineCap(GfxState *state) SAL_OVERRIDE; virtual void updateMiterLimit(GfxState *state) SAL_OVERRIDE; virtual void updateLineWidth(GfxState *state) SAL_OVERRIDE; virtual void updateFillColor(GfxState *state) SAL_OVERRIDE; virtual void updateStrokeColor(GfxState *state) SAL_OVERRIDE; virtual void updateFillOpacity(GfxState *state) SAL_OVERRIDE; virtual void updateStrokeOpacity(GfxState *state) SAL_OVERRIDE; virtual void updateBlendMode(GfxState *state) SAL_OVERRIDE; //----- update text state virtual void updateFont(GfxState *state) SAL_OVERRIDE; virtual void updateRender(GfxState *state) SAL_OVERRIDE; //----- path painting virtual void stroke(GfxState *state) SAL_OVERRIDE; virtual void fill(GfxState *state) SAL_OVERRIDE; virtual void eoFill(GfxState *state) SAL_OVERRIDE; //----- path clipping virtual void clip(GfxState *state) SAL_OVERRIDE; virtual void eoClip(GfxState *state) SAL_OVERRIDE; //----- text drawing virtual void drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, CharCode code, int nBytes, Unicode *u, int uLen) SAL_OVERRIDE; virtual void drawString(GfxState *state, GooString *s) SAL_OVERRIDE; virtual void endTextObject(GfxState *state) SAL_OVERRIDE; //----- image drawing virtual void drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif GBool inlineImg) SAL_OVERRIDE; virtual void drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif int *maskColors, GBool inlineImg) SAL_OVERRIDE; virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert #if POPPLER_CHECK_VERSION(0, 12, 0) , GBool maskInterpolate #endif ) SAL_OVERRIDE; virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, #if POPPLER_CHECK_VERSION(0, 12, 0) GBool interpolate, #endif Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap #if POPPLER_CHECK_VERSION(0, 12, 0) , GBool maskInterpolate #endif ) SAL_OVERRIDE; void setPageNum( int nNumPages ); }; } extern FILE* g_binary_out; // note: if you ever hcange Output_t, please keep in mind that the current code // relies on it being of 8 bit size typedef Guchar Output_t; typedef std::vector< Output_t > OutputBuffer; #endif // INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>