text
stringlengths
54
60.6k
<commit_before>#pragma once #include <iterator> #include <cstdlib> //malloc, realloc #include <cstring> //memcpy, memmove #include <exception> //bad_alloc #include <type_traits> #include <utility> namespace tyti { template<typename T> class any_iterator : std::iterator<std::bidirectional_iterator_tag, T> { //functionpointer save structure struct TypeInfos { void(*const inc_fn)(void*); void(*const dec_fn)(void*); const bool(*const equal_fn)(const void*,const void*); const T*(*const deref_fn)(const void*); void(*const dtor_fn)(void*); void(*const copy_ctor_fn)(void*,const void*); void(*const move_ctor_fn)(void*, const void*); const size_t size; }; template<typename IterType> TypeInfos* getFunctionInfos() { #if !defined(_MSC_VER) || (_MSC_VER > 1600) // skip vs 2010. It doesnt implement "is_copy_constructible" static_assert(std::is_copy_constructible<IterType>::value, "any_iterator requires a copy constructable type"); static_assert(std::is_destructible<IterType>::value, "any_iterator requires a destructable type"); #endif static TypeInfos ti = { &any_iterator::inc<IterType>, &any_iterator::dec<IterType>, &any_iterator::equal<IterType>, &any_iterator::deref<IterType>, //(std::is_trivially_destructible<IterType>::value) ? //static_cast<void(*)(void*)>(nullptr) : &any_iterator::dtor<IterType>, //(std::is_trivially_copy_constructible<IterType>::value) ? //static_cast<void(*)(void*,const void*)>(nullptr) : &any_iterator::copyConstructor<IterType>, &any_iterator::moveConstructor<IterType>, sizeof(IterType) }; return &ti; } //access functions template<typename Iter> static void inc(void* _ptr) { ++(*reinterpret_cast<Iter*>(_ptr)); } template<typename Iter> static void dec(void* _ptr) { --(*reinterpret_cast<Iter*>(_ptr)); } template<typename Iter> static const T* deref(const void* _ptr) { return &(*(*reinterpret_cast<const Iter*>(_ptr))); } template<typename Iter> static const bool equal(const void* _lhs, const void* _rhs) { return *reinterpret_cast<const Iter*>(_lhs) == *reinterpret_cast<const Iter*>(_rhs); } template<typename Iter> static void dtor(void* _ptr) { reinterpret_cast<Iter*>(_ptr)->~Iter(); } template<typename Iter> static void copyConstructor(void* _dst, const void* _src) { new (_dst) Iter(*reinterpret_cast<const Iter*>(_src)); } template<typename Iter> static void moveConstructor(void* _dst, const void* _src) { new (_dst) Iter(std::move(*reinterpret_cast<const Iter*>(_src))); } // helper functions inline void destruct() { ti_->dtor_fn(ptr_); } void switch_type(const TypeInfos* _newType) { destruct(); if (ti_->size < _newType->size) { ptr_ = std::realloc(ptr_, _newType->size); if (!ptr_) throw std::bad_alloc(); } ti_ = _newType; } inline void copy_and_assign(const void* _src) { ti_->copy_ctor_fn(ptr_, _src); } inline void move_iter(const void* _src) { ti_->move_ctor_fn(ptr_, _src); } // member variables void* ptr_; const TypeInfos* ti_; /// Interface public: template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type> explicit any_iterator(const IterType& _iter) : ptr_(std::malloc(sizeof(IterType))), ti_(getFunctionInfos<IterType>()) { if (!ptr_) throw std::bad_alloc(); copy_and_assign(&_iter); } template<typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type> explicit any_iterator(IterType&& _iter) : ptr_(std::malloc(_iter.ti_->size)), ti_(std::move(_iter.ti_)) { if (!ptr_) throw std::bad_alloc(); move_iter(_iter.ptr_); } any_iterator(const any_iterator& _iter) : ptr_(std::malloc(_iter.ti_->size)), ti_(_iter.ti_) { if (!ptr_) throw std::bad_alloc(); copy_and_assign(_iter.ptr_); } any_iterator(any_iterator&& _iter) : ptr_(_iter.ptr), ti_(_iter.ti_) { _iter.ptr_ = nullptr; _iter.ti_ = getFunctionInfos<int>();//dont call dtor } template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type > const any_iterator& operator=(const IterType& _iter) { switch_type(getFunctionInfos<IterType>()); copy_and_assign(&_iter); return *this; } template <typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type> const any_iterator& operator=(IterType&& _iter) { switch_type(getFunctionInfos<IterType>()); move_iter(&_iter); return *this; } const any_iterator& operator=(const any_iterator& _iter) { switch_type(_iter.ti_); copy_and_assign(_iter.ptr_); return *this; } const any_iterator& operator=(any_iterator&& _iter) { ti_ = _iter.ti_; ptr_ = _iter.ptr_; _iter.ti_ = getFunctionInfos<int>(); _iter.ptr_ = nullptr; return *this; } ~any_iterator() { destruct(); std::free(ptr_); } bool operator==(const any_iterator& _rhs) const { if (ti_ != _rhs.ti_) //different types return false; return ti_->equal_fn(ptr_, _rhs.ptr_); } template <typename IterType> bool operator==(const IterType& _rhs) const { return ti_->equal_fn(ptr_, reinterpret_cast<const void*>(&_rhs)); } template <typename IterType> bool operator!=(const IterType& _rhs) const{ return !operator==(_rhs); } /// Standard pre-increment operator any_iterator& operator++() { ti_->inc_fn(ptr_); return *this; } /// Standard post-increment operator any_iterator operator++(int) { any_iterator cpy(*this); ti_->inc_fn(ptr_); return cpy; } /// Standard pre-decrement operator any_iterator& operator--() { ti_->dec_fn(ptr_); return *this; } /// Standard post-decrement operator any_iterator operator--(int) { any_iterator cpy(*this); ti_->dec_fn(ptr_); return cpy; } const T& operator*() const { return *(ti_->deref_fn(ptr_)); } /// Standard pointer operator. const T* operator->() const { return ti_->deref_fn(ptr_); } }; // C++17 todo: //if msvc >= 2017 or gcc with c++17 support //#include <any> //using AnyIterator = AnyIteratorT<std::any>; //endif } // end namespace tyti template<typename IterT, typename T> bool operator==(const IterT&& _lhs, const tyti::any_iterator<T>&& _rhs) { return _rhs.operator==(std::forward<IterT>(_lhs)); } template<typename IterT, typename T> bool operator!=(IterT&& _lhs, tyti::any_iterator<T>&& _rhs) { return _rhs.operator!=(std::forward<IterT>(_lhs)); }<commit_msg>removes some redundant constraint checking since it is already included as a requirement in the iterator_tag<commit_after>#pragma once #include <iterator> #include <cstdlib> //malloc, realloc #include <cstring> //memcpy, memmove #include <exception> //bad_alloc #include <type_traits> #include <utility> namespace tyti { template<typename T> class any_iterator : std::iterator<std::bidirectional_iterator_tag, T> { //functionpointer save structure struct TypeInfos { void(*const inc_fn)(void*); void(*const dec_fn)(void*); const bool(*const equal_fn)(const void*,const void*); const T*(*const deref_fn)(const void*); void(*const dtor_fn)(void*); void(*const copy_ctor_fn)(void*,const void*); void(*const move_ctor_fn)(void*, const void*); const size_t size; }; template<typename IterType> TypeInfos* getFunctionInfos() { static TypeInfos ti = { &any_iterator::inc<IterType>, &any_iterator::dec<IterType>, &any_iterator::equal<IterType>, &any_iterator::deref<IterType>, //(std::is_trivially_destructible<IterType>::value) ? //static_cast<void(*)(void*)>(nullptr) : &any_iterator::dtor<IterType>, //(std::is_trivially_copy_constructible<IterType>::value) ? //static_cast<void(*)(void*,const void*)>(nullptr) : &any_iterator::copyConstructor<IterType>, &any_iterator::moveConstructor<IterType>, sizeof(IterType) }; return &ti; } //access functions template<typename Iter> static void inc(void* _ptr) { ++(*reinterpret_cast<Iter*>(_ptr)); } template<typename Iter> static void dec(void* _ptr) { --(*reinterpret_cast<Iter*>(_ptr)); } template<typename Iter> static const T* deref(const void* _ptr) { return &(*(*reinterpret_cast<const Iter*>(_ptr))); } template<typename Iter> static const bool equal(const void* _lhs, const void* _rhs) { return *reinterpret_cast<const Iter*>(_lhs) == *reinterpret_cast<const Iter*>(_rhs); } template<typename Iter> static void dtor(void* _ptr) { reinterpret_cast<Iter*>(_ptr)->~Iter(); } template<typename Iter> static void copyConstructor(void* _dst, const void* _src) { new (_dst) Iter(*reinterpret_cast<const Iter*>(_src)); } template<typename Iter> static void moveConstructor(void* _dst, const void* _src) { new (_dst) Iter(std::move(*reinterpret_cast<const Iter*>(_src))); } // helper functions inline void destruct() { ti_->dtor_fn(ptr_); } void switch_type(const TypeInfos* _newType) { destruct(); if (ti_->size < _newType->size) { ptr_ = std::realloc(ptr_, _newType->size); if (!ptr_) throw std::bad_alloc(); } ti_ = _newType; } inline void copy_and_assign(const void* _src) { ti_->copy_ctor_fn(ptr_, _src); } inline void move_iter(const void* _src) { ti_->move_ctor_fn(ptr_, _src); } // member variables void* ptr_; const TypeInfos* ti_; /// Interface public: template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type> explicit any_iterator(const IterType& _iter) : ptr_(std::malloc(sizeof(IterType))), ti_(getFunctionInfos<IterType>()) { if (!ptr_) throw std::bad_alloc(); copy_and_assign(&_iter); } template<typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type> explicit any_iterator(IterType&& _iter) : ptr_(std::malloc(_iter.ti_->size)), ti_(std::move(_iter.ti_)) { if (!ptr_) throw std::bad_alloc(); move_iter(_iter.ptr_); } any_iterator(const any_iterator& _iter) : ptr_(std::malloc(_iter.ti_->size)), ti_(_iter.ti_) { if (!ptr_) throw std::bad_alloc(); copy_and_assign(_iter.ptr_); } any_iterator(any_iterator&& _iter) : ptr_(_iter.ptr), ti_(_iter.ti_) { _iter.ptr_ = nullptr; _iter.ti_ = getFunctionInfos<int>();//dont call dtor } template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type > const any_iterator& operator=(const IterType& _iter) { switch_type(getFunctionInfos<IterType>()); copy_and_assign(&_iter); return *this; } template <typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type> const any_iterator& operator=(IterType&& _iter) { switch_type(getFunctionInfos<IterType>()); move_iter(&_iter); return *this; } const any_iterator& operator=(const any_iterator& _iter) { switch_type(_iter.ti_); copy_and_assign(_iter.ptr_); return *this; } const any_iterator& operator=(any_iterator&& _iter) { ti_ = _iter.ti_; ptr_ = _iter.ptr_; _iter.ti_ = getFunctionInfos<int>(); _iter.ptr_ = nullptr; return *this; } ~any_iterator() { destruct(); std::free(ptr_); } bool operator==(const any_iterator& _rhs) const { if (ti_ != _rhs.ti_) //different types return false; return ti_->equal_fn(ptr_, _rhs.ptr_); } template <typename IterType> bool operator==(const IterType& _rhs) const { return ti_->equal_fn(ptr_, reinterpret_cast<const void*>(&_rhs)); } template <typename IterType> bool operator!=(const IterType& _rhs) const{ return !operator==(_rhs); } /// Standard pre-increment operator any_iterator& operator++() { ti_->inc_fn(ptr_); return *this; } /// Standard post-increment operator any_iterator operator++(int) { any_iterator cpy(*this); ti_->inc_fn(ptr_); return cpy; } /// Standard pre-decrement operator any_iterator& operator--() { ti_->dec_fn(ptr_); return *this; } /// Standard post-decrement operator any_iterator operator--(int) { any_iterator cpy(*this); ti_->dec_fn(ptr_); return cpy; } const T& operator*() const { return *(ti_->deref_fn(ptr_)); } /// Standard pointer operator. const T* operator->() const { return ti_->deref_fn(ptr_); } }; // C++17 todo: //if msvc >= 2017 or gcc with c++17 support //#include <any> //using AnyIterator = AnyIteratorT<std::any>; //endif } // end namespace tyti template<typename IterT, typename T> bool operator==(const IterT&& _lhs, const tyti::any_iterator<T>&& _rhs) { return _rhs.operator==(std::forward<IterT>(_lhs)); } template<typename IterT, typename T> bool operator!=(IterT&& _lhs, tyti::any_iterator<T>&& _rhs) { return _rhs.operator!=(std::forward<IterT>(_lhs)); }<|endoftext|>
<commit_before>#pragma once #include <hop_bits/optimisationAlgorithm.hpp> namespace hop { class CovarianceMatrixAdaptationEvolutionStrategy : public OptimisationAlgorithm { public: //TODO: which input parameters should be added to the constructor? explicit CovarianceMatrixAdaptationEvolutionStrategy( const std::shared_ptr<OptimisationProblem> optimisationProblem); CovarianceMatrixAdaptationEvolutionStrategy(const CovarianceMatrixAdaptationEvolutionStrategy&) = delete; CovarianceMatrixAdaptationEvolutionStrategy& operator=(const CovarianceMatrixAdaptationEvolutionStrategy&) = delete; std::string to_string() const override; protected: void optimiseImplementation() override; // input parameters // N unsigned int numberOfDimensions_; // xmean arma::Col<double> objectiveValues_; double sigma_; // stopfitness double stopValue_; // selection parameters int lambda_; double mu_; arma::Col<double> weights_; double mueff_; // adaptation parameters double cc_; double cs_; double c1_; double cmu_; double damps_; // dynamic parameters and constants arma::Col<double> pc_; arma::Col<double> ps_; arma::Mat<double> B_; arma::Mat<double> D_; arma::Mat<double> C_; arma::Mat<double> invsqrtC_; double eigeneval_; double chiN_; //function to use double frosenbrock(arma::Col<double> x); }; } <commit_msg>fix: The parameter D_ should be a column vector<commit_after>#pragma once #include <hop_bits/optimisationAlgorithm.hpp> namespace hop { class CovarianceMatrixAdaptationEvolutionStrategy : public OptimisationAlgorithm { public: //TODO: which input parameters should be added to the constructor? explicit CovarianceMatrixAdaptationEvolutionStrategy( const std::shared_ptr<OptimisationProblem> optimisationProblem); CovarianceMatrixAdaptationEvolutionStrategy(const CovarianceMatrixAdaptationEvolutionStrategy&) = delete; CovarianceMatrixAdaptationEvolutionStrategy& operator=(const CovarianceMatrixAdaptationEvolutionStrategy&) = delete; std::string to_string() const override; protected: void optimiseImplementation() override; // input parameters // N unsigned int numberOfDimensions_; // xmean arma::Col<double> objectiveValues_; double sigma_; // stopfitness double stopValue_; // selection parameters int lambda_; double mu_; arma::Col<double> weights_; double mueff_; // adaptation parameters double cc_; double cs_; double c1_; double cmu_; double damps_; // dynamic parameters and constants arma::Col<double> pc_; arma::Col<double> ps_; arma::Mat<double> B_; arma::Col<double> D_; arma::Mat<double> C_; arma::Mat<double> invsqrtC_; double eigeneval_; double chiN_; //function to use double frosenbrock(arma::Col<double> x); }; } <|endoftext|>
<commit_before>// win32.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <cstdio> #include "test.h" int _tmain(int argc, _TCHAR* argv[]) { Test t; int i = t.function_one(400, true, "Hello World!"); printf("function_one: %i\n", i); bool b = t.function_two(4.2e14, (void *)(0x100), 0.125f); printf("function_two: %i\n", b); double d = t.function_three(256); printf("function_three: %f\n", d); unsigned __int64 u = t.function_four(); printf("function_four: %llu\n", u); return 0; } <commit_msg>Fixed the new test calls.<commit_after>// win32.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <cstdio> #include "test.h" int _tmain(int argc, _TCHAR* argv[]) { Test t; int i = t.function_one(400, true, "Hello World!"); printf("function_one: %i\n", i); bool b = t.function_two(4.2e14, (void *)(0x100), 0.125f); printf("function_two: %i\n", b); double d = t.function_three(256); printf("function_three: %f\n", d); unsigned __int64 u = t.function_four(); printf("function_four: %llu\n", u); float f = t.function_five(4294967306); printf("function_five: %f\n", f); return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ <commit_msg>Add DLL Calibration<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file adr32s.H /// @brief Subroutines for the PHY ADR32S registers /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_ADR32S_H_ #define _MSS_ADR32S_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <lib/shared/mss_const.H> #include <lib/utils/scom.H> namespace mss { // I have a dream that the PHY code can be shared among controllers. So, I drive the // engine from a set of traits. This might be folly. Allow me to dream. BRS /// /// @class adr32sTraits /// @brief a collection of traits associated with the PHY ADR32S interface /// @tparam T fapi2::TargetType representing the PHY /// template< fapi2::TargetType T > class adr32sTraits; /// /// @class adr32sTraits /// @brief a collection of traits associated with the Centaur PHY ADR32S interface /// template<> class adr32sTraits<fapi2::TARGET_TYPE_MBA> { }; /// /// @class adr32sTraits /// @brief a collection of traits associated with the Nimbus PHY ADR32S /// template<> class adr32sTraits<fapi2::TARGET_TYPE_MCA> { public: // Number of ADR32S units static constexpr uint64_t ADR32S_COUNT = 2; // MCA ADR32S control registers all come in pairs. static const std::vector<uint64_t> DLL_CNFG_REG; enum { DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_RESET, DLL_CNTL_INIT_RXDLL_CAL_UPDATE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_UPDATE, DLL_CNTL_REGS_RXDLL_CAL_SKIP = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP, DLL_CNTL_REGS_RXDLL_CAL_SKIP_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP_LEN, DLL_CNTL_REGS_RXDLL_COARSE_ADJ_BY2 = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_COARSE_ADJ_BY2, DLL_CNTL_RXREG_FILTER_LENGTH_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC, DLL_CNTL_RXREG_FILTER_LENGTH_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC_LEN, DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC, DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC_LEN, DLL_CNTL_EN_DRIVER_INVFB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_EN_DRIVER_INVFB_DC, DLL_CNTL_RXREG_FINECAL_2XILSB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FINECAL_2XILSB_DC, DLL_CNTL_CAL_GOOD = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_GOOD, DLL_CNTL_CAL_ERROR = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR, DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR_FINE, }; }; namespace adr32s { /// /// @brief Read DLL_CNTL /// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY /// @tparam T fapi2 Target Type - derived /// @tparam TT traits type defaults to adr32sTraits<T> /// @param[in] i_target the fapi2 target of the port /// @param[out] o_data the value of the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> > inline fapi2::ReturnCode read_dll_cntl( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data ) { static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range"); FAPI_TRY( mss::getScom(i_target, TT::DLL_CNFG_REG[I], o_data) ); FAPI_INF("dll_cntl adrs32%d: 0x%016lx", I, o_data); fapi_try_exit: return fapi2::current_err; } /// /// @brief Write DLL_CNTL_ADR32S0 /// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY /// @tparam T fapi2 Target Type - derived /// @tparam TT traits type defaults to adr32sTraits<T> /// @param[in] i_target the fapi2 target of the port /// @param[in] i_data the value of the register /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> > inline fapi2::ReturnCode write_dll_cntl( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data ) { static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range"); FAPI_INF("dll_cntl adr32s%d: 0x%016lx", I, i_data); FAPI_TRY( mss::putScom(i_target, TT::DLL_CNFG_REG[I], i_data) ); fapi_try_exit: return fapi2::current_err; } // // Reseting the DLL registers TODO RTC:156518 // /// /// @brief Set the DLL cal reset (begins DLL cal operations) /// @tparam T fapi2 Target Type - derived /// @tparam TT traits type defaults to adr32sTraits<T> /// @param[in] o_data the value of the register /// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit /// @note Default state is 'low' as writing a 0 forces the cal to begin. /// template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits<T> > inline void set_dll_cal_reset( fapi2::buffer<uint64_t>& o_data, const states i_state = mss::LOW ) { FAPI_INF("set_dll_cal_reset %s", (i_state == mss::LOW ? "low" : "high")); o_data.writeBit<TT::DLL_CNTL_INIT_RXDLL_CAL_RESET>(i_state); } } // close namespace adr } // close namespace mss #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Fondazione Istituto Italiano di Tecnologia * Authors: Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ #include <iDynTree/InverseKinematics.h> #include <iDynTree/KinDynComputations.h> #include <iDynTree/Core/TestUtils.h> #include <iDynTree/Model/JointState.h> #include <iDynTree/Model/ModelTestUtils.h> #include "testModels.h" #include <cstdio> #include <cstdlib> #include <ctime> /** * Return the current time in seconds, with respect * to an arbitrary point in time. */ inline double clockInSec() { clock_t ret = clock(); return ((double)ret)/((double)CLOCKS_PER_SEC); } iDynTree::JointPosDoubleArray getRandomJointPositions(const iDynTree::Model & model) { iDynTree::JointPosDoubleArray sRandom(model); getRandomJointPositions(sRandom,model); return sRandom; } struct simpleChainIKOptions { iDynTree::InverseKinematicsRotationParametrization rotationParametrization; bool useDesiredJointPositionsToActualValue; bool useDesiredJointPositionsToRandomValue; }; void simpleChainIK(int minNrOfJoints, int maxNrOfJoints, const iDynTree::InverseKinematicsRotationParametrization rotationParametrization) { // Solve a simple IK problem for a chain, with no constraints for (int i = minNrOfJoints; i <= maxNrOfJoints; i++) { assert(i >= 2); std::cerr << "~~~~~~~> simpleChainIK with " << i << " dofs " << std::endl; bool noFixedJoints = true; iDynTree::Model chain = iDynTree::getRandomChain(i,10,noFixedJoints); ASSERT_EQUAL_DOUBLE(i, chain.getNrOfDOFs()); // Name of the targetFrame the leaf added by getRandomChain std::string targetFrame = "link" + iDynTree::int2string(i - 1); // Create IK iDynTree::InverseKinematics ik; bool ok = ik.setModel(chain); ASSERT_IS_TRUE(ok); // Always express the target as cost ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone); // Use the requested parametrization ik.setRotationParametrization(rotationParametrization); // Create also a KinDyn object to perform forward kinematics for the desired values and the optimized ones iDynTree::KinDynComputations kinDynDes; ok = kinDynDes.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); iDynTree::KinDynComputations kinDynOpt; ok = kinDynOpt.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); // Create a random vector of internal joint positions // used to get reasonable values for the constraints and the targets iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model()); ok = kinDynDes.setJointPos(s); ASSERT_IS_TRUE(ok); // Add the fixed base constraint ok = ik.addFrameConstraint("link1", kinDynDes.getWorldTransform("link1")); //ok = ik.addFrameRotationConstraint("link1", iDynTree::Transform::Identity().getRotation()); //ok = ik.addFramePositionConstraint("link1", iDynTree::Transform::Identity().getPosition()); ASSERT_IS_TRUE(ok); // Add target ok = ik.addPositionTarget(targetFrame, kinDynDes.getWorldTransform(targetFrame)); ASSERT_IS_TRUE(ok); // Add a random initial guess iDynTree::Transform baseDes = kinDynDes.getWorldBaseTransform(); iDynTree::JointPosDoubleArray sInitial = getRandomJointPositions(ik.model()); ik.setInitialCondition(&(baseDes),&(sInitial)); // Add a random desired position iDynTree::JointPosDoubleArray sDesired = getRandomJointPositions(ik.model()); ik.setDesiredJointConfiguration(sDesired,1e-12); // Start from the initial one double tic = clockInSec(); ok = ik.solve(); double toc = clockInSec(); ASSERT_IS_TRUE(ok); // Get the solution iDynTree::Transform baseOpt = iDynTree::Transform::Identity(); iDynTree::JointPosDoubleArray sOpt(ik.model()); ik.getSolution(baseOpt,sOpt); iDynTree::Twist dummyVel; dummyVel.zero(); iDynTree::Vector3 dummyGrav; dummyGrav.zero(); iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model()); dummyJointVel.zero(); kinDynOpt.setRobotState(baseOpt,sOpt,dummyVel,dummyJointVel,dummyGrav); double tolConstraints = 1e-7; double tolTargets = 1e-6; // Check if the base link constraint is still valid ASSERT_EQUAL_TRANSFORM_TOL(kinDynOpt.getWorldTransform("link1"), kinDynDes.getWorldTransform("link1"), tolConstraints); // Check if the target is realized ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(targetFrame).getPosition(), kinDynOpt.getWorldTransform(targetFrame).getPosition(), tolTargets); } } // Check the consistency of a simple humanoid wholebody IK test case void simpleHumanoidWholeBodyIKConsistency(const iDynTree::InverseKinematicsRotationParametrization rotationParametrization) { iDynTree::InverseKinematics ik; bool ok = ik.loadModelFromFile(getAbsModelPath("iCubGenova02.urdf")); ASSERT_IS_TRUE(ok); //ik.setFloatingBaseOnFrameNamed("l_foot"); ik.setRotationParametrization(rotationParametrization); // Create also a KinDyn object to perform forward kinematics for the desired values iDynTree::KinDynComputations kinDynDes; ok = kinDynDes.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); // Create a random vector of internal joint positions // used to get reasonable values for the constraints and the targets iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model()); ok = kinDynDes.setJointPos(s); ASSERT_IS_TRUE(ok); // Create a simple IK problem with the foot constraint // The l_sole frame is our world absolute frame (i.e. {}^A H_{l_sole} = identity ok = ik.addFrameConstraint("l_foot",kinDynDes.getWorldTransform("l_foot")); ASSERT_IS_TRUE(ok); std::cerr << "kinDynDes.getWorldTransform(l_foot) : " << kinDynDes.getWorldTransform("l_foot").toString() << std::endl; // The relative position of the r_sole should be the initial one ok = ik.addFrameConstraint("r_sole",kinDynDes.getWorldTransform("r_sole")); ASSERT_IS_TRUE(ok); // The two cartesian targets should be reasonable values ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone); ok = ik.addPositionTarget("l_elbow_1",kinDynDes.getWorldTransform("l_elbow_1")); ASSERT_IS_TRUE(ok); //ok = ik.addPositionTarget("r_elbow_1",kinDynDes.getRelativeTransform("l_sole","r_elbow_1").getPosition()); //ASSERT_IS_TRUE(ok); iDynTree::Transform initialH = kinDynDes.getWorldBaseTransform(); ik.setInitialCondition(&initialH,&s); ik.setDesiredJointConfiguration(s,1e-15); // Solve the optimization problem double tic = clockInSec(); ok = ik.solve(); double toc = clockInSec(); std::cerr << "Inverse Kinematics solved in " << toc-tic << " seconds. " << std::endl; ASSERT_IS_TRUE(ok); iDynTree::Transform basePosOptimized; iDynTree::JointPosDoubleArray sOptimized(ik.model()); sOptimized.zero(); ik.getSolution(basePosOptimized,sOptimized); // We create a new KinDyn object to perform forward kinematics for the optimized values iDynTree::KinDynComputations kinDynOpt; kinDynOpt.loadRobotModel(ik.model()); iDynTree::Twist dummyVel; dummyVel.zero(); iDynTree::Vector3 dummyGrav; dummyGrav.zero(); iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model()); dummyJointVel.zero(); kinDynOpt.setRobotState(basePosOptimized, sOptimized, dummyVel, dummyJointVel, dummyGrav); // Check that the contraint and the targets are respected double tolConstraints = 1e-7; double tolTargets = 1e-6; ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform("l_foot"),kinDynOpt.getWorldTransform("l_foot"),tolConstraints); ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform("r_sole"),kinDynOpt.getWorldTransform("r_sole"),tolConstraints); ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform("l_elbow_1").getPosition(), kinDynOpt.getWorldTransform("l_elbow_1").getPosition(),tolTargets); return; } int main() { // Improve repetability (at least in the same platform) srand(0); simpleChainIK(2,13,iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw); // This is not working at the moment, there is some problem with quaternion constraints //simpleChainIK(10,iDynTree::InverseKinematicsRotationParametrizationQuaternion); simpleHumanoidWholeBodyIKConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw); return EXIT_SUCCESS; } <commit_msg>Improve robustness of Inverse Kinematics test<commit_after>/* * Copyright (C) 2017 Fondazione Istituto Italiano di Tecnologia * Authors: Silvio Traversaro * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT * */ #include <iDynTree/InverseKinematics.h> #include <iDynTree/KinDynComputations.h> #include <iDynTree/Core/TestUtils.h> #include <iDynTree/Model/JointState.h> #include <iDynTree/Model/ModelTestUtils.h> #include "testModels.h" #include <cstdio> #include <cstdlib> #include <ctime> /** * Return the current time in seconds, with respect * to an arbitrary point in time. */ inline double clockInSec() { clock_t ret = clock(); return ((double)ret)/((double)CLOCKS_PER_SEC); } iDynTree::JointPosDoubleArray getRandomJointPositions(const iDynTree::Model & model) { iDynTree::JointPosDoubleArray sRandom(model); getRandomJointPositions(sRandom,model); return sRandom; } inline iDynTree::JointPosDoubleArray getRandomJointPositionsCloseTo(const iDynTree::Model& model, iDynTree::VectorDynSize s, double maxDelta) { iDynTree::JointPosDoubleArray vec(model); assert(vec.size() == model.getNrOfPosCoords()); for(iDynTree::JointIndex jntIdx=0; jntIdx < model.getNrOfJoints(); jntIdx++) { iDynTree::IJointConstPtr jntPtr = model.getJoint(jntIdx); if( jntPtr->hasPosLimits() ) { for(int i=0; i < jntPtr->getNrOfPosCoords(); i++) { int dofIndex = jntPtr->getDOFsOffset()+i; double max = std::min(jntPtr->getMaxPosLimit(i),s(dofIndex)+maxDelta); double min = std::max(jntPtr->getMinPosLimit(i),s(dofIndex)-maxDelta); vec(dofIndex) = iDynTree::getRandomDouble(min,max); } } else { for(int i=0; i < jntPtr->getNrOfPosCoords(); i++) { int dofIndex = jntPtr->getDOFsOffset()+i; vec(jntPtr->getDOFsOffset()+i) = iDynTree::getRandomDouble(s(dofIndex)-maxDelta,s(dofIndex)+maxDelta); } } } return vec; } struct simpleChainIKOptions { iDynTree::InverseKinematicsRotationParametrization rotationParametrization; bool useDesiredJointPositionsToActualValue; bool useDesiredJointPositionsToRandomValue; }; void simpleChainIK(int minNrOfJoints, int maxNrOfJoints, const iDynTree::InverseKinematicsRotationParametrization rotationParametrization) { // Solve a simple IK problem for a chain, with no constraints for (int i = minNrOfJoints; i <= maxNrOfJoints; i++) { assert(i >= 2); std::cerr << "~~~~~~~> simpleChainIK with " << i << " dofs " << std::endl; bool noFixedJoints = true; iDynTree::Model chain = iDynTree::getRandomChain(i,10,noFixedJoints); ASSERT_EQUAL_DOUBLE(i, chain.getNrOfDOFs()); // Name of the targetFrame the leaf added by getRandomChain std::string targetFrame = "link" + iDynTree::int2string(i - 1); // Create IK iDynTree::InverseKinematics ik; bool ok = ik.setModel(chain); ASSERT_IS_TRUE(ok); // Always express the target as cost ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone); // Use the requested parametrization ik.setRotationParametrization(rotationParametrization); ik.setTol(1e-6); ik.setConstrTol(1e-7); // Create also a KinDyn object to perform forward kinematics for the desired values and the optimized ones iDynTree::KinDynComputations kinDynDes; ok = kinDynDes.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); iDynTree::KinDynComputations kinDynOpt; ok = kinDynOpt.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); // Create a random vector of internal joint positions // used to get reasonable values for the constraints and the targets iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model()); ok = kinDynDes.setJointPos(s); ASSERT_IS_TRUE(ok); // Add the fixed base constraint ok = ik.addFrameConstraint("link1", kinDynDes.getWorldTransform("link1")); //ok = ik.addFrameRotationConstraint("link1", iDynTree::Transform::Identity().getRotation()); //ok = ik.addFramePositionConstraint("link1", iDynTree::Transform::Identity().getPosition()); ASSERT_IS_TRUE(ok); // Add target ok = ik.addPositionTarget(targetFrame, kinDynDes.getWorldTransform(targetFrame)); ASSERT_IS_TRUE(ok); // Add a random initial guess iDynTree::Transform baseDes = kinDynDes.getWorldBaseTransform(); // Set a max delta to avoid local minima in testing double maxDelta = 0.01; iDynTree::JointPosDoubleArray sInitial = getRandomJointPositionsCloseTo(ik.model(),s,maxDelta); ik.setInitialCondition(&(baseDes),&(sInitial)); // Add a random desired position iDynTree::JointPosDoubleArray sDesired = getRandomJointPositions(ik.model()); ik.setDesiredJointConfiguration(sDesired,1e-12); // Start from the initial one double tic = clockInSec(); ok = ik.solve(); double toc = clockInSec(); ASSERT_IS_TRUE(ok); // Get the solution iDynTree::Transform baseOpt = iDynTree::Transform::Identity(); iDynTree::JointPosDoubleArray sOpt(ik.model()); ik.getSolution(baseOpt,sOpt); iDynTree::Twist dummyVel; dummyVel.zero(); iDynTree::Vector3 dummyGrav; dummyGrav.zero(); iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model()); dummyJointVel.zero(); kinDynOpt.setRobotState(baseOpt,sOpt,dummyVel,dummyJointVel,dummyGrav); double tolConstraints = 1e-6; double tolTargets = 1e-3; // Check if the base link constraint is still valid ASSERT_EQUAL_TRANSFORM_TOL(kinDynOpt.getWorldTransform("link1"), kinDynDes.getWorldTransform("link1"), tolConstraints); // Check if the target is realized ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform(targetFrame).getPosition(), kinDynOpt.getWorldTransform(targetFrame).getPosition(), tolTargets); } } // Check the consistency of a simple humanoid wholebody IK test case void simpleHumanoidWholeBodyIKConsistency(const iDynTree::InverseKinematicsRotationParametrization rotationParametrization) { iDynTree::InverseKinematics ik; bool ok = ik.loadModelFromFile(getAbsModelPath("iCubGenova02.urdf")); ASSERT_IS_TRUE(ok); //ik.setFloatingBaseOnFrameNamed("l_foot"); ik.setRotationParametrization(rotationParametrization); // Create also a KinDyn object to perform forward kinematics for the desired values iDynTree::KinDynComputations kinDynDes; ok = kinDynDes.loadRobotModel(ik.model()); ASSERT_IS_TRUE(ok); // Create a random vector of internal joint positions // used to get reasonable values for the constraints and the targets iDynTree::JointPosDoubleArray s = getRandomJointPositions(kinDynDes.model()); ok = kinDynDes.setJointPos(s); ASSERT_IS_TRUE(ok); // Create a simple IK problem with the foot constraint // The l_sole frame is our world absolute frame (i.e. {}^A H_{l_sole} = identity ok = ik.addFrameConstraint("l_foot",kinDynDes.getWorldTransform("l_foot")); ASSERT_IS_TRUE(ok); std::cerr << "kinDynDes.getWorldTransform(l_foot) : " << kinDynDes.getWorldTransform("l_foot").toString() << std::endl; // The relative position of the r_sole should be the initial one ok = ik.addFrameConstraint("r_sole",kinDynDes.getWorldTransform("r_sole")); ASSERT_IS_TRUE(ok); // The two cartesian targets should be reasonable values ik.setTargetResolutionMode(iDynTree::InverseKinematicsTreatTargetAsConstraintNone); ok = ik.addPositionTarget("l_elbow_1",kinDynDes.getWorldTransform("l_elbow_1")); ASSERT_IS_TRUE(ok); //ok = ik.addPositionTarget("r_elbow_1",kinDynDes.getRelativeTransform("l_sole","r_elbow_1").getPosition()); //ASSERT_IS_TRUE(ok); iDynTree::Transform initialH = kinDynDes.getWorldBaseTransform(); ik.setInitialCondition(&initialH,&s); ik.setDesiredJointConfiguration(s,1e-15); // Solve the optimization problem double tic = clockInSec(); ok = ik.solve(); double toc = clockInSec(); std::cerr << "Inverse Kinematics solved in " << toc-tic << " seconds. " << std::endl; ASSERT_IS_TRUE(ok); iDynTree::Transform basePosOptimized; iDynTree::JointPosDoubleArray sOptimized(ik.model()); sOptimized.zero(); ik.getSolution(basePosOptimized,sOptimized); // We create a new KinDyn object to perform forward kinematics for the optimized values iDynTree::KinDynComputations kinDynOpt; kinDynOpt.loadRobotModel(ik.model()); iDynTree::Twist dummyVel; dummyVel.zero(); iDynTree::Vector3 dummyGrav; dummyGrav.zero(); iDynTree::JointDOFsDoubleArray dummyJointVel(ik.model()); dummyJointVel.zero(); kinDynOpt.setRobotState(basePosOptimized, sOptimized, dummyVel, dummyJointVel, dummyGrav); // Check that the contraint and the targets are respected double tolConstraints = 1e-7; double tolTargets = 1e-6; ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform("l_foot"),kinDynOpt.getWorldTransform("l_foot"),tolConstraints); ASSERT_EQUAL_TRANSFORM_TOL(kinDynDes.getWorldTransform("r_sole"),kinDynOpt.getWorldTransform("r_sole"),tolConstraints); ASSERT_EQUAL_VECTOR_TOL(kinDynDes.getWorldTransform("l_elbow_1").getPosition(), kinDynOpt.getWorldTransform("l_elbow_1").getPosition(),tolTargets); return; } int main() { // Improve repetability (at least in the same platform) srand(0); simpleChainIK(2,13,iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw); // This is not working at the moment, there is some problem with quaternion constraints //simpleChainIK(10,iDynTree::InverseKinematicsRotationParametrizationQuaternion); simpleHumanoidWholeBodyIKConsistency(iDynTree::InverseKinematicsRotationParametrizationRollPitchYaw); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::ExtractElement: return ConstantExpr::getExtractElement(Op0, Op1); case Instruction::InsertElement: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getInsertElement(Op0, Op1, Op2); case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a /// getelementptr constantexpr, return the constant value being addressed by the /// constant expression, or null if something is funny and we can't decide. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE) { if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) return 0; // Do not allow stepping over the value! // Loop over all of the operands, tracking down which value we are // addressing... gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); for (++I; I != E; ++I) if (const StructType *STy = dyn_cast<StructType>(*I)) { ConstantUInt *CU = cast<ConstantUInt>(I.getOperand()); assert(CU->getValue() < STy->getNumElements() && "Struct index out of range!"); unsigned El = (unsigned)CU->getValue(); if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { C = CS->getOperand(El); } else if (isa<ConstantAggregateZero>(C)) { C = Constant::getNullValue(STy->getElementType(El)); } else if (isa<UndefValue>(C)) { C = UndefValue::get(STy->getElementType(El)); } else { return 0; } } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) { if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) { if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0; if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) C = CA->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(ATy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(ATy->getElementType()); else return 0; } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) { if ((uint64_t)CI->getRawValue() >= PTy->getNumElements()) return 0; if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) C = CP->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(PTy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(PTy->getElementType()); else return 0; } else { return 0; } } else { return 0; } return C; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { if (!I->use_empty() || isa<TerminatorInst>(I)) return false; if (!I->mayWriteToMemory()) return true; if (CallInst *CI = dyn_cast<CallInst>(I)) if (Function *F = CI->getCalledFunction()) switch (F->getIntrinsicID()) { default: break; case Intrinsic::returnaddress: case Intrinsic::frameaddress: case Intrinsic::stacksave: case Intrinsic::isunordered_f32: case Intrinsic::isunordered_f64: case Intrinsic::bswap_i16: case Intrinsic::bswap_i32: case Intrinsic::bswap_i64: case Intrinsic::ctpop_i8: case Intrinsic::ctpop_i16: case Intrinsic::ctpop_i32: case Intrinsic::ctpop_i64: case Intrinsic::ctlz_i8: case Intrinsic::ctlz_i16: case Intrinsic::ctlz_i32: case Intrinsic::ctlz_i64: case Intrinsic::cttz_i8: case Intrinsic::cttz_i16: case Intrinsic::cttz_i32: case Intrinsic::cttz_i64: case Intrinsic::sqrt_f32: case Intrinsic::sqrt_f64: return true; // These intrinsics have no side effects. } return false; } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } <commit_msg>use autogenerated side-effect information<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::ExtractElement: return ConstantExpr::getExtractElement(Op0, Op1); case Instruction::InsertElement: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getInsertElement(Op0, Op1, Op2); case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a /// getelementptr constantexpr, return the constant value being addressed by the /// constant expression, or null if something is funny and we can't decide. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE) { if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) return 0; // Do not allow stepping over the value! // Loop over all of the operands, tracking down which value we are // addressing... gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); for (++I; I != E; ++I) if (const StructType *STy = dyn_cast<StructType>(*I)) { ConstantUInt *CU = cast<ConstantUInt>(I.getOperand()); assert(CU->getValue() < STy->getNumElements() && "Struct index out of range!"); unsigned El = (unsigned)CU->getValue(); if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { C = CS->getOperand(El); } else if (isa<ConstantAggregateZero>(C)) { C = Constant::getNullValue(STy->getElementType(El)); } else if (isa<UndefValue>(C)) { C = UndefValue::get(STy->getElementType(El)); } else { return 0; } } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) { if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) { if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0; if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) C = CA->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(ATy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(ATy->getElementType()); else return 0; } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) { if ((uint64_t)CI->getRawValue() >= PTy->getNumElements()) return 0; if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) C = CP->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(PTy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(PTy->getElementType()); else return 0; } else { return 0; } } else { return 0; } return C; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { if (!I->use_empty() || isa<TerminatorInst>(I)) return false; if (!I->mayWriteToMemory()) return true; if (CallInst *CI = dyn_cast<CallInst>(I)) if (Function *F = CI->getCalledFunction()) { #define GET_SIDE_EFFECT_INFO #include "llvm/Intrinsics.gen" #undef GET_SIDE_EFFECT_INFO } return false; } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } <|endoftext|>
<commit_before>#include <catch.hpp> #include <rapidcheck-catch.h> #include <numeric> #include "util/Predictable.h" #include "util/GenUtils.h" #include "util/ArbitraryRandom.h" #include "rapidcheck/newgen/detail/ExecRaw.h" #include "rapidcheck/shrinkable/Operations.h" #include "rapidcheck/seq/Operations.h" using namespace rc; using namespace rc::test; using namespace rc::newgen::detail; namespace { template<int N> Gen<std::pair<std::vector<int>, Recipe>> testExecGen() { return execRaw( [=](const FixedCountdown<N> &n) { std::vector<int> values; values.push_back(n.value); while (values.size() < (n.value + 1)) values.push_back(*genFixedCountdown(N)); return values; }); } } // namespace TEST_CASE("execRaw") { SECTION("uses correct arbitrary instance for arguments") { auto values = execRaw([]( const Predictable &a, const Predictable &b, const Predictable &c) { return std::make_tuple(a, b, c); })(Random(), 0).value().first; REQUIRE(isArbitraryPredictable(std::get<0>(values))); REQUIRE(isArbitraryPredictable(std::get<1>(values))); REQUIRE(isArbitraryPredictable(std::get<2>(values))); } SECTION("shrinks arguments like a tuple") { typedef std::tuple<FixedCountdown<1>, FixedCountdown<2>, FixedCountdown<3>> TupleT; auto execShrinkable = execRaw([]( const FixedCountdown<1> &a, const FixedCountdown<2> &b, const FixedCountdown<3> &c) { return std::make_tuple(a, b, c); })(Random(), 0); auto tupleShrinkable = newgen::tuple( newgen::arbitrary<FixedCountdown<1>>(), newgen::arbitrary<FixedCountdown<2>>(), newgen::arbitrary<FixedCountdown<3>>())(Random(), 0); auto mappedShrinkable = shrinkable::map( execShrinkable, [](std::pair<TupleT, Recipe> &&x) { return std::move(x.first); }); REQUIRE(mappedShrinkable == tupleShrinkable); } prop("traversing a random path through the shrink tree yields the expected" " values", []{ const auto shrinkable = testExecGen<5>()(Random(), 0); const auto path = *gen::collection<std::vector<bool>>( gen::arbitrary<bool>()); std::vector<int> accepted = shrinkable.value().first; auto acceptedShrinkable = shrinkable; auto shrinks = shrinkable.shrinks(); int i = 0; int x = 5; for (bool accept : path) { if (i >= accepted.size()) { RC_ASSERT(!shrinks.next()); break; } auto shrink = *shrinks.next(); auto actual = shrink.value().first; auto expected = accepted; expected[i] = --x; // First element determines the size expected.resize(expected[0] + 1); RC_ASSERT(actual == expected); if (accept) { accepted = expected; acceptedShrinkable = shrink; shrinks = shrink.shrinks(); } if (x == 0) { x = 5; i++; } } }); prop("the number of shrinks is never never more than the sum of the number" " of shrinks for the requested values", []{ const auto shrinkable = testExecGen<5>()(Random(), 0); int i = *gen::ranged<int>(0, 5); const auto shrink = *seq::at(shrinkable.shrinks(), i); const auto value = shrink.value().first; int maxShrinks = std::accumulate(begin(value), end(value), 0); RC_ASSERT(seq::length(shrink.shrinks()) <= maxShrinks); }); prop("passes on the correct size", [] { int expectedSize = *gen::nonNegative<int>(); int n = *gen::ranged<int>(1, 10); auto shrinkable = execRaw([=](const PassedSize &sz) { *genFixedCountdown(3); // Force some shrinks std::vector<int> sizes; sizes.push_back(sz.value); while (sizes.size() < n) sizes.push_back(*genSize()); return sizes; })(Random(), expectedSize); auto valueShrinkable = shrinkable::map( shrinkable, [](std::pair<std::vector<int>, Recipe> &&x) { return std::move(x.first); }); RC_ASSERT( shrinkable::all( valueShrinkable, [=](const Shrinkable<std::vector<int>> &x) { auto sizes = x.value(); return std::all_of( begin(sizes), end(sizes), [=](int sz) { return sz == expectedSize; }); })); }); prop("passes on sequentially split generators", [](const Random &initial) { int n = *gen::ranged<int>(1, 10); auto shrinkable = execRaw([=](const PassedRandom &rnd) { std::vector<Random> randoms; randoms.push_back(rnd.value); while (randoms.size() < n) randoms.push_back(*genRandom()); // Force some shrinks, must be last because it will steal a // random split otherwise *genFixedCountdown(3); return randoms; })(initial, 0); Random r(initial); std::vector<Random> expected; // The arguments are generated as a tuple so we want the same // splitting behavior expected.push_back( std::get<0>(newgen::tuple(genRandom())(r.split(), 0).value())); while (expected.size() < n) expected.push_back(r.split()); auto valueShrinkable = shrinkable::map( shrinkable, [](std::pair<std::vector<Random>, Recipe> &&x) { return std::move(x.first); }); RC_ASSERT( shrinkable::all( valueShrinkable, [=](const Shrinkable<std::vector<Random>> &x) { return x.value() == expected; })); }); SECTION("the ingredients of the recipe exactly match the generated value") { REQUIRE( shrinkable::all( testExecGen<3>()(Random(), 0), [](const Shrinkable<std::pair<std::vector<int>, Recipe>> &x) { typedef std::tuple<FixedCountdown<3>> ArgTuple; const auto pair = x.value(); const auto recipe = pair.second; std::vector<int> actual; auto argTuple = recipe.ingredients.front().value().get<ArgTuple>(); actual.push_back(std::get<0>(argTuple).value); auto it = recipe.ingredients.begin() + 1; for (; it != end(recipe.ingredients); it++) actual.push_back(it->value().get<int>()); return actual == pair.first; })); } SECTION("works with non-copyable types") { auto shrinkable = execRaw([=](NonCopyable nc) { return std::move(nc); })(Random(), 0); REQUIRE(isArbitraryPredictable(shrinkable.value().first)); } // TODO shrink tests? } <commit_msg>Move ExecRawTests to new framework<commit_after>#include <catch.hpp> #include <rapidcheck-catch.h> #include <numeric> #include "util/Predictable.h" #include "util/GenUtils.h" #include "util/ArbitraryRandom.h" #include "rapidcheck/newgen/detail/ExecRaw.h" #include "rapidcheck/shrinkable/Operations.h" #include "rapidcheck/seq/Operations.h" using namespace rc; using namespace rc::test; using namespace rc::newgen::detail; namespace { template<int N> Gen<std::pair<std::vector<int>, Recipe>> testExecGen() { return execRaw( [=](const FixedCountdown<N> &n) { std::vector<int> values; values.push_back(n.value); while (values.size() < (n.value + 1)) values.push_back(*genFixedCountdown(N)); return values; }); } } // namespace TEST_CASE("execRaw") { SECTION("uses correct arbitrary instance for arguments") { auto values = execRaw([]( const Predictable &a, const Predictable &b, const Predictable &c) { return std::make_tuple(a, b, c); })(Random(), 0).value().first; REQUIRE(isArbitraryPredictable(std::get<0>(values))); REQUIRE(isArbitraryPredictable(std::get<1>(values))); REQUIRE(isArbitraryPredictable(std::get<2>(values))); } SECTION("shrinks arguments like a tuple") { typedef std::tuple<FixedCountdown<1>, FixedCountdown<2>, FixedCountdown<3>> TupleT; auto execShrinkable = execRaw([]( const FixedCountdown<1> &a, const FixedCountdown<2> &b, const FixedCountdown<3> &c) { return std::make_tuple(a, b, c); })(Random(), 0); auto tupleShrinkable = newgen::tuple( newgen::arbitrary<FixedCountdown<1>>(), newgen::arbitrary<FixedCountdown<2>>(), newgen::arbitrary<FixedCountdown<3>>())(Random(), 0); auto mappedShrinkable = shrinkable::map( execShrinkable, [](std::pair<TupleT, Recipe> &&x) { return std::move(x.first); }); REQUIRE(mappedShrinkable == tupleShrinkable); } newprop( "traversing a random path through the shrink tree yields the expected" " values", []{ const auto shrinkable = testExecGen<5>()(Random(), 0); const auto path = *newgen::container<std::vector<bool>>( newgen::arbitrary<bool>()); std::vector<int> accepted = shrinkable.value().first; auto acceptedShrinkable = shrinkable; auto shrinks = shrinkable.shrinks(); int i = 0; int x = 5; for (bool accept : path) { if (i >= accepted.size()) { RC_ASSERT(!shrinks.next()); break; } auto shrink = *shrinks.next(); auto actual = shrink.value().first; auto expected = accepted; expected[i] = --x; // First element determines the size expected.resize(expected[0] + 1); RC_ASSERT(actual == expected); if (accept) { accepted = expected; acceptedShrinkable = shrink; shrinks = shrink.shrinks(); } if (x == 0) { x = 5; i++; } } }); newprop( "the number of shrinks is never never more than the sum of the number" " of shrinks for the requested values", []{ const auto shrinkable = testExecGen<5>()(Random(), 0); int i = *newgen::inRange<int>(0, 5); const auto shrink = *seq::at(shrinkable.shrinks(), i); const auto value = shrink.value().first; int maxShrinks = std::accumulate(begin(value), end(value), 0); RC_ASSERT(seq::length(shrink.shrinks()) <= maxShrinks); }); newprop( "passes on the correct size", [] { int expectedSize = *newgen::nonNegative<int>(); int n = *newgen::inRange<int>(1, 10); auto shrinkable = execRaw([=](const PassedSize &sz) { *genFixedCountdown(3); // Force some shrinks std::vector<int> sizes; sizes.push_back(sz.value); while (sizes.size() < n) sizes.push_back(*genSize()); return sizes; })(Random(), expectedSize); auto valueShrinkable = shrinkable::map( shrinkable, [](std::pair<std::vector<int>, Recipe> &&x) { return std::move(x.first); }); RC_ASSERT( shrinkable::all( valueShrinkable, [=](const Shrinkable<std::vector<int>> &x) { auto sizes = x.value(); return std::all_of( begin(sizes), end(sizes), [=](int sz) { return sz == expectedSize; }); })); }); newprop( "passes on sequentially split generators", [](const Random &initial) { int n = *newgen::inRange<int>(1, 10); auto shrinkable = execRaw([=](const PassedRandom &rnd) { std::vector<Random> randoms; randoms.push_back(rnd.value); while (randoms.size() < n) randoms.push_back(*genRandom()); // Force some shrinks, must be last because it will steal a // random split otherwise *genFixedCountdown(3); return randoms; })(initial, 0); Random r(initial); std::vector<Random> expected; // The arguments are generated as a tuple so we want the same // splitting behavior expected.push_back( std::get<0>(newgen::tuple(genRandom())(r.split(), 0).value())); while (expected.size() < n) expected.push_back(r.split()); auto valueShrinkable = shrinkable::map( shrinkable, [](std::pair<std::vector<Random>, Recipe> &&x) { return std::move(x.first); }); RC_ASSERT( shrinkable::all( valueShrinkable, [=](const Shrinkable<std::vector<Random>> &x) { return x.value() == expected; })); }); SECTION("the ingredients of the recipe exactly match the generated value") { REQUIRE( shrinkable::all( testExecGen<3>()(Random(), 0), [](const Shrinkable<std::pair<std::vector<int>, Recipe>> &x) { typedef std::tuple<FixedCountdown<3>> ArgTuple; const auto pair = x.value(); const auto recipe = pair.second; std::vector<int> actual; auto argTuple = recipe.ingredients.front().value().get<ArgTuple>(); actual.push_back(std::get<0>(argTuple).value); auto it = recipe.ingredients.begin() + 1; for (; it != end(recipe.ingredients); it++) actual.push_back(it->value().get<int>()); return actual == pair.first; })); } SECTION("works with non-copyable types") { auto shrinkable = execRaw([=](NonCopyable nc) { return std::move(nc); })(Random(), 0); REQUIRE(isArbitraryPredictable(shrinkable.value().first)); } // TODO shrink tests? } <|endoftext|>
<commit_before>#include "Halide.h" #include <cstdio> #include <cstdint> #include "benchmark.h" using namespace Halide; template<typename T> bool test(int w, bool div) { Func f, g, h; Var x, y; size_t bits = sizeof(T)*8; bool is_signed = (T)(-1) < (T)(0); printf("%sInt(%2d, %2d) ", is_signed ? " " : "U", (int)bits, w); int min_val = 2, num_vals = 254; if (bits <= 8 && is_signed) { // There are two types of integer division that cause runtime crashes: // 1) Division by zero // 2) Division of the smallest negative number by -1 (because // the result overflows) // In either case, let's avoid overflows to dodge such errors. num_vals = 126; } Image<T> input(w, num_vals); for (int y = 0; y < num_vals; y++) { for (int x = 0; x < input.width(); x++) { uint32_t bits = rand() ^ (rand() << 16); input(x, y) = (T)bits; } } if (div) { // Test div f(x, y) = input(x, y) / cast<T>(y + min_val); // Reference good version g(x, y) = input(x, y) / cast<T>(y + min_val); // Version that uses fast_integer_divide h(x, y) = Halide::fast_integer_divide(input(x, y), cast<uint8_t>(y + min_val)); } else { // Test mod f(x, y) = input(x, y) % cast<T>(y + min_val); // Reference good version g(x, y) = input(x, y) % cast<T>(y + min_val); // Version that uses fast_integer_modulo h(x, y) = Halide::fast_integer_modulo(input(x, y), cast<uint8_t>(y + min_val)); } // Try dividing by all the known constants using vectors f.bound(y, 0, num_vals).bound(x, 0, input.width()).unroll(y); h.bound(x, 0, input.width()); if (w > 1) { f.vectorize(x); h.vectorize(x); } f.compile_jit(); g.compile_jit(); h.compile_jit(); Image<T> correct = g.realize(input.width(), num_vals); double t_correct = benchmark(5, 200, [&]() { g.realize(correct); }); Image<T> fast = f.realize(input.width(), num_vals); double t_fast = benchmark(5, 200, [&]() { f.realize(fast); }); Image<T> fast_dynamic = h.realize(input.width(), num_vals); double t_fast_dynamic = benchmark(10, 200, [&]() { h.realize(fast_dynamic); }); printf("%6.3f %6.3f\n", t_correct / t_fast, t_correct / t_fast_dynamic); for (int y = 0; y < num_vals; y++) { for (int x = 0; x < input.width(); x++) { if (fast(x, y) != correct(x, y)) { printf("fast(%d, %d) = %lld instead of %lld (%lld/%d)\n", x, y, (long long int)fast(x, y), (long long int)correct(x, y), (long long int)input(x, y), (T)(y + min_val)); return false; } } } return true; } int main(int argc, char **argv) { srand(time(nullptr)); bool success = true; for (int i = 0; i < 2; i++) { const char *name = (i == 0 ? "divisor" : "modulus"); printf("type const-%s speed-up runtime-%s speed-up\n", name, name); // Scalar success = success && test<int32_t>(1, i == 0); success = success && test<int16_t>(1, i == 0); success = success && test<int8_t>(1, i == 0); success = success && test<uint32_t>(1, i == 0); success = success && test<uint16_t>(1, i == 0); success = success && test<uint8_t>(1, i == 0); // Vector success = success && test<int32_t>(8, i == 0); success = success && test<int16_t>(16, i == 0); success = success && test<int8_t>(32, i == 0); success = success && test<uint32_t>(8, i == 0); success = success && test<uint16_t>(16, i == 0); success = success && test<uint8_t>(32, i == 0); } if (success) { printf("Success!\n"); return 0; } else { return -1; } } <commit_msg>Fix mismatched iteration count<commit_after>#include "Halide.h" #include <cstdio> #include <cstdint> #include "benchmark.h" using namespace Halide; template<typename T> bool test(int w, bool div) { Func f, g, h; Var x, y; size_t bits = sizeof(T)*8; bool is_signed = (T)(-1) < (T)(0); printf("%sInt(%2d, %2d) ", is_signed ? " " : "U", (int)bits, w); int min_val = 2, num_vals = 254; if (bits <= 8 && is_signed) { // There are two types of integer division that cause runtime crashes: // 1) Division by zero // 2) Division of the smallest negative number by -1 (because // the result overflows) // In either case, let's avoid overflows to dodge such errors. num_vals = 126; } Image<T> input(w, num_vals); for (int y = 0; y < num_vals; y++) { for (int x = 0; x < input.width(); x++) { uint32_t bits = rand() ^ (rand() << 16); input(x, y) = (T)bits; } } if (div) { // Test div f(x, y) = input(x, y) / cast<T>(y + min_val); // Reference good version g(x, y) = input(x, y) / cast<T>(y + min_val); // Version that uses fast_integer_divide h(x, y) = Halide::fast_integer_divide(input(x, y), cast<uint8_t>(y + min_val)); } else { // Test mod f(x, y) = input(x, y) % cast<T>(y + min_val); // Reference good version g(x, y) = input(x, y) % cast<T>(y + min_val); // Version that uses fast_integer_modulo h(x, y) = Halide::fast_integer_modulo(input(x, y), cast<uint8_t>(y + min_val)); } // Try dividing by all the known constants using vectors f.bound(y, 0, num_vals).bound(x, 0, input.width()).unroll(y); h.bound(x, 0, input.width()); if (w > 1) { f.vectorize(x); h.vectorize(x); } f.compile_jit(); g.compile_jit(); h.compile_jit(); Image<T> correct = g.realize(input.width(), num_vals); double t_correct = benchmark(5, 200, [&]() { g.realize(correct); }); Image<T> fast = f.realize(input.width(), num_vals); double t_fast = benchmark(5, 200, [&]() { f.realize(fast); }); Image<T> fast_dynamic = h.realize(input.width(), num_vals); double t_fast_dynamic = benchmark(5, 200, [&]() { h.realize(fast_dynamic); }); printf("%6.3f %6.3f\n", t_correct / t_fast, t_correct / t_fast_dynamic); for (int y = 0; y < num_vals; y++) { for (int x = 0; x < input.width(); x++) { if (fast(x, y) != correct(x, y)) { printf("fast(%d, %d) = %lld instead of %lld (%lld/%d)\n", x, y, (long long int)fast(x, y), (long long int)correct(x, y), (long long int)input(x, y), (T)(y + min_val)); return false; } } } return true; } int main(int argc, char **argv) { srand(time(nullptr)); bool success = true; for (int i = 0; i < 2; i++) { const char *name = (i == 0 ? "divisor" : "modulus"); printf("type const-%s speed-up runtime-%s speed-up\n", name, name); // Scalar success = success && test<int32_t>(1, i == 0); success = success && test<int16_t>(1, i == 0); success = success && test<int8_t>(1, i == 0); success = success && test<uint32_t>(1, i == 0); success = success && test<uint16_t>(1, i == 0); success = success && test<uint8_t>(1, i == 0); // Vector success = success && test<int32_t>(8, i == 0); success = success && test<int16_t>(16, i == 0); success = success && test<int8_t>(32, i == 0); success = success && test<uint32_t>(8, i == 0); success = success && test<uint16_t>(16, i == 0); success = success && test<uint8_t>(32, i == 0); } if (success) { printf("Success!\n"); return 0; } else { return -1; } } <|endoftext|>
<commit_before>/* The class for calculating the global (not detector specific) quality assurance. It reuses the following TLists from its base class AliQADataMaker::fRecPointsQAList (for keeping the track residuals) AliQADataMaker::fESDsQAList (for keeping global ESD QA data) */ #include <TPDGCode.h> #include <TH1F.h> #include "AliGlobalQADataMaker.h" #include "AliGeomManager.h" #include "AliESDEvent.h" #include "AliESDv0.h" ClassImp(AliGlobalQADataMaker) void AliGlobalQADataMaker::InitRecPoints() { //------------------------------------------------------ // This function books the histograms of *track*residuals* // as a part of global QA //------------------------------------------------------ Char_t *name[]={ "SPD1 residuals Y","SPD1 residuals Z", "SPD2 residuals Y","SPD2 residuals Z", "SDD1 residuals Y","SDD1 residuals Z", "SDD2 residuals Y","SDD2 residuals Z", "SSD1 residuals Y","SSD1 residuals Z", "SSD2 residuals Y","SSD2 residuals Z", "TPC1 residuals Y","TPC1 residuals Z", "TPC2 residuals Y","TPC2 residuals Z", "TRD1 residuals Y","TRD1 residuals Z", "TRD2 residuals Y","TRD2 residuals Z", "TRD3 residuals Y","TRD3 residuals Z", "TRD4 residuals Y","TRD4 residuals Z", "TRD5 residuals Y","TRD5 residuals Z", "TRD6 residuals Y","TRD6 residuals Z", "TOF residuals Y","TOF residuals Z", "PHOS1 residuals Y","PHOS1 residuals Z", "PHOS2 residuals Y","PHOS2 residuals Z", "HMPID residuals Y","HMPID residuals Z", "MUON residuals Y","MUON residuals Z", "EMCAL residuals Y","EMCAL residuals Z" }; for (Int_t m=1; m<AliGeomManager::kLastLayer; m++) { Int_t i=2*m-2; TH1F *h=new TH1F(name[i],name[i],100,-5.,5.); Add2RecPointsList(h,i); h=new TH1F(name[i+1],name[i+1],100,-5.,5.); Add2RecPointsList(h,i+1); } } void AliGlobalQADataMaker::InitESDs() { //------------------------------------------------------ // This function books the ESD QA histograms // as a part of global QA //------------------------------------------------------ {// Cluster related QA Char_t *name[]={ "Fraction of the assigned clusters in ITS", "Fraction of the assigned clusters in TPC", "Fraction of the assigned clusters in TRD" }; Add2ESDsList(new TH1F(name[0],name[0],100,0.,2.),kClr0); Add2ESDsList(new TH1F(name[1],name[1],100,0.,2.),kClr1); Add2ESDsList(new TH1F(name[2],name[2],100,0.,2.),kClr2); } {// Track related QA Char_t *name[]={ "Track azimuthal distribution (rad)", // kTrk0 "Track pseudo-rapidity distribution", // kTrk1 "TPC: track momentum distribution (GeV)", // kTrk2 "TPC-ITS matched: track momentum distribution (GeV)", // kTrk3 "TPC-TOF matched: track momentum distribution (GeV)", // kTrk4 "TPC-ITS track-matching probability", // kTrk5 "TPC-TOF track-matching probability" // kTrk6 }; Add2ESDsList(new TH1F(name[0],name[0],100,-0.02,6.30),kTrk0); Add2ESDsList(new TH1F(name[1],name[1],100,-2.00,2.00),kTrk1); Add2ESDsList(new TH1F(name[2],name[2],50, 0.20,5.00),kTrk2); Add2ESDsList(new TH1F(name[3],name[3],50, 0.20,5.00),kTrk3); Add2ESDsList(new TH1F(name[4],name[4],50, 0.20,5.00),kTrk4); Add2ESDsList(new TH1F(name[5],name[5],50, 0.20,5.00),kTrk5); Add2ESDsList(new TH1F(name[6],name[6],50, 0.20,5.00),kTrk6); } {// V0 related QA Char_t *name[]={ "K0s mass (GeV)", "Lambda0 + Lambda0Bar mass (GeV)" }; Add2ESDsList(new TH1F(name[0],name[0],50, 0.4477,0.5477),kV0s0); Add2ESDsList(new TH1F(name[1],name[1],50, 1.0657,1.1657),kV0s1); } {// PID related QA Char_t *name[]={ "ITS: dEdx (ADC) for particles with momentum 0.4 - 0.5 (GeV)", "TPC: dEdx (ADC) for particles with momentum 0.4 - 0.5 (GeV)", "TOF: tracking - measured (ps)" }; Add2ESDsList(new TH1F(name[0],name[0],50,0.00,200.),kPid0); Add2ESDsList(new TH1F(name[1],name[1],50,0.00,100.),kPid1); Add2ESDsList(new TH1F(name[2],name[2],50,-3500.,3500.),kPid2); } } void AliGlobalQADataMaker::MakeESDs(AliESDEvent * event) { //----------------------------------------------------------- // This function fills the ESD QA histograms // as a part of global QA //----------------------------------------------------------- const AliESDEvent *esd=event; Int_t ntrk=esd->GetNumberOfTracks() ; for (Int_t i=0; i<ntrk; i++) { const AliESDtrack *track=esd->GetTrack(i); // Cluster related QA if (track->IsOn(AliESDtrack::kITSrefit)) { Int_t n=track->GetITSclusters(0); GetESDsData(kClr0)->Fill(Float_t(n)/6.); //6 is the number of ITS layers } if (track->IsOn(AliESDtrack::kTPCrefit)) { Int_t n =track->GetTPCNcls(); Int_t nf=track->GetTPCNclsF(); // number of crossed TPC pad rows GetESDsData(kClr1)->Fill(Float_t(n)/nf); } if (track->IsOn(AliESDtrack::kTRDrefit)) { Int_t n=track->GetTRDclusters(0); GetESDsData(kClr2)->Fill(Float_t(n)/(6*24));//(6*24) is the number of TRD time bins } Double_t p=track->GetP(); // Track related QA if (track->IsOn(AliESDtrack::kTPCrefit)) { Float_t dz[2]; track->GetDZ(0.,0.,0.,esd->GetMagneticField(),dz); if ((TMath::Abs(dz[0])<3.) && (TMath::Abs(dz[1])<3.)) { // beam pipe Double_t phi=track->Phi(); GetESDsData(kTrk0)->Fill(phi); Double_t y=track->Y(); GetESDsData(kTrk1)->Fill(y); if (TMath::Abs(y)<0.9) { GetESDsData(kTrk2)->Fill(p); if (track->IsOn(AliESDtrack::kITSrefit)) GetESDsData(kTrk3)->Fill(p); if (track->IsOn(AliESDtrack::kTOFout)) GetESDsData(kTrk4)->Fill(p); } } } // PID related QA if ((p>0.4) && (p<0.5)) { if (track->IsOn(AliESDtrack::kITSpid)) { Double_t dedx=track->GetITSsignal(); GetESDsData(kPid0)->Fill(dedx); } if (track->IsOn(AliESDtrack::kTPCpid)) { Double_t dedx=track->GetTPCsignal(); GetESDsData(kPid1)->Fill(dedx); } } if (p>1.0) { if (track->IsOn(AliESDtrack::kTOFpid)) { Double_t times[10]; track->GetIntegratedTimes(times); Double_t tof=track->GetTOFsignal(); GetESDsData(kPid2)->Fill(times[2]-tof); } } } TH1 *tpc=GetESDsData(kTrk2); tpc->Sumw2(); TH1 *its=GetESDsData(kTrk3); its->Sumw2(); TH1 *tof=GetESDsData(kTrk4); tof->Sumw2(); GetESDsData(kTrk5)->Divide(its,tpc,1,1.,"b"); GetESDsData(kTrk6)->Divide(tof,tpc,1,1.,"b"); // V0 related QA Int_t nV0=esd->GetNumberOfV0s(); for (Int_t i=0; i<nV0; i++) { Double_t mass; AliESDv0 v0(*esd->GetV0(i)); v0.ChangeMassHypothesis(kK0Short); mass=v0.GetEffMass(); GetESDsData(kV0s0)->Fill(mass); v0.ChangeMassHypothesis(kLambda0); mass=v0.GetEffMass(); GetESDsData(kV0s1)->Fill(mass); v0.ChangeMassHypothesis(kLambda0Bar); mass=v0.GetEffMass(); GetESDsData(kV0s1)->Fill(mass); } } <commit_msg>Using pseudo-rapidity getter.<commit_after>/* The class for calculating the global (not detector specific) quality assurance. It reuses the following TLists from its base class AliQADataMaker::fRecPointsQAList (for keeping the track residuals) AliQADataMaker::fESDsQAList (for keeping global ESD QA data) */ #include <TPDGCode.h> #include <TH1F.h> #include "AliGlobalQADataMaker.h" #include "AliGeomManager.h" #include "AliESDEvent.h" #include "AliESDv0.h" ClassImp(AliGlobalQADataMaker) void AliGlobalQADataMaker::InitRecPoints() { //------------------------------------------------------ // This function books the histograms of *track*residuals* // as a part of global QA //------------------------------------------------------ Char_t *name[]={ "SPD1 residuals Y","SPD1 residuals Z", "SPD2 residuals Y","SPD2 residuals Z", "SDD1 residuals Y","SDD1 residuals Z", "SDD2 residuals Y","SDD2 residuals Z", "SSD1 residuals Y","SSD1 residuals Z", "SSD2 residuals Y","SSD2 residuals Z", "TPC1 residuals Y","TPC1 residuals Z", "TPC2 residuals Y","TPC2 residuals Z", "TRD1 residuals Y","TRD1 residuals Z", "TRD2 residuals Y","TRD2 residuals Z", "TRD3 residuals Y","TRD3 residuals Z", "TRD4 residuals Y","TRD4 residuals Z", "TRD5 residuals Y","TRD5 residuals Z", "TRD6 residuals Y","TRD6 residuals Z", "TOF residuals Y","TOF residuals Z", "PHOS1 residuals Y","PHOS1 residuals Z", "PHOS2 residuals Y","PHOS2 residuals Z", "HMPID residuals Y","HMPID residuals Z", "MUON residuals Y","MUON residuals Z", "EMCAL residuals Y","EMCAL residuals Z" }; for (Int_t m=1; m<AliGeomManager::kLastLayer; m++) { Int_t i=2*m-2; TH1F *h=new TH1F(name[i],name[i],100,-5.,5.); Add2RecPointsList(h,i); h=new TH1F(name[i+1],name[i+1],100,-5.,5.); Add2RecPointsList(h,i+1); } } void AliGlobalQADataMaker::InitESDs() { //------------------------------------------------------ // This function books the ESD QA histograms // as a part of global QA //------------------------------------------------------ {// Cluster related QA Char_t *name[]={ "Fraction of the assigned clusters in ITS", "Fraction of the assigned clusters in TPC", "Fraction of the assigned clusters in TRD" }; Add2ESDsList(new TH1F(name[0],name[0],100,0.,2.),kClr0); Add2ESDsList(new TH1F(name[1],name[1],100,0.,2.),kClr1); Add2ESDsList(new TH1F(name[2],name[2],100,0.,2.),kClr2); } {// Track related QA Char_t *name[]={ "Track azimuthal distribution (rad)", // kTrk0 "Track pseudo-rapidity distribution", // kTrk1 "TPC: track momentum distribution (GeV)", // kTrk2 "TPC-ITS matched: track momentum distribution (GeV)", // kTrk3 "TPC-TOF matched: track momentum distribution (GeV)", // kTrk4 "TPC-ITS track-matching probability", // kTrk5 "TPC-TOF track-matching probability" // kTrk6 }; Add2ESDsList(new TH1F(name[0],name[0],100,-0.02,6.30),kTrk0); Add2ESDsList(new TH1F(name[1],name[1],100,-2.00,2.00),kTrk1); Add2ESDsList(new TH1F(name[2],name[2],50, 0.20,5.00),kTrk2); Add2ESDsList(new TH1F(name[3],name[3],50, 0.20,5.00),kTrk3); Add2ESDsList(new TH1F(name[4],name[4],50, 0.20,5.00),kTrk4); Add2ESDsList(new TH1F(name[5],name[5],50, 0.20,5.00),kTrk5); Add2ESDsList(new TH1F(name[6],name[6],50, 0.20,5.00),kTrk6); } {// V0 related QA Char_t *name[]={ "K0s mass (GeV)", "Lambda0 + Lambda0Bar mass (GeV)" }; Add2ESDsList(new TH1F(name[0],name[0],50, 0.4477,0.5477),kV0s0); Add2ESDsList(new TH1F(name[1],name[1],50, 1.0657,1.1657),kV0s1); } {// PID related QA Char_t *name[]={ "ITS: dEdx (ADC) for particles with momentum 0.4 - 0.5 (GeV)", "TPC: dEdx (ADC) for particles with momentum 0.4 - 0.5 (GeV)", "TOF: tracking - measured (ps)" }; Add2ESDsList(new TH1F(name[0],name[0],50,0.00,200.),kPid0); Add2ESDsList(new TH1F(name[1],name[1],50,0.00,100.),kPid1); Add2ESDsList(new TH1F(name[2],name[2],50,-3500.,3500.),kPid2); } } void AliGlobalQADataMaker::MakeESDs(AliESDEvent * event) { //----------------------------------------------------------- // This function fills the ESD QA histograms // as a part of global QA //----------------------------------------------------------- const AliESDEvent *esd=event; Int_t ntrk=esd->GetNumberOfTracks() ; for (Int_t i=0; i<ntrk; i++) { const AliESDtrack *track=esd->GetTrack(i); // Cluster related QA if (track->IsOn(AliESDtrack::kITSrefit)) { Int_t n=track->GetITSclusters(0); GetESDsData(kClr0)->Fill(Float_t(n)/6.); //6 is the number of ITS layers } if (track->IsOn(AliESDtrack::kTPCrefit)) { Int_t n =track->GetTPCNcls(); Int_t nf=track->GetTPCNclsF(); // number of crossed TPC pad rows GetESDsData(kClr1)->Fill(Float_t(n)/nf); } if (track->IsOn(AliESDtrack::kTRDrefit)) { Int_t n=track->GetTRDclusters(0); GetESDsData(kClr2)->Fill(Float_t(n)/(6*24));//(6*24) is the number of TRD time bins } Double_t p=track->GetP(); // Track related QA if (track->IsOn(AliESDtrack::kTPCrefit)) { Float_t dz[2]; track->GetDZ(0.,0.,0.,esd->GetMagneticField(),dz); if ((TMath::Abs(dz[0])<3.) && (TMath::Abs(dz[1])<3.)) { // beam pipe Double_t phi=track->Phi(); GetESDsData(kTrk0)->Fill(phi); Double_t y=track->Eta(); GetESDsData(kTrk1)->Fill(y); if (TMath::Abs(y)<0.9) { GetESDsData(kTrk2)->Fill(p); if (track->IsOn(AliESDtrack::kITSrefit)) GetESDsData(kTrk3)->Fill(p); if (track->IsOn(AliESDtrack::kTOFout)) GetESDsData(kTrk4)->Fill(p); } } } // PID related QA if ((p>0.4) && (p<0.5)) { if (track->IsOn(AliESDtrack::kITSpid)) { Double_t dedx=track->GetITSsignal(); GetESDsData(kPid0)->Fill(dedx); } if (track->IsOn(AliESDtrack::kTPCpid)) { Double_t dedx=track->GetTPCsignal(); GetESDsData(kPid1)->Fill(dedx); } } if (p>1.0) { if (track->IsOn(AliESDtrack::kTOFpid)) { Double_t times[10]; track->GetIntegratedTimes(times); Double_t tof=track->GetTOFsignal(); GetESDsData(kPid2)->Fill(times[2]-tof); } } } TH1 *tpc=GetESDsData(kTrk2); tpc->Sumw2(); TH1 *its=GetESDsData(kTrk3); its->Sumw2(); TH1 *tof=GetESDsData(kTrk4); tof->Sumw2(); GetESDsData(kTrk5)->Divide(its,tpc,1,1.,"b"); GetESDsData(kTrk6)->Divide(tof,tpc,1,1.,"b"); // V0 related QA Int_t nV0=esd->GetNumberOfV0s(); for (Int_t i=0; i<nV0; i++) { Double_t mass; AliESDv0 v0(*esd->GetV0(i)); v0.ChangeMassHypothesis(kK0Short); mass=v0.GetEffMass(); GetESDsData(kV0s0)->Fill(mass); v0.ChangeMassHypothesis(kLambda0); mass=v0.GetEffMass(); GetESDsData(kV0s1)->Fill(mass); v0.ChangeMassHypothesis(kLambda0Bar); mass=v0.GetEffMass(); GetESDsData(kV0s1)->Fill(mass); } } <|endoftext|>
<commit_before>#include <vector> #include <Poco/Exception.h> #include "service/GatewayService.h" #include "server/AccessLevel.h" #include "dao/GatewayDao.h" #include "dao/RoleInPlaceDao.h" #include "dao/PlaceDao.h" #include "dao/IdentityDao.h" #include "dao/VerifiedIdentityDao.h" #include "policy/GatewayAccessPolicy.h" BEEEON_OBJECT(GatewayService, BeeeOn::GatewayService) using namespace std; using namespace Poco; using namespace BeeeOn; GatewayService::GatewayService(): m_gatewayDao(&NullGatewayDao::instance()), m_roleInPlaceDao(&NullRoleInPlaceDao::instance()), m_placeDao(&NullPlaceDao::instance()), m_identityDao(&NullIdentityDao::instance()), m_rpc(&NullGatewayRPC::instance()), m_accessPolicy(&NullGatewayAccessPolicy::instance()) { injector<GatewayService, GatewayDao>("gatewayDao", &GatewayService::setGatewayDao); injector<GatewayService, RoleInPlaceDao>("roleInPlaceDao", &GatewayService::setRoleInPlaceDao); injector<GatewayService, PlaceDao>("placeDao", &GatewayService::setPlaceDao); injector<GatewayService, IdentityDao>("identityDao", &GatewayService::setIdentityDao); injector<GatewayService, VerifiedIdentityDao>("verifiedIdentityDao", &GatewayService::setVerifiedIdentityDao); injector<GatewayService, GatewayRPC>("gatewayRPC", &GatewayService::setGatewayRPC); injector<GatewayService, GatewayAccessPolicy>("accessPolicy", &GatewayService::setAccessPolicy); } void GatewayService::setGatewayDao(GatewayDao *dao) { m_gatewayDao = dao? dao : &NullGatewayDao::instance(); } void GatewayService::setRoleInPlaceDao(RoleInPlaceDao *dao) { m_roleInPlaceDao = dao? dao :&NullRoleInPlaceDao::instance(); } void GatewayService::setPlaceDao(PlaceDao *dao) { m_placeDao = dao? dao : &NullPlaceDao::instance(); } void GatewayService::setIdentityDao(IdentityDao *dao) { m_identityDao = dao? dao :&NullIdentityDao::instance(); } void GatewayService::setVerifiedIdentityDao(VerifiedIdentityDao *dao) { m_verifiedIdentityDao = dao? dao : &NullVerifiedIdentityDao::instance(); } void GatewayService::setGatewayRPC(GatewayRPC *rpc) { m_rpc = rpc? rpc : &NullGatewayRPC::instance(); } void GatewayService::setAccessPolicy(GatewayAccessPolicy *policy) { m_accessPolicy = policy? policy : &NullGatewayAccessPolicy::instance(); } bool GatewayService::registerGateway(SingleWithData<Gateway> &input, const VerifiedIdentity &verifiedIdentity) { VerifiedIdentity tmp(verifiedIdentity); if (!m_verifiedIdentityDao->fetch(tmp)) throw InvalidArgumentException("invalid verified identity"); Gateway &gateway = input.target(); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway was not found"); if (gateway.hasPlace()) { const AccessLevel &level = m_roleInPlaceDao-> fetchAccessLevel(gateway.place(), tmp.user()); if (level <= AccessLevel::admin()) // is owner throw ExistsException("gateway is already assigned"); throw NotFoundException("gateway is owned by somebody else"); } vector<Place> places; m_roleInPlaceDao->fetchAccessiblePlaces( places, tmp.user(), AccessLevel::admin()); if (places.size() > 1) throw IllegalStateException("too many places, incompatible"); if (places.size() == 0) { Place place; createImplicitPlace(place, tmp.identity()); places.push_back(place); } m_accessPolicy->assureAssignGateway(input, places.front()); input.data().full(gateway); return m_gatewayDao->assignAndUpdate(gateway, places.front()); } void GatewayService::createImplicitPlace(Place &place, const Identity &identity) { place.setName("Implicit"); m_placeDao->create(place); RoleInPlace role; role.setPlace(place); role.setIdentity(identity); role.setLevel(AccessLevel::admin()); m_roleInPlaceDao->create(role); } bool GatewayService::fetch(Single<Gateway> &input) { m_accessPolicy->assureGet(input, input.target()); return m_gatewayDao->fetch(input.target()); } bool GatewayService::fetchFromPlace(Relation<Gateway, Place> &input) { m_accessPolicy->assureGet(input, input.target()); return m_gatewayDao->fetchFromPlace(input.target(), input.base()); } void GatewayService::fetchAccessible(Relation<vector<Gateway>, User> &input) { m_gatewayDao->fetchAccessible(input.target(), input.base()); } bool GatewayService::update(SingleWithData<Gateway> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUpdate(input, gateway); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); input.data().partial(gateway); return m_gatewayDao->update(gateway); } bool GatewayService::updateInPlace(RelationWithData<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUpdate(input, gateway); if (!m_gatewayDao->fetchFromPlace(gateway, input.base())) throw NotFoundException("gateway does not exist"); input.data().partial(gateway); return m_gatewayDao->update(gateway); } bool GatewayService::assignAndUpdate( RelationWithData<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureAssignGateway(input, input.base()); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); if (gateway.hasPlace()) // do not leak it exists throw NotFoundException("gateway is already assigned"); input.data().partial(gateway); return m_gatewayDao->assignAndUpdate(gateway, input.base()); } bool GatewayService::unassign(Relation<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUnassign(input, input.target()); if (!m_gatewayDao->fetchFromPlace(gateway, input.base())) return false; return m_gatewayDao->unassign(gateway); } bool GatewayService::unassign(Relation<Gateway, User> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUnassign(input, input.target()); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); if (!gateway.hasPlace()) // do not leak that this gateway exists throw NotFoundException("gateway is not assigned"); return m_gatewayDao->unassign(gateway); } void GatewayService::scanDevices(Single<Gateway> &input) { m_accessPolicy->assureScanDevices(input, input.target()); m_rpc->sendListen(input.target()); } void GatewayService::unpairDevice(Single<Gateway> &input, Device &device) { m_rpc->unpairDevice(input.target(), device); } void GatewayService::pingGateway(Single<Gateway> &input) { m_rpc->pingGateway(input.target()); } <commit_msg>GatewayService: always create an implicit place on register<commit_after>#include <vector> #include <Poco/Exception.h> #include "service/GatewayService.h" #include "server/AccessLevel.h" #include "dao/GatewayDao.h" #include "dao/RoleInPlaceDao.h" #include "dao/PlaceDao.h" #include "dao/IdentityDao.h" #include "dao/VerifiedIdentityDao.h" #include "policy/GatewayAccessPolicy.h" BEEEON_OBJECT(GatewayService, BeeeOn::GatewayService) using namespace std; using namespace Poco; using namespace BeeeOn; GatewayService::GatewayService(): m_gatewayDao(&NullGatewayDao::instance()), m_roleInPlaceDao(&NullRoleInPlaceDao::instance()), m_placeDao(&NullPlaceDao::instance()), m_identityDao(&NullIdentityDao::instance()), m_rpc(&NullGatewayRPC::instance()), m_accessPolicy(&NullGatewayAccessPolicy::instance()) { injector<GatewayService, GatewayDao>("gatewayDao", &GatewayService::setGatewayDao); injector<GatewayService, RoleInPlaceDao>("roleInPlaceDao", &GatewayService::setRoleInPlaceDao); injector<GatewayService, PlaceDao>("placeDao", &GatewayService::setPlaceDao); injector<GatewayService, IdentityDao>("identityDao", &GatewayService::setIdentityDao); injector<GatewayService, VerifiedIdentityDao>("verifiedIdentityDao", &GatewayService::setVerifiedIdentityDao); injector<GatewayService, GatewayRPC>("gatewayRPC", &GatewayService::setGatewayRPC); injector<GatewayService, GatewayAccessPolicy>("accessPolicy", &GatewayService::setAccessPolicy); } void GatewayService::setGatewayDao(GatewayDao *dao) { m_gatewayDao = dao? dao : &NullGatewayDao::instance(); } void GatewayService::setRoleInPlaceDao(RoleInPlaceDao *dao) { m_roleInPlaceDao = dao? dao :&NullRoleInPlaceDao::instance(); } void GatewayService::setPlaceDao(PlaceDao *dao) { m_placeDao = dao? dao : &NullPlaceDao::instance(); } void GatewayService::setIdentityDao(IdentityDao *dao) { m_identityDao = dao? dao :&NullIdentityDao::instance(); } void GatewayService::setVerifiedIdentityDao(VerifiedIdentityDao *dao) { m_verifiedIdentityDao = dao? dao : &NullVerifiedIdentityDao::instance(); } void GatewayService::setGatewayRPC(GatewayRPC *rpc) { m_rpc = rpc? rpc : &NullGatewayRPC::instance(); } void GatewayService::setAccessPolicy(GatewayAccessPolicy *policy) { m_accessPolicy = policy? policy : &NullGatewayAccessPolicy::instance(); } bool GatewayService::registerGateway(SingleWithData<Gateway> &input, const VerifiedIdentity &verifiedIdentity) { VerifiedIdentity tmp(verifiedIdentity); if (!m_verifiedIdentityDao->fetch(tmp)) throw InvalidArgumentException("invalid verified identity"); Gateway &gateway = input.target(); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway was not found"); if (gateway.hasPlace()) { const AccessLevel &level = m_roleInPlaceDao-> fetchAccessLevel(gateway.place(), tmp.user()); if (level <= AccessLevel::admin()) // is owner throw ExistsException("gateway is already assigned"); throw NotFoundException("gateway is owned by somebody else"); } Place place; createImplicitPlace(place, tmp.identity()); m_accessPolicy->assureAssignGateway(input, place); input.data().full(gateway); return m_gatewayDao->assignAndUpdate(gateway, place); } void GatewayService::createImplicitPlace(Place &place, const Identity &identity) { place.setName("Implicit"); m_placeDao->create(place); RoleInPlace role; role.setPlace(place); role.setIdentity(identity); role.setLevel(AccessLevel::admin()); m_roleInPlaceDao->create(role); } bool GatewayService::fetch(Single<Gateway> &input) { m_accessPolicy->assureGet(input, input.target()); return m_gatewayDao->fetch(input.target()); } bool GatewayService::fetchFromPlace(Relation<Gateway, Place> &input) { m_accessPolicy->assureGet(input, input.target()); return m_gatewayDao->fetchFromPlace(input.target(), input.base()); } void GatewayService::fetchAccessible(Relation<vector<Gateway>, User> &input) { m_gatewayDao->fetchAccessible(input.target(), input.base()); } bool GatewayService::update(SingleWithData<Gateway> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUpdate(input, gateway); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); input.data().partial(gateway); return m_gatewayDao->update(gateway); } bool GatewayService::updateInPlace(RelationWithData<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUpdate(input, gateway); if (!m_gatewayDao->fetchFromPlace(gateway, input.base())) throw NotFoundException("gateway does not exist"); input.data().partial(gateway); return m_gatewayDao->update(gateway); } bool GatewayService::assignAndUpdate( RelationWithData<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureAssignGateway(input, input.base()); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); if (gateway.hasPlace()) // do not leak it exists throw NotFoundException("gateway is already assigned"); input.data().partial(gateway); return m_gatewayDao->assignAndUpdate(gateway, input.base()); } bool GatewayService::unassign(Relation<Gateway, Place> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUnassign(input, input.target()); if (!m_gatewayDao->fetchFromPlace(gateway, input.base())) return false; return m_gatewayDao->unassign(gateway); } bool GatewayService::unassign(Relation<Gateway, User> &input) { Gateway &gateway = input.target(); m_accessPolicy->assureUnassign(input, input.target()); if (!m_gatewayDao->fetch(gateway)) throw NotFoundException("gateway does not exist"); if (!gateway.hasPlace()) // do not leak that this gateway exists throw NotFoundException("gateway is not assigned"); return m_gatewayDao->unassign(gateway); } void GatewayService::scanDevices(Single<Gateway> &input) { m_accessPolicy->assureScanDevices(input, input.target()); m_rpc->sendListen(input.target()); } void GatewayService::unpairDevice(Single<Gateway> &input, Device &device) { m_rpc->unpairDevice(input.target(), device); } void GatewayService::pingGateway(Single<Gateway> &input) { m_rpc->pingGateway(input.target()); } <|endoftext|>
<commit_before>#include "mex.h" #include "matrix.h" #include <cmath> #include <cstdint> #include <thread> #include <emmintrin.h> /* * compilation, at matlab prompt: (adjust NUM_THREADS as appropriate) * * == windows == * * mex OPTIMFLAGS="/O2" -largeArrayDims -DNUM_THREADS=4 dmsm.cpp * * == linux == * * mex OPTIMFLAGS="-O3" -largeArrayDims -DNUM_THREADS=4 -v CXXFLAGS='$CXXFLAGS -std=c++0x -fPIC' dmsm.cpp */ #define DENSE_MATRIX_PARAMETER_IN prhs[0] #define SPARSE_MATRIX_PARAMETER_IN prhs[1] #define DIAG_VECTOR_PARAMETER_IN prhs[2] #define START_PARAMETER_IN prhs[3] #define END_PARAMETER_IN prhs[4] // X = D*S => X' = S'*D' template<typename scalar> static void sparsetic_times_densetic (int nrhs, const mxArray* prhs[], mxArray* plhs[], size_t start, size_t end) { mwIndex* ir = mxGetIr(SPARSE_MATRIX_PARAMETER_IN); /* Row indexing */ mwIndex* jc = mxGetJc(SPARSE_MATRIX_PARAMETER_IN); /* Column count */ double* s = mxGetPr(SPARSE_MATRIX_PARAMETER_IN); /* Non-zero elements */ scalar* Btic = (scalar*) mxGetData(DENSE_MATRIX_PARAMETER_IN); mwSize Bcol = mxGetM(DENSE_MATRIX_PARAMETER_IN); scalar* Xtic = (scalar*) mxGetData(plhs[0]); mwSize Xcol = mxGetM(plhs[0]); size_t off = 0; if (nrhs > 3) { off = mxGetScalar(START_PARAMETER_IN) - 1; } if (nrhs == 2) { for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = s[k]; scalar* Bticrow = Btic + ir[k] * Bcol; scalar* Xticrow = Xtic + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } else { double* w = mxGetPr(DIAG_VECTOR_PARAMETER_IN); for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ double wi = w[off+i]; mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = wi * s[k]; scalar* Bticrow = Btic + ir[k] * Bcol; scalar* Xticrow = Xtic + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } } static int first = 1; void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { if (first) { mexPrintf("dmsm using NUM_THREADS=%u\n",NUM_THREADS); first=0; } switch (nrhs) { case 5: if (mxGetM(END_PARAMETER_IN) != 1 || mxGetN(END_PARAMETER_IN) != 1) { mexErrMsgTxt("End must be a scalar. Fail."); return; } // fall through case 4: if (mxGetM(START_PARAMETER_IN) != 1 || mxGetN(START_PARAMETER_IN) != 1) { mexErrMsgTxt("Start must be a scalar. Fail."); return; } // fall through case 3: if (mxIsSparse(DIAG_VECTOR_PARAMETER_IN)) { mexErrMsgTxt("Scale must be dense. Fail."); return; } if (mxGetM(DIAG_VECTOR_PARAMETER_IN) != 1 || mxGetN(DIAG_VECTOR_PARAMETER_IN) != mxGetN(SPARSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Scale has incompatible shape. Fail."); return; } // fall through case 2: if (! mxIsSparse(SPARSE_MATRIX_PARAMETER_IN) || mxIsSparse(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Require one sparse and one dense argument. Fail."); return; } if (mxGetM(SPARSE_MATRIX_PARAMETER_IN) != mxGetN(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Arguments have incompatible shape. Fail."); return; } if (! mxIsSingle(DENSE_MATRIX_PARAMETER_IN) && ! mxIsDouble(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Dense argument must be double or single. Fail."); return; } break; default: mexErrMsgTxt("Wrong number of arguments. Fail."); return; } bool singlePrec = mxIsSingle(DENSE_MATRIX_PARAMETER_IN); void* Btic = mxGetData(DENSE_MATRIX_PARAMETER_IN); size_t Bcol = mxGetM(DENSE_MATRIX_PARAMETER_IN); size_t Arow = mxGetN(SPARSE_MATRIX_PARAMETER_IN); size_t start = 1; size_t end = Arow; switch (nrhs) { case 5: end = mxGetScalar(END_PARAMETER_IN); if (end > Arow) { mexErrMsgTxt("End is invalid. Fail."); return; } // fall through case 4: start = mxGetScalar(START_PARAMETER_IN); if (start < 1) { mexErrMsgTxt("Start is invalid. Fail."); return; } break; default: break; } plhs[0] = mxCreateNumericMatrix(Bcol, 1+end-start, (singlePrec) ? mxSINGLE_CLASS : mxDOUBLE_CLASS, mxREAL); std::thread t[NUM_THREADS]; size_t quot = (1+end-start)/NUM_THREADS; for (size_t i = 0; i + 1 < NUM_THREADS; ++i) { if (singlePrec) { t[i] = std::thread(sparsetic_times_densetic<float>, nrhs, prhs, plhs, i * quot, (i + 1) * quot); } else { t[i] = std::thread(sparsetic_times_densetic<double>, nrhs, prhs, plhs, i * quot, (i + 1) * quot); } } if (singlePrec) { sparsetic_times_densetic<float> (nrhs, prhs, plhs, (NUM_THREADS - 1) * quot, 1 + end - start); } else { sparsetic_times_densetic<double> (nrhs, prhs, plhs, (NUM_THREADS - 1) * quot, 1 + end - start); } for (int i = 0; i + 1 < NUM_THREADS; ++i) { t[i].join (); } return; } <commit_msg>dmsm single precision weights<commit_after>#include "mex.h" #include "matrix.h" #include <cmath> #include <cstdint> #include <thread> #include <emmintrin.h> /* % dense matrix times sparse matrix * >> A=sprandn(100,100,0.1); W=ones(1,100); B=randn(5,100); Z=B*diag(W)*A; ZZ=dmsm(B,A,W); disp(norm(Z-ZZ)) * 0 * % dense matrix times scaled sparse matrix * >> A=sprandn(100,100,0.1); W=randn(1,100); B=randn(5,100); Z=B*A*diag(W); ZZ=dmsm(B,A,W); disp(norm(Z-ZZ)) 9.1859e-15 */ /* * compilation, at matlab prompt: (adjust NUM_THREADS as appropriate) * * == windows == * * mex OPTIMFLAGS="/O2" -largeArrayDims -DNUM_THREADS=4 dmsm.cpp * * == linux == * * mex OPTIMFLAGS="-O3" -largeArrayDims -DNUM_THREADS=4 -v CXXFLAGS='$CXXFLAGS -std=c++0x -fPIC' dmsm.cpp */ #define DENSE_MATRIX_PARAMETER_IN prhs[0] #define SPARSE_MATRIX_PARAMETER_IN prhs[1] #define DIAG_VECTOR_PARAMETER_IN prhs[2] #define START_PARAMETER_IN prhs[3] #define END_PARAMETER_IN prhs[4] // X = D*S => X' = S'*D' static void sparsetic_times_densetic (int nrhs, const mxArray* prhs[], mxArray* plhs[], size_t start, size_t end) { mwIndex* ir = mxGetIr(SPARSE_MATRIX_PARAMETER_IN); /* Row indexing */ mwIndex* jc = mxGetJc(SPARSE_MATRIX_PARAMETER_IN); /* Column count */ double* s = mxGetPr(SPARSE_MATRIX_PARAMETER_IN); /* Non-zero elements */ void* Btic = mxGetData(DENSE_MATRIX_PARAMETER_IN); mwSize Bcol = mxGetM(DENSE_MATRIX_PARAMETER_IN); void* Xtic = mxGetData(plhs[0]); mwSize Xcol = mxGetM(plhs[0]); bool singlePrec = mxIsSingle(DENSE_MATRIX_PARAMETER_IN); size_t off = 0; if (nrhs > 3) { off = mxGetScalar(START_PARAMETER_IN) - 1; } if (nrhs == 2) { if (singlePrec) { for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = s[k]; float* Bticrow = ((float*)Btic) + ir[k] * Bcol; float* Xticrow = ((float*)Xtic) + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } else { for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = s[k]; double* Bticrow = ((double*)Btic) + ir[k] * Bcol; double* Xticrow = ((double*)Xtic) + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } } else { bool diagsinglePrec = mxIsSingle(DIAG_VECTOR_PARAMETER_IN); float* wf = (float*) mxGetPr(DIAG_VECTOR_PARAMETER_IN); double* wd = (double*) mxGetPr(DIAG_VECTOR_PARAMETER_IN); if (singlePrec) { for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ double wi = diagsinglePrec ? wf[off+i] : wd[off+i]; mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = wi * s[k]; float* Bticrow = ((float*)Btic) + ir[k] * Bcol; float* Xticrow = ((float*)Xtic) + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } else { for (size_t i=start; i<end; ++i) { /* Loop through rows of A (and X) */ double wi = diagsinglePrec ? wf[off+i] : wd[off+i]; mwIndex stop = jc[off+i+1]; for (mwIndex k=jc[off+i]; k<stop; ++k) { /* Loop through non-zeros in ith row of A */ double sk = wi * s[k]; double* Bticrow = ((double*)Btic) + ir[k] * Bcol; double* Xticrow = ((double*)Xtic) + i * Xcol; for (mwSize j=0; j<Xcol; ++j) { Xticrow[j] += sk * Bticrow[j]; } } } } } } static int first = 1; void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { if (first) { mexPrintf("dmsm using NUM_THREADS=%u\n",NUM_THREADS); first=0; } switch (nrhs) { case 5: if (mxGetM(END_PARAMETER_IN) != 1 || mxGetN(END_PARAMETER_IN) != 1) { mexErrMsgTxt("End must be a scalar. Fail."); return; } // fall through case 4: if (mxGetM(START_PARAMETER_IN) != 1 || mxGetN(START_PARAMETER_IN) != 1) { mexErrMsgTxt("Start must be a scalar. Fail."); return; } // fall through case 3: if (mxIsSparse(DIAG_VECTOR_PARAMETER_IN)) { mexErrMsgTxt("Scale must be dense. Fail."); return; } if (! mxIsSingle(DIAG_VECTOR_PARAMETER_IN) && ! mxIsDouble(DIAG_VECTOR_PARAMETER_IN)) { mexErrMsgTxt("Scale must be double or single. Fail."); return; } if (mxGetM(DIAG_VECTOR_PARAMETER_IN) != 1 || mxGetN(DIAG_VECTOR_PARAMETER_IN) != mxGetN(SPARSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Scale has incompatible shape. Fail."); return; } // fall through case 2: if (! mxIsSparse(SPARSE_MATRIX_PARAMETER_IN) || mxIsSparse(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Require one sparse and one dense argument. Fail."); return; } if (mxGetM(SPARSE_MATRIX_PARAMETER_IN) != mxGetN(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Arguments have incompatible shape. Fail."); return; } if (! mxIsSingle(DENSE_MATRIX_PARAMETER_IN) && ! mxIsDouble(DENSE_MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Dense argument must be double or single. Fail."); return; } break; default: mexErrMsgTxt("Wrong number of arguments. Fail."); return; } size_t Bcol = mxGetM(DENSE_MATRIX_PARAMETER_IN); size_t Arow = mxGetN(SPARSE_MATRIX_PARAMETER_IN); size_t start = 1; size_t end = Arow; switch (nrhs) { case 5: end = mxGetScalar(END_PARAMETER_IN); if (end > Arow) { mexErrMsgTxt("End is invalid. Fail."); return; } // fall through case 4: start = mxGetScalar(START_PARAMETER_IN); if (start < 1) { mexErrMsgTxt("Start is invalid. Fail."); return; } break; default: break; } bool singlePrec = mxIsSingle(DENSE_MATRIX_PARAMETER_IN); plhs[0] = mxCreateNumericMatrix(Bcol, 1+end-start, (singlePrec) ? mxSINGLE_CLASS : mxDOUBLE_CLASS, mxREAL); std::thread t[NUM_THREADS]; size_t quot = (1+end-start)/NUM_THREADS; for (size_t i = 0; i + 1 < NUM_THREADS; ++i) { t[i] = std::thread(sparsetic_times_densetic, nrhs, prhs, plhs, i * quot, (i + 1) * quot); } sparsetic_times_densetic (nrhs, prhs, plhs, (NUM_THREADS - 1) * quot, 1 + end - start); for (int i = 0; i + 1 < NUM_THREADS; ++i) { t[i].join (); } return; } <|endoftext|>
<commit_before>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * 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. */ #include <sstream> #include "memory.h" #include "luts.h" #include "conversions.h" #include "powerline.h" std::string mem_string( const MemoryStatus & mem_status, MEMORY_MODE mode, bool use_colors, bool use_powerline_left, bool use_powerline_right ) { std::ostringstream oss; // Change the percision for floats, for a pretty output oss.precision( 2 ); oss.setf( std::ios::fixed | std::ios::right ); unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem); if( use_colors ) { if( use_powerline_right ) { oss << "#[bg=default]"; powerline( oss, mem_lut[color], POWERLINE_RIGHT ); oss << ' '; } else if( use_powerline_left ) { //powerline( oss, mem_lut[color], POWERLINE_LEFT ); // We do not know how to invert the default background color powerline( oss, mem_lut[color], NONE ); oss << ' '; } else { powerline( oss, mem_lut[color], NONE ); } } switch( mode ) { case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB { const float free_mem = mem_status.total_mem - mem_status.used_mem; const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES ); // if free memory is less than 1 GB, use MB instead if( free_mem_in_gigabytes < 1.0f ) { oss << free_mem << "MB"; } else { oss << free_mem_in_gigabytes << "GB"; } break; } case MEMORY_MODE_USAGE_PERCENTAGE: { // Calculate the percentage of used memory const float percentage_mem = mem_status.used_mem / static_cast<float>( mem_status.total_mem ) * 100.0; oss << percentage_mem << '%'; break; } default: // Default mode, just show the used/total memory in MB if(mem_status.used_mem>10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else if(mem_status.used_mem<10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB"; } if( use_colors ) { if( use_powerline_left ) { powerline( oss, mem_lut[color], POWERLINE_LEFT, true ); } else if( !use_powerline_right ) { oss << "#[fg=default,bg=default]"; } } return oss.str(); } <commit_msg>Undefined references to std::string in aarch64 build<commit_after>/* vim: tabstop=2 shiftwidth=2 expandtab textwidth=80 linebreak wrap * * Copyright 2012 Matthew McCormick * 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. */ #include <sstream> #include <string> #include "memory.h" #include "luts.h" #include "conversions.h" #include "powerline.h" std::string mem_string( const MemoryStatus & mem_status, MEMORY_MODE mode, bool use_colors, bool use_powerline_left, bool use_powerline_right ) { std::ostringstream oss; // Change the percision for floats, for a pretty output oss.precision( 2 ); oss.setf( std::ios::fixed | std::ios::right ); unsigned int color = static_cast< unsigned int >((100 * mem_status.used_mem) / mem_status.total_mem); if( use_colors ) { if( use_powerline_right ) { oss << "#[bg=default]"; powerline( oss, mem_lut[color], POWERLINE_RIGHT ); oss << ' '; } else if( use_powerline_left ) { //powerline( oss, mem_lut[color], POWERLINE_LEFT ); // We do not know how to invert the default background color powerline( oss, mem_lut[color], NONE ); oss << ' '; } else { powerline( oss, mem_lut[color], NONE ); } } switch( mode ) { case MEMORY_MODE_FREE_MEMORY: // Show free memory in MB or GB { const float free_mem = mem_status.total_mem - mem_status.used_mem; const float free_mem_in_gigabytes = convert_unit( free_mem, GIGABYTES, MEGABYTES ); // if free memory is less than 1 GB, use MB instead if( free_mem_in_gigabytes < 1.0f ) { oss << free_mem << "MB"; } else { oss << free_mem_in_gigabytes << "GB"; } break; } case MEMORY_MODE_USAGE_PERCENTAGE: { // Calculate the percentage of used memory const float percentage_mem = mem_status.used_mem / static_cast<float>( mem_status.total_mem ) * 100.0; oss << percentage_mem << '%'; break; } default: // Default mode, just show the used/total memory in MB if(mem_status.used_mem>10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem/1024)<<"/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else if(mem_status.used_mem<10000 && mem_status.total_mem>10000) oss<<static_cast<unsigned int>(mem_status.used_mem)<<"MB/"<<static_cast<unsigned int>(mem_status.total_mem/1024)<<"GB"; else oss<<static_cast<unsigned int>(mem_status.used_mem)<<"/"<<static_cast<unsigned int>(mem_status.total_mem)<<"MB"; } if( use_colors ) { if( use_powerline_left ) { powerline( oss, mem_lut[color], POWERLINE_LEFT, true ); } else if( !use_powerline_right ) { oss << "#[fg=default,bg=default]"; } } return oss.str(); } <|endoftext|>
<commit_before>#ifndef __MODEL_HPP_INCLUDED #define __MODEL_HPP_INCLUDED // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <iostream> #include <queue> // std::queue #include <string.h> #include "globals.hpp" #include "shader.hpp" #include "heightmap_loader.hpp" #include "objloader.hpp" namespace model { class World { public: // constructor. World(); // destructor. ~World(); // this method renders the entire world, one shader at a time. void render(); // this method sets a shader pointer. void set_pointer(GLuint shaderID, void* shader_pointer); // this method gets a shader pointer. void* get_pointer(GLuint shaderID); // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue. GLuint get_shaderID(); private: std::vector<void*> shader_pointer_vector; std::queue<GLuint> free_shaderID_queue; }; class Shader { public: // constructor. Shader(ShaderStruct shader_struct); // destructor. ~Shader(); // this method renders all species using this shader. void render(); // this method sets a species pointer. void set_pointer(GLuint speciesID, void* species_pointer); // this method gets a species pointer. void* get_pointer(GLuint speciesID); // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue. GLuint get_speciesID(); // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world. void switch_to_new_world(model::World *new_world_pointer); model::World *world_pointer; // pointer to the world. GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. GLuint programID; // shaders' programID, returned by `LoadShaders`. private: std::vector<void*> species_pointer_vector; std::queue<GLuint> free_speciesID_queue; const char *char_vertex_shader; const char *char_fragment_shader; }; class Graph { public: // constructor. Graph(); // destructor. ~Graph(); // this method sets a node pointer. void set_pointer(GLuint nodeID, void* node_pointer); // this method gets a node pointer. void* get_pointer(GLuint nodeID); // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue. GLuint get_nodeID(); private: std::vector<void*> node_pointer_vector; std::queue<GLuint> free_nodeID_queue; }; // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph. // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s. // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`). class Node { public: // constructor. Node(NodeStruct node_struct); // destructor. ~Node(); // this method creates a bidirectional link. // creating of bidirectional links is not possible before all nodes are created. void create_bidirectional_link(GLuint nodeID); // this method deletes a bidirectional link. // deleting of links is not possible before all nodes are created. void delete_bidirectional_link(GLuint nodeID); // this method transfers this node to a new graph. // links will not be changed. // all nodes that are to be transferred must be transferred separately. // before transfering any node to a new graph, // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls. void transfer_to_new_graph(model::Graph *new_graph_pointer); GLuint nodeID; model::Graph *graph_pointer; // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created. std::vector<GLuint> neighbor_nodeIDs; private: // this method creates an unidirectional link. // in the constructor only unidirectional links can be created. void create_unidirectional_link(GLuint nodeID); // this method deletes an unidirectional link. void delete_unidirectional_link(GLuint nodeID); glm::vec3 coordinate_vector; }; class Species { public: // constructor. Species(SpeciesStruct species_struct); // destructor. ~Species(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader. void switch_to_new_shader(model::Shader *new_shader_pointer); model::Shader *shader_pointer; // pointer to the shader. std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!). void *texture_pointer; // pointer to the texture species (not yet in use!). // The rest fields are created in the constructor. GLuint MatrixID; GLuint ViewMatrixID; GLuint ModelMatrixID; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; glm::mat4 ProjectionMatrix; glm::mat4 ViewMatrix; private: GLuint speciesID; // species ID, returned by `model::World->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. const char *char_model_file_format; const char *char_model_filename; const char *char_texture_file_format; const char *char_texture_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Object { public: // constructor. Object(ObjectStruct object_struct); // destructor. ~Object(); // this method renders this object. void render(); // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species. void switch_to_new_species(model::Species *new_species_pointer); model::Species *species_pointer; // pointer to the species. GLuint objectID; // object ID, returned by `model::Species->get_objectID()`. bool has_entered; glm::vec3 coordinate_vector; // rotate vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. // The rest fields are created in the constructor. glm::mat4 model_matrix; // model matrix. std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. not used at the moment. glm::mat4 MVP_matrix; // model view projection matrix. }; } #endif <commit_msg>`class Species`: `model::Shader *shader_pointer` on `private`-muuttuja.<commit_after>#ifndef __MODEL_HPP_INCLUDED #define __MODEL_HPP_INCLUDED // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <iostream> #include <queue> // std::queue #include <string.h> #include "globals.hpp" #include "shader.hpp" #include "heightmap_loader.hpp" #include "objloader.hpp" namespace model { class World { public: // constructor. World(); // destructor. ~World(); // this method renders the entire world, one shader at a time. void render(); // this method sets a shader pointer. void set_pointer(GLuint shaderID, void* shader_pointer); // this method gets a shader pointer. void* get_pointer(GLuint shaderID); // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue. GLuint get_shaderID(); private: std::vector<void*> shader_pointer_vector; std::queue<GLuint> free_shaderID_queue; }; class Shader { public: // constructor. Shader(ShaderStruct shader_struct); // destructor. ~Shader(); // this method renders all species using this shader. void render(); // this method sets a species pointer. void set_pointer(GLuint speciesID, void* species_pointer); // this method gets a species pointer. void* get_pointer(GLuint speciesID); // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue. GLuint get_speciesID(); // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world. void switch_to_new_world(model::World *new_world_pointer); model::World *world_pointer; // pointer to the world. GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. GLuint programID; // shaders' programID, returned by `LoadShaders`. private: std::vector<void*> species_pointer_vector; std::queue<GLuint> free_speciesID_queue; const char *char_vertex_shader; const char *char_fragment_shader; }; class Graph { public: // constructor. Graph(); // destructor. ~Graph(); // this method sets a node pointer. void set_pointer(GLuint nodeID, void* node_pointer); // this method gets a node pointer. void* get_pointer(GLuint nodeID); // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue. GLuint get_nodeID(); private: std::vector<void*> node_pointer_vector; std::queue<GLuint> free_nodeID_queue; }; // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph. // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s. // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`). class Node { public: // constructor. Node(NodeStruct node_struct); // destructor. ~Node(); // this method creates a bidirectional link. // creating of bidirectional links is not possible before all nodes are created. void create_bidirectional_link(GLuint nodeID); // this method deletes a bidirectional link. // deleting of links is not possible before all nodes are created. void delete_bidirectional_link(GLuint nodeID); // this method transfers this node to a new graph. // links will not be changed. // all nodes that are to be transferred must be transferred separately. // before transfering any node to a new graph, // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls. void transfer_to_new_graph(model::Graph *new_graph_pointer); GLuint nodeID; model::Graph *graph_pointer; // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created. std::vector<GLuint> neighbor_nodeIDs; private: // this method creates an unidirectional link. // in the constructor only unidirectional links can be created. void create_unidirectional_link(GLuint nodeID); // this method deletes an unidirectional link. void delete_unidirectional_link(GLuint nodeID); glm::vec3 coordinate_vector; }; class Species { public: // constructor. Species(SpeciesStruct species_struct); // destructor. ~Species(); // this method renders all objects of this species. void render(); // this method sets a object pointer. void set_pointer(GLuint objectID, void* object_pointer); // this method gets a object pointer. void* get_pointer(GLuint objectID); // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue. GLuint get_objectID(); // this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader. void switch_to_new_shader(model::Shader *new_shader_pointer); std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. glm::vec3 lightPos; // light position. void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!). void *texture_pointer; // pointer to the texture species (not yet in use!). // The rest fields are created in the constructor. GLuint MatrixID; GLuint ViewMatrixID; GLuint ModelMatrixID; GLuint vertexPosition_modelspaceID; GLuint vertexUVID; GLuint vertexNormal_modelspaceID; std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory). std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_UVs; std::vector<glm::vec3> indexed_normals; GLuint vertexbuffer; GLuint uvbuffer; GLuint normalbuffer; GLuint elementbuffer; glm::mat4 ProjectionMatrix; glm::mat4 ViewMatrix; private: model::Shader *shader_pointer; // pointer to the shader. GLuint speciesID; // species ID, returned by `model::World->get_speciesID()`. GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`. GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. const char *char_model_file_format; const char *char_model_filename; const char *char_texture_file_format; const char *char_texture_filename; const char *char_color_channel; std::vector<void*> object_pointer_vector; std::queue<GLuint> free_objectID_queue; }; class Object { public: // constructor. Object(ObjectStruct object_struct); // destructor. ~Object(); // this method renders this object. void render(); // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species. void switch_to_new_species(model::Species *new_species_pointer); model::Species *species_pointer; // pointer to the species. GLuint objectID; // object ID, returned by `model::Species->get_objectID()`. bool has_entered; glm::vec3 coordinate_vector; // rotate vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. // The rest fields are created in the constructor. glm::mat4 model_matrix; // model matrix. std::vector<glm::vec3> vertices; // vertices of the object. std::vector<glm::vec2> UVs; // UVs of the object. std::vector<glm::vec3> normals; // normals of the object. not used at the moment. glm::mat4 MVP_matrix; // model view projection matrix. }; } #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSceneReaderV1.h" #include "mitkSerializerMacros.h" #include "mitkBaseRenderer.h" #include "mitkPropertyListDeserializer.h" #include "mitkProgressBar.h" #include "mitkIOUtil.h" #include "Poco/Path.h" #include <mitkRenderingModeProperty.h> MITK_REGISTER_SERIALIZER(SceneReaderV1) namespace { typedef std::pair<mitk::DataNode::Pointer, std::list<std::string> > NodesAndParentsPair; bool NodeSortByLayerIsLessThan( const NodesAndParentsPair& left, const NodesAndParentsPair& right ) { if ( left.first.IsNotNull() && right.first.IsNotNull() ) { int leftLayer; int rightLayer; if ( left.first->GetIntProperty("layer", leftLayer) && right.first->GetIntProperty("layer", rightLayer) ) { return leftLayer < rightLayer; } else { // fall back to name sort return left.first->GetName() < right.first->GetName(); } } // in all other cases, fall back to stupid pointer comparison // this is not reasonable but at least answers the sorting // question clearly return left.first.GetPointer() < right.first.GetPointer(); } } bool mitk::SceneReaderV1::LoadScene( TiXmlDocument& document, const std::string& workingDirectory, DataStorage* storage ) { assert(storage); bool error(false); // TODO prepare to detect errors (such as cycles) from wrongly written or edited xml files //Get number of elements to initialze progress bar // 1. if there is a <data type="..." file="..."> element, // - construct a name for the appropriate serializer // - try to instantiate this serializer via itk object factory // - if serializer could be created, use it to read the file into a BaseData object // - if successful, call the new node's SetData(..) // create a node for the tag "data" and test if node was created typedef std::vector<mitk::DataNode::Pointer> DataNodeVector; DataNodeVector DataNodes; unsigned int listSize = 0; for( TiXmlElement* element = document.FirstChildElement("node"); element != NULL; element = element->NextSiblingElement("node") ) { ++listSize; } ProgressBar::GetInstance()->AddStepsToDo(listSize * 2); for (TiXmlElement* element = document.FirstChildElement("node"); element != NULL; element = element->NextSiblingElement("node")) { DataNodes.push_back(LoadBaseDataFromDataTag(element->FirstChildElement("data"), workingDirectory, error)); ProgressBar::GetInstance()->Progress(); } // iterate all nodes // first level nodes should be <node> elements DataNodeVector::iterator nit = DataNodes.begin(); for( TiXmlElement* element = document.FirstChildElement("node"); element != NULL || nit != DataNodes.end(); element = element->NextSiblingElement("node"), ++nit ) { mitk::DataNode::Pointer node = *nit; // in case dataXmlElement is valid test whether it containts the "properties" child tag // and process further if and only if yes TiXmlElement *dataXmlElement = element->FirstChildElement("data"); if( dataXmlElement && dataXmlElement->FirstChildElement("properties") ) { TiXmlElement *baseDataElement = dataXmlElement->FirstChildElement("properties"); if ( node->GetData() ) { DecorateBaseDataWithProperties( node->GetData(), baseDataElement, workingDirectory); } else { MITK_WARN << "BaseData properties stored in scene file, but BaseData could not be read" << std::endl; } } // 2. check child nodes const char* uida = element->Attribute("UID"); std::string uid(""); if (uida) { uid = uida; m_NodeForID[uid] = node.GetPointer(); m_IDForNode[ node.GetPointer() ] = uid; } else { MITK_ERROR << "No UID found for current node. Node will have no parents."; error = true; } // 3. if there are <properties> nodes, // - instantiate the appropriate PropertyListDeSerializer // - use them to construct PropertyList objects // - add these properties to the node (if necessary, use renderwindow name) bool success = DecorateNodeWithProperties(node, element, workingDirectory); if (!success) { MITK_ERROR << "Could not load properties for node."; error = true; } // remember node for later adding to DataStorage m_OrderedNodePairs.push_back( std::make_pair( node, std::list<std::string>() ) ); // 4. if there are <source> elements, remember parent objects for( TiXmlElement* source = element->FirstChildElement("source"); source != NULL; source = source->NextSiblingElement("source") ) { const char* sourceUID = source->Attribute("UID"); if (sourceUID) { m_OrderedNodePairs.back().second.push_back( std::string(sourceUID) ); } } ProgressBar::GetInstance()->Progress(); } // end for all <node> // sort our nodes by their "layer" property // (to be inserted in that order) m_OrderedNodePairs.sort( &NodeSortByLayerIsLessThan ); // remove all unknown parent UIDs for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { for (std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end();) { if (m_NodeForID.find( *parentsIter ) == m_NodeForID.end()) { parentsIter = nodesIter->second.erase( parentsIter ); MITK_WARN << "Found a DataNode with unknown parents. Will add it to DataStorage without any parent objects."; error = true; } else { ++parentsIter; } } } // repeat the following loop ... // ... for all created nodes unsigned int lastMapSize(0); while ( lastMapSize != m_OrderedNodePairs.size()) // this is to prevent infinite loops; each iteration must at least add one node to DataStorage { lastMapSize = m_OrderedNodePairs.size(); // iterate (layer) ordered nodes backwards // we insert the highest layers first for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { bool addThisNode(true); // if any parent node is not yet in DataStorage, skip node for now and check later for (std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { if ( !storage->Exists( m_NodeForID[ *parentsIter ] ) ) { addThisNode = false; break; } } if (addThisNode) { DataStorage::SetOfObjects::Pointer parents = DataStorage::SetOfObjects::New(); for ( std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter ) { parents->push_back(m_NodeForID[*parentsIter]); } // if all parents are found in datastorage (or are unknown), add node to DataStorage storage->Add(nodesIter->first, parents); // remove this node from m_OrderedNodePairs m_OrderedNodePairs.erase( nodesIter ); // break this for loop because iterators are probably invalid break; } } } // All nodes that are still in m_OrderedNodePairs at this point are not part of a proper directed graph structure. We'll add such nodes without any parent information. for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { storage->Add( nodesIter->first ); MITK_WARN << "Encountered node that is not part of a directed graph structure. Will be added to DataStorage without parents."; error = true; } return !error; } mitk::DataNode::Pointer mitk::SceneReaderV1::LoadBaseDataFromDataTag( TiXmlElement* dataElement, const std::string& workingDirectory, bool& error ) { DataNode::Pointer node; if (dataElement) { const char* filename = dataElement->Attribute("file"); if ( filename ) { try { std::vector<BaseData::Pointer> baseData = IOUtil::Load( workingDirectory + Poco::Path::separator() + filename ); if (baseData.size() > 1) { MITK_WARN << "Discarding multiple base data results from " << filename << " except the first one."; } node = DataNode::New(); node->SetData(baseData.front()); } catch (std::exception& e) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Exception says: " << e.what(); error = true; } if (node.IsNull()) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Factory returned NULL object."; error = true; } } } // in case there was no <data> element we create a new empty node (for appending a propertylist later) if (node.IsNull()) { node = DataNode::New(); } return node; } void mitk::SceneReaderV1::ClearNodePropertyListWithExceptions(DataNode& node, PropertyList& propertyList) { // Basically call propertyList.Clear(), but implement exceptions (see bug 19354) BaseData* data = node.GetData(); PropertyList::Pointer propertiesToKeep = PropertyList::New(); if (dynamic_cast<Image*>(data)) { /* Older scene files (before changes of bug 17547) could contain a RenderingMode property with value "LevelWindow_Color". Since bug 17547 this value has been removed and replaced by the default value LookupTable_LevelWindow_Color. This new default value does only result in "black-to-white" CT images (or others) if there is a corresponding lookup table. Such a lookup table is provided as a default value by the Image mapper. Since that value was never present in older scene files, we do well in not removing the new default value here. Otherwise the mapper would fall back to another default which is all the colors of the rainbow :-( */ BaseProperty::Pointer lutProperty = propertyList.GetProperty("LookupTable"); propertiesToKeep->SetProperty("LookupTable", lutProperty); } propertyList.Clear(); propertyList.ConcatenatePropertyList(propertiesToKeep); } bool mitk::SceneReaderV1::DecorateNodeWithProperties(DataNode* node, TiXmlElement* nodeElement, const std::string& workingDirectory) { assert(node); assert(nodeElement); bool error(false); for( TiXmlElement* properties = nodeElement->FirstChildElement("properties"); properties != NULL; properties = properties->NextSiblingElement("properties") ) { const char* propertiesfilea( properties->Attribute("file") ); std::string propertiesfile( propertiesfilea ? propertiesfilea : "" ); const char* renderwindowa( properties->Attribute("renderwindow") ); std::string renderwindow( renderwindowa ? renderwindowa : "" ); PropertyList::Pointer propertyList = node->GetPropertyList(renderwindow); // DataNode implementation always returns a propertylist ClearNodePropertyListWithExceptions(*node, *propertyList); // use deserializer to construct new properties PropertyListDeserializer::Pointer deserializer = PropertyListDeserializer::New(); deserializer->SetFilename(workingDirectory + Poco::Path::separator() + propertiesfile); bool success = deserializer->Deserialize(); error |= !success; PropertyList::Pointer readProperties = deserializer->GetOutput(); if (readProperties.IsNotNull()) { propertyList->ConcatenatePropertyList( readProperties, true ); // true = replace } else { MITK_ERROR << "Property list reader did not return a property list. This is an implementation error. Please tell your developer."; error = true; } } return !error; } bool mitk::SceneReaderV1::DecorateBaseDataWithProperties(BaseData::Pointer data, TiXmlElement *baseDataNodeElem, const std::string &workingDir) { // check given variables, initialize error variable assert(baseDataNodeElem); bool error(false); // get the file name stored in the <properties ...> tag const char* baseDataPropertyFile( baseDataNodeElem->Attribute("file") ); // check if the filename was found if(baseDataPropertyFile) { //PropertyList::Pointer dataPropList = data->GetPropertyList(); PropertyListDeserializer::Pointer propertyDeserializer = PropertyListDeserializer::New(); // initialize the property reader propertyDeserializer->SetFilename(workingDir + Poco::Path::separator() + baseDataPropertyFile); bool ioSuccess = propertyDeserializer->Deserialize(); error = !ioSuccess; // get the output PropertyList::Pointer inProperties = propertyDeserializer->GetOutput(); // store the read-in properties to the given node or throw error otherwise if( inProperties.IsNotNull() ) { data->SetPropertyList( inProperties ); } else { MITK_ERROR << "The property deserializer did not return a (valid) property list."; error = true; } } else { MITK_ERROR << "Function DecorateBaseDataWithProperties(...) called with false TiXmlElement. \n \t ->Given element does not contain a 'file' attribute. \n"; error = true; } return !error; } <commit_msg>Keep multi-component flag for old scene files<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSceneReaderV1.h" #include "mitkSerializerMacros.h" #include "mitkBaseRenderer.h" #include "mitkPropertyListDeserializer.h" #include "mitkProgressBar.h" #include "mitkIOUtil.h" #include "Poco/Path.h" #include <mitkRenderingModeProperty.h> MITK_REGISTER_SERIALIZER(SceneReaderV1) namespace { typedef std::pair<mitk::DataNode::Pointer, std::list<std::string> > NodesAndParentsPair; bool NodeSortByLayerIsLessThan( const NodesAndParentsPair& left, const NodesAndParentsPair& right ) { if ( left.first.IsNotNull() && right.first.IsNotNull() ) { int leftLayer; int rightLayer; if ( left.first->GetIntProperty("layer", leftLayer) && right.first->GetIntProperty("layer", rightLayer) ) { return leftLayer < rightLayer; } else { // fall back to name sort return left.first->GetName() < right.first->GetName(); } } // in all other cases, fall back to stupid pointer comparison // this is not reasonable but at least answers the sorting // question clearly return left.first.GetPointer() < right.first.GetPointer(); } } bool mitk::SceneReaderV1::LoadScene( TiXmlDocument& document, const std::string& workingDirectory, DataStorage* storage ) { assert(storage); bool error(false); // TODO prepare to detect errors (such as cycles) from wrongly written or edited xml files //Get number of elements to initialze progress bar // 1. if there is a <data type="..." file="..."> element, // - construct a name for the appropriate serializer // - try to instantiate this serializer via itk object factory // - if serializer could be created, use it to read the file into a BaseData object // - if successful, call the new node's SetData(..) // create a node for the tag "data" and test if node was created typedef std::vector<mitk::DataNode::Pointer> DataNodeVector; DataNodeVector DataNodes; unsigned int listSize = 0; for( TiXmlElement* element = document.FirstChildElement("node"); element != NULL; element = element->NextSiblingElement("node") ) { ++listSize; } ProgressBar::GetInstance()->AddStepsToDo(listSize * 2); for (TiXmlElement* element = document.FirstChildElement("node"); element != NULL; element = element->NextSiblingElement("node")) { DataNodes.push_back(LoadBaseDataFromDataTag(element->FirstChildElement("data"), workingDirectory, error)); ProgressBar::GetInstance()->Progress(); } // iterate all nodes // first level nodes should be <node> elements DataNodeVector::iterator nit = DataNodes.begin(); for( TiXmlElement* element = document.FirstChildElement("node"); element != NULL || nit != DataNodes.end(); element = element->NextSiblingElement("node"), ++nit ) { mitk::DataNode::Pointer node = *nit; // in case dataXmlElement is valid test whether it containts the "properties" child tag // and process further if and only if yes TiXmlElement *dataXmlElement = element->FirstChildElement("data"); if( dataXmlElement && dataXmlElement->FirstChildElement("properties") ) { TiXmlElement *baseDataElement = dataXmlElement->FirstChildElement("properties"); if ( node->GetData() ) { DecorateBaseDataWithProperties( node->GetData(), baseDataElement, workingDirectory); } else { MITK_WARN << "BaseData properties stored in scene file, but BaseData could not be read" << std::endl; } } // 2. check child nodes const char* uida = element->Attribute("UID"); std::string uid(""); if (uida) { uid = uida; m_NodeForID[uid] = node.GetPointer(); m_IDForNode[ node.GetPointer() ] = uid; } else { MITK_ERROR << "No UID found for current node. Node will have no parents."; error = true; } // 3. if there are <properties> nodes, // - instantiate the appropriate PropertyListDeSerializer // - use them to construct PropertyList objects // - add these properties to the node (if necessary, use renderwindow name) bool success = DecorateNodeWithProperties(node, element, workingDirectory); if (!success) { MITK_ERROR << "Could not load properties for node."; error = true; } // remember node for later adding to DataStorage m_OrderedNodePairs.push_back( std::make_pair( node, std::list<std::string>() ) ); // 4. if there are <source> elements, remember parent objects for( TiXmlElement* source = element->FirstChildElement("source"); source != NULL; source = source->NextSiblingElement("source") ) { const char* sourceUID = source->Attribute("UID"); if (sourceUID) { m_OrderedNodePairs.back().second.push_back( std::string(sourceUID) ); } } ProgressBar::GetInstance()->Progress(); } // end for all <node> // sort our nodes by their "layer" property // (to be inserted in that order) m_OrderedNodePairs.sort( &NodeSortByLayerIsLessThan ); // remove all unknown parent UIDs for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { for (std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end();) { if (m_NodeForID.find( *parentsIter ) == m_NodeForID.end()) { parentsIter = nodesIter->second.erase( parentsIter ); MITK_WARN << "Found a DataNode with unknown parents. Will add it to DataStorage without any parent objects."; error = true; } else { ++parentsIter; } } } // repeat the following loop ... // ... for all created nodes unsigned int lastMapSize(0); while ( lastMapSize != m_OrderedNodePairs.size()) // this is to prevent infinite loops; each iteration must at least add one node to DataStorage { lastMapSize = m_OrderedNodePairs.size(); // iterate (layer) ordered nodes backwards // we insert the highest layers first for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { bool addThisNode(true); // if any parent node is not yet in DataStorage, skip node for now and check later for (std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { if ( !storage->Exists( m_NodeForID[ *parentsIter ] ) ) { addThisNode = false; break; } } if (addThisNode) { DataStorage::SetOfObjects::Pointer parents = DataStorage::SetOfObjects::New(); for ( std::list<std::string>::iterator parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter ) { parents->push_back(m_NodeForID[*parentsIter]); } // if all parents are found in datastorage (or are unknown), add node to DataStorage storage->Add(nodesIter->first, parents); // remove this node from m_OrderedNodePairs m_OrderedNodePairs.erase( nodesIter ); // break this for loop because iterators are probably invalid break; } } } // All nodes that are still in m_OrderedNodePairs at this point are not part of a proper directed graph structure. We'll add such nodes without any parent information. for (OrderedNodesList::iterator nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { storage->Add( nodesIter->first ); MITK_WARN << "Encountered node that is not part of a directed graph structure. Will be added to DataStorage without parents."; error = true; } return !error; } mitk::DataNode::Pointer mitk::SceneReaderV1::LoadBaseDataFromDataTag( TiXmlElement* dataElement, const std::string& workingDirectory, bool& error ) { DataNode::Pointer node; if (dataElement) { const char* filename = dataElement->Attribute("file"); if ( filename ) { try { std::vector<BaseData::Pointer> baseData = IOUtil::Load( workingDirectory + Poco::Path::separator() + filename ); if (baseData.size() > 1) { MITK_WARN << "Discarding multiple base data results from " << filename << " except the first one."; } node = DataNode::New(); node->SetData(baseData.front()); } catch (std::exception& e) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Exception says: " << e.what(); error = true; } if (node.IsNull()) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Factory returned NULL object."; error = true; } } } // in case there was no <data> element we create a new empty node (for appending a propertylist later) if (node.IsNull()) { node = DataNode::New(); } return node; } void mitk::SceneReaderV1::ClearNodePropertyListWithExceptions(DataNode& node, PropertyList& propertyList) { // Basically call propertyList.Clear(), but implement exceptions (see bug 19354) BaseData* data = node.GetData(); PropertyList::Pointer propertiesToKeep = PropertyList::New(); if (dynamic_cast<Image*>(data)) { /* Older scene files (before changes of bug 17547) could contain a RenderingMode property with value "LevelWindow_Color". Since bug 17547 this value has been removed and replaced by the default value LookupTable_LevelWindow_Color. This new default value does only result in "black-to-white" CT images (or others) if there is a corresponding lookup table. Such a lookup table is provided as a default value by the Image mapper. Since that value was never present in older scene files, we do well in not removing the new default value here. Otherwise the mapper would fall back to another default which is all the colors of the rainbow :-( */ BaseProperty::Pointer lutProperty = propertyList.GetProperty("LookupTable"); propertiesToKeep->SetProperty("LookupTable", lutProperty); /* Older scene files (before changes of T14807) may contain multi-component images without the "Image.Displayed Component" property. As the treatment as multi-component image and the corresponding visualization options hinges on that property we should not delete it, if it was added by the mapper. Old diffusion images might contain the "DisplayChannel" property which stores the same information, however ignoring it is an acceptable loss of precision as usually which channel is selected is not terribly important. This is a fix for the issue reported in T19919. */ BaseProperty::Pointer compProperty = propertyList.GetProperty("Image.Displayed Component"); if (compProperty.IsNotNull()) { propertiesToKeep->SetProperty("Image.Displayed Component", compProperty); } } propertyList.Clear(); propertyList.ConcatenatePropertyList(propertiesToKeep); } bool mitk::SceneReaderV1::DecorateNodeWithProperties(DataNode* node, TiXmlElement* nodeElement, const std::string& workingDirectory) { assert(node); assert(nodeElement); bool error(false); for( TiXmlElement* properties = nodeElement->FirstChildElement("properties"); properties != NULL; properties = properties->NextSiblingElement("properties") ) { const char* propertiesfilea( properties->Attribute("file") ); std::string propertiesfile( propertiesfilea ? propertiesfilea : "" ); const char* renderwindowa( properties->Attribute("renderwindow") ); std::string renderwindow( renderwindowa ? renderwindowa : "" ); PropertyList::Pointer propertyList = node->GetPropertyList(renderwindow); // DataNode implementation always returns a propertylist ClearNodePropertyListWithExceptions(*node, *propertyList); // use deserializer to construct new properties PropertyListDeserializer::Pointer deserializer = PropertyListDeserializer::New(); deserializer->SetFilename(workingDirectory + Poco::Path::separator() + propertiesfile); bool success = deserializer->Deserialize(); error |= !success; PropertyList::Pointer readProperties = deserializer->GetOutput(); if (readProperties.IsNotNull()) { propertyList->ConcatenatePropertyList( readProperties, true ); // true = replace } else { MITK_ERROR << "Property list reader did not return a property list. This is an implementation error. Please tell your developer."; error = true; } } return !error; } bool mitk::SceneReaderV1::DecorateBaseDataWithProperties(BaseData::Pointer data, TiXmlElement *baseDataNodeElem, const std::string &workingDir) { // check given variables, initialize error variable assert(baseDataNodeElem); bool error(false); // get the file name stored in the <properties ...> tag const char* baseDataPropertyFile( baseDataNodeElem->Attribute("file") ); // check if the filename was found if(baseDataPropertyFile) { //PropertyList::Pointer dataPropList = data->GetPropertyList(); PropertyListDeserializer::Pointer propertyDeserializer = PropertyListDeserializer::New(); // initialize the property reader propertyDeserializer->SetFilename(workingDir + Poco::Path::separator() + baseDataPropertyFile); bool ioSuccess = propertyDeserializer->Deserialize(); error = !ioSuccess; // get the output PropertyList::Pointer inProperties = propertyDeserializer->GetOutput(); // store the read-in properties to the given node or throw error otherwise if( inProperties.IsNotNull() ) { data->SetPropertyList( inProperties ); } else { MITK_ERROR << "The property deserializer did not return a (valid) property list."; error = true; } } else { MITK_ERROR << "Function DecorateBaseDataWithProperties(...) called with false TiXmlElement. \n \t ->Given element does not contain a 'file' attribute. \n"; error = true; } return !error; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkToolManager.h" #include "mitkStandaloneDataStorage.h" #include "mitkCoreObjectFactory.h" #include "mitkGlobalInteraction.h" class mitkToolManagerTestClass { public: static void TestToolManagerWithOutTools(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetTools().size() == 0, "Get empty tool list" ) MITK_TEST_CONDITION( toolManager->GetToolById(0) == NULL, "Get empty tool by id" ) } static void TestToolManagerWithTools(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetTools().size() > 0, "Get tool list with size 1" ) MITK_TEST_CONDITION( toolManager->GetToolById(0) != NULL, "Test GetToolById() method" ) MITK_TEST_CONDITION( toolManager->ActivateTool(0) == true, "Activate tool" ) MITK_TEST_CONDITION( toolManager->GetActiveToolID() == 0, "Check for right tool id" ) mitk::Tool* tool = toolManager->GetActiveTool(); MITK_TEST_CONDITION( tool != NULL, "Check for right tool" ) } static void TestSetterMethods(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetReferenceData().size() == 0, "Get reference data size (0)" ) mitk::DataNode::Pointer nodeEmpty = mitk::DataNode::New(); toolManager->SetReferenceData(nodeEmpty); MITK_TEST_CONDITION( toolManager->GetReferenceData().size() == 1, "Get reference data size (1)" ) MITK_TEST_CONDITION( toolManager->GetReferenceData(0) == nodeEmpty, "Check if it is the right reference data" ) MITK_TEST_CONDITION( toolManager->GetReferenceData()[0] == nodeEmpty, "Check if it is the right reference data vector" ) mitk::DataNode::Pointer nodeEmpty2 = mitk::DataNode::New(); toolManager->SetWorkingData(nodeEmpty2); MITK_TEST_CONDITION( toolManager->GetWorkingData().size() == 1, "Get working data size (1)" ) MITK_TEST_CONDITION( toolManager->GetWorkingData(0) == nodeEmpty2, "Check if it is the right working data" ) MITK_TEST_CONDITION( toolManager->GetWorkingData()[0] == nodeEmpty2, "Check if it is the right working data vector" ) } }; int mitkToolManagerTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("ToolManager") // Global interaction must(!) be initialized if used mitk::GlobalInteraction::GetInstance()->Initialize("global"); // instantiation mitk::StandaloneDataStorage::Pointer dataStorage = mitk::StandaloneDataStorage::New(); mitk::ToolManager::Pointer toolManager = mitk::ToolManager::New(dataStorage.GetPointer()); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(toolManager.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! //mitkToolManagerTestClass::TestToolManagerWithOutTools(toolManager); //now we add one tool toolManager = mitk::ToolManager::New(dataStorage.GetPointer()); //start test with tool mitkToolManagerTestClass::TestToolManagerWithTools(toolManager); //now the setter methods mitkToolManagerTestClass::TestSetterMethods(toolManager); // always end with this! MITK_TEST_END() } <commit_msg>COMP: Try to find out what causes the segfault.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkToolManager.h" #include "mitkStandaloneDataStorage.h" #include "mitkCoreObjectFactory.h" #include "mitkGlobalInteraction.h" class mitkToolManagerTestClass { public: static void TestToolManagerWithOutTools(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetTools().size() == 0, "Get empty tool list" ) MITK_TEST_CONDITION( toolManager->GetToolById(0) == NULL, "Get empty tool by id" ) } static void TestToolManagerWithTools(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetTools().size() > 0, "Get tool list with size 1" ) MITK_TEST_CONDITION( toolManager->GetToolById(0) != NULL, "Test GetToolById() method" ) MITK_TEST_CONDITION( toolManager->ActivateTool(0) == true, "Activate tool" ) MITK_TEST_CONDITION( toolManager->GetActiveToolID() == 0, "Check for right tool id" ) mitk::Tool* tool = toolManager->GetActiveTool(); MITK_TEST_CONDITION( tool != NULL, "Check for right tool" ) } static void TestSetterMethods(mitk::ToolManager::Pointer toolManager) { MITK_TEST_CONDITION( toolManager->GetReferenceData().size() == 0, "Get reference data size (0)" ) mitk::DataNode::Pointer nodeEmpty = mitk::DataNode::New(); toolManager->SetReferenceData(nodeEmpty); MITK_TEST_CONDITION( toolManager->GetReferenceData().size() == 1, "Get reference data size (1)" ) MITK_TEST_CONDITION( toolManager->GetReferenceData(0) == nodeEmpty, "Check if it is the right reference data" ) MITK_TEST_CONDITION( toolManager->GetReferenceData()[0] == nodeEmpty, "Check if it is the right reference data vector" ) mitk::DataNode::Pointer nodeEmpty2 = mitk::DataNode::New(); toolManager->SetWorkingData(nodeEmpty2); MITK_TEST_CONDITION( toolManager->GetWorkingData().size() == 1, "Get working data size (1)" ) MITK_TEST_CONDITION( toolManager->GetWorkingData(0) == nodeEmpty2, "Check if it is the right working data" ) MITK_TEST_CONDITION( toolManager->GetWorkingData()[0] == nodeEmpty2, "Check if it is the right working data vector" ) } }; int mitkToolManagerTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("ToolManager") // Global interaction must(!) be initialized if used /*TEMP mitk::GlobalInteraction::GetInstance()->Initialize("global"); // instantiation mitk::StandaloneDataStorage::Pointer dataStorage = mitk::StandaloneDataStorage::New(); mitk::ToolManager::Pointer toolManager = mitk::ToolManager::New(dataStorage.GetPointer()); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(toolManager.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! //mitkToolManagerTestClass::TestToolManagerWithOutTools(toolManager); //now we add one tool toolManager = mitk::ToolManager::New(dataStorage.GetPointer()); //start test with tool mitkToolManagerTestClass::TestToolManagerWithTools(toolManager); //now the setter methods mitkToolManagerTestClass::TestSetterMethods(toolManager);TEMP*/ // always end with this! MITK_TEST_END() } <|endoftext|>
<commit_before>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); pinMode(PIN_LINE_LED,OUTPUT); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = readLineSensor(0); int longPin = 0; for (int i=1; i<8; i++) { long long iTime = readLineSensor(i); if (iTime < longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y, int r) { double i = y*sqrt(3)/2 + x/2 + r; double j = y*sqrt(3)/2 - x/2 - r; double k = x - r; double coef = 100.0/(((i>j)?i:j)>k?((i>j)?i:j):k); setMotors(i*coef,j*coef,k*coef); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k>0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); usleep(100000); } <commit_msg>actually return stuff lol<commit_after>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); pinMode(PIN_LINE_LED,OUTPUT); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = readLineSensor(0); int longPin = 0; for (int i=1; i<8; i++) { long long iTime = readLineSensor(i); if (iTime < longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y, int r) { double i = y*sqrt(3)/2 + x/2 + r; double j = y*sqrt(3)/2 - x/2 - r; double k = x - r; double coef = 100.0/(((i>j)?i:j)>k?((i>j)?i:j):k); setMotors(i*coef,j*coef,k*coef); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k>0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); usleep(100000); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Joseph Thomson * * 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. */ #pragma once #ifndef OBSERVER_HPP #define OBSERVER_HPP #include <functional> #include <iosfwd> #include <utility> //========== // observer //========== template <typename T> class observer; template <typename T> constexpr T* get_pointer(observer<T> const&) noexcept; template <typename T> class observer { public: using element_type = T; private: T* target; public: constexpr explicit observer(T& r) noexcept : target(&r) { } constexpr explicit observer(T&&) noexcept = delete; template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr observer(observer<U> const& i) noexcept : target(get_pointer(i)) { } constexpr T& operator*() const noexcept { return *target; } constexpr T* operator->() const noexcept { return target; } constexpr explicit operator T*() const noexcept { return target; } void swap(observer& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> constexpr observer<T> make_observer(T& r) noexcept { return observer<T>(r); } template <typename T> observer<T> make_observer(T&&) = delete; template <typename T> constexpr T* get_pointer(observer<T> const& i) noexcept { return static_cast<T*>(i); } template <typename T> void swap(observer<T>& lhs, observer<T>& rhs) { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator!=(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator<(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator<=(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> std::ostream& operator<<(std::ostream& s, observer<T> const& i) { return s << get_pointer(i); } namespace std { template <typename T> struct hash<observer<T>> { constexpr std::size_t operator()(observer<T> const& i) const noexcept { return hash<T*>()(get_pointer(i)); } }; } // namespace std //============== // observer_ptr //============== template <typename T> class observer_ptr; template <typename T> constexpr T* get_pointer(observer_ptr<T> const&) noexcept; template <typename T> class observer_ptr { public: using element_type = T; private: T* target; public: constexpr observer_ptr() noexcept : target() { } constexpr explicit observer_ptr(T& r) noexcept : target(&r) { } constexpr explicit observer_ptr(T&&) noexcept = delete; constexpr observer_ptr(observer<T> const& i) noexcept : target(get_pointer(i)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr observer_ptr(observer<U> const& i) noexcept : target(get_pointer(i)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr observer_ptr(observer_ptr<U> const& i) noexcept : target(get_pointer(i)) { } constexpr observer_ptr(std::nullptr_t) noexcept : target(nullptr) { } constexpr explicit observer_ptr(T* p) noexcept : target(p) { } constexpr explicit operator bool() const noexcept { return target != nullptr; } constexpr T& operator*() const { return *target; } constexpr T* operator->() const { return target; } constexpr explicit operator T*() const noexcept { return target; } void swap(observer_ptr& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> constexpr T* get_pointer(observer_ptr<T> const& i) noexcept { return static_cast<T*>(i); } template <typename T> void swap(observer_ptr<T>& lhs, observer_ptr<T>& rhs) noexcept { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T> constexpr bool operator==(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return !lhs; } template <typename T> constexpr bool operator==(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return !rhs; } template <typename T1, typename T2> constexpr bool operator!=(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T> constexpr bool operator!=(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return !(lhs == nullptr); } template <typename T> constexpr bool operator!=(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return !(nullptr == rhs); } template <typename T1, typename T2> constexpr bool operator<(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator<(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator<(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T> constexpr bool operator<(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return std::less<T*>()(get_pointer(lhs), nullptr); } template <typename T> constexpr bool operator<(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return std::less<T*>()(nullptr, get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator>(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator>(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T> constexpr bool operator>(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return nullptr < lhs; } template <typename T> constexpr bool operator>(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return rhs < nullptr; } template <typename T1, typename T2> constexpr bool operator<=(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator<=(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator<=(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T> constexpr bool operator<=(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return !(nullptr < lhs); } template <typename T> constexpr bool operator<=(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return !(rhs < nullptr); } template <typename T1, typename T2> constexpr bool operator>=(observer_ptr<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T1, typename T2> constexpr bool operator>=(observer_ptr<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T1, typename T2> constexpr bool operator>=(observer<T1> const& lhs, observer_ptr<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> constexpr bool operator>=(observer_ptr<T> const& lhs, std::nullptr_t) noexcept { return !(lhs < nullptr); } template <typename T> constexpr bool operator>=(std::nullptr_t, observer_ptr<T> const& rhs) noexcept { return !(nullptr < rhs); } template <typename T> std::ostream& operator<<(std::ostream& s, observer_ptr<T> const& i) { return s << get_pointer(i); } namespace std { template <typename T> struct hash<observer_ptr<T>> { constexpr std::size_t operator()(observer_ptr<T> const& i) const noexcept { return hash<T*>()(get_pointer(i)); } }; } // namespace std #endif // OBSERVER_HPP <commit_msg>Remove `observer_ptr<T>` entirely.<commit_after>/* * Copyright (c) 2016 Joseph Thomson * * 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 GSL_OBSERVER_HPP #define GSL_OBSERVER_HPP #include <functional> #include <type_traits> namespace gsl { template <typename T> class observer { public: using element_type = T; constexpr explicit observer(T& t) noexcept : ptr(&t) { } constexpr explicit observer(T&&) noexcept = delete; template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr observer(observer<U> const& o) noexcept : ptr(static_cast<U*>(o)) { } constexpr T& operator*() const noexcept { return *ptr; } constexpr T* operator->() const noexcept { return ptr; } constexpr explicit operator T*() const noexcept { return ptr; } void swap(observer& other) noexcept { using std::swap; swap(ptr, other.ptr); } private: T* ptr; }; template <typename T> constexpr observer<T> make_observer(T& t) noexcept { return observer<T>(t); } template <typename T> observer<T> make_observer(T&&) = delete; template <typename T> void swap(observer<T>& lhs, observer<T>& rhs) { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return static_cast<T1*>(lhs) == static_cast<T2*>(rhs); } template <typename T1, typename T2> constexpr bool operator!=(observer<T1> const& lhs, observer<T2> const& rhs) noexcept { return !(lhs == rhs); } } // namespace gsl namespace std { template <typename T> struct less<observer<T>> { constexpr bool operator()(observer<T> const& lhs, observer<T> const& rhs) const noexcept { return less<T*>(static_cast<T*>(lhs), static_cast<T*>(rhs)); } }; template <typename T> struct hash<observer<T>> { constexpr std::size_t operator()(observer<T> const& o) const noexcept { return hash<T*>()(static_cast<T*>(o)); } }; } // namespace std #endif // GSL_OBSERVER_HPP <|endoftext|>
<commit_before>/* * wexcept.hpp * Classes to handle exceptions with const wchar_t* messages * * written by janus_wel<janus.wel.3@gmail.com> * This source code is in the public domain, and has NO WARRANTY. * */ #ifndef WEXCEPT_HPP #define WEXCEPT_HPP #include <exception> #include <string> namespace util { namespace exception { class wexception { public: virtual ~wexception(void) throw() {} virtual const wchar_t* what(void) const throw() = 0; }; class wlogic_error : public wexception { protected: std::wstring errmsg; public: wlogic_error(std::wstring errmsg = std::wstring(L"")) throw() : errmsg(errmsg) {} virtual ~wlogic_error(void) throw() {} virtual const wchar_t* what(void) const throw() { return errmsg.c_str(); } }; class wruntime_error : public wexception { protected: std::wstring errmsg; public: wruntime_error(std::wstring errmsg = std::wstring(L"")) throw() : errmsg(errmsg) {} virtual ~wruntime_error(void) throw() {} virtual const wchar_t* what(void) const throw() { return errmsg.c_str(); } }; } } #endif // WEXCEPT_HPP <commit_msg>Add some comments and change some return types<commit_after>/* * wexcept.hpp * Classes to handle exceptions with const wchar_t* messages * * written by janus_wel<janus.wel.3@gmail.com> * This source code is in the public domain, and has NO WARRANTY. * */ #ifndef WEXCEPT_HPP #define WEXCEPT_HPP #include <string> // TODO?: Define other exceptions that are corresponding ones defined by <exception>. namespace util { namespace exception { // base class class wexception { public: virtual ~wexception(void) throw() {} virtual const std::wstring& what(void) const throw() = 0; }; // corresponding to std::logic_error class wlogic_error : public wexception { protected: std::wstring errmsg; public: wlogic_error(std::wstring errmsg = std::wstring(L"")) throw() : errmsg(errmsg) {} virtual ~wlogic_error(void) throw() {} virtual const std::wstring& what(void) const throw() { return errmsg; } }; // corresponding to std::runtime_error class wruntime_error : public wexception { protected: std::wstring errmsg; public: wruntime_error(std::wstring errmsg = std::wstring(L"")) throw() : errmsg(errmsg) {} virtual ~wruntime_error(void) throw() {} virtual const std::wstring& what(void) const throw() { return errmsg; } }; } } #endif // WEXCEPT_HPP <|endoftext|>
<commit_before>#include "openCLUtilities.hpp" cl::Context createCLContext(cl_device_type type, bool GLInterop, cl_vendor vendor) { // Get available platforms cl::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(platforms.size() == 0) throw cl::Error(1, "No OpenCL platforms were found"); cl::Platform platform = platforms[0]; // Use the preferred platform and create a context cl_context_properties cps[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platform)(), 0 }; try { cl::Context context = cl::Context(type, cps); return context; } catch(cl::Error error) { throw cl::Error(1, "Failed to create an OpenCL context!"); } } cl::Program buildProgramFromSource(cl::Context context, std::string filename) { // Read source file std::ifstream sourceFile(filename.c_str()); if(sourceFile.fail()) throw cl::Error(1, "Failed to open OpenCL source file"); std::string sourceCode( std::istreambuf_iterator<char>(sourceFile), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length()+1)); // Make program of the source code in the context cl::Program program = cl::Program(context, source); cl::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); // Build program for these specific devices try{ program.build(devices); } catch(cl::Error error) { if(error.err() == CL_BUILD_PROGRAM_FAILURE) { std::cout << "Build log:\t" << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl; } throw error; } return program; } char *getCLErrorString(cl_int err) { switch (err) { case CL_SUCCESS: return (char *) "Success!"; case CL_DEVICE_NOT_FOUND: return (char *) "Device not found."; case CL_DEVICE_NOT_AVAILABLE: return (char *) "Device not available"; case CL_COMPILER_NOT_AVAILABLE: return (char *) "Compiler not available"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return (char *) "Memory object allocation failure"; case CL_OUT_OF_RESOURCES: return (char *) "Out of resources"; case CL_OUT_OF_HOST_MEMORY: return (char *) "Out of host memory"; case CL_PROFILING_INFO_NOT_AVAILABLE: return (char *) "Profiling information not available"; case CL_MEM_COPY_OVERLAP: return (char *) "Memory copy overlap"; case CL_IMAGE_FORMAT_MISMATCH: return (char *) "Image format mismatch"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return (char *) "Image format not supported"; case CL_BUILD_PROGRAM_FAILURE: return (char *) "Program build failure"; case CL_MAP_FAILURE: return (char *) "Map failure"; case CL_INVALID_VALUE: return (char *) "Invalid value"; case CL_INVALID_DEVICE_TYPE: return (char *) "Invalid device type"; case CL_INVALID_PLATFORM: return (char *) "Invalid platform"; case CL_INVALID_DEVICE: return (char *) "Invalid device"; case CL_INVALID_CONTEXT: return (char *) "Invalid context"; case CL_INVALID_QUEUE_PROPERTIES: return (char *) "Invalid queue properties"; case CL_INVALID_COMMAND_QUEUE: return (char *) "Invalid command queue"; case CL_INVALID_HOST_PTR: return (char *) "Invalid host pointer"; case CL_INVALID_MEM_OBJECT: return (char *) "Invalid memory object"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return (char *) "Invalid image format descriptor"; case CL_INVALID_IMAGE_SIZE: return (char *) "Invalid image size"; case CL_INVALID_SAMPLER: return (char *) "Invalid sampler"; case CL_INVALID_BINARY: return (char *) "Invalid binary"; case CL_INVALID_BUILD_OPTIONS: return (char *) "Invalid build options"; case CL_INVALID_PROGRAM: return (char *) "Invalid program"; case CL_INVALID_PROGRAM_EXECUTABLE: return (char *) "Invalid program executable"; case CL_INVALID_KERNEL_NAME: return (char *) "Invalid kernel name"; case CL_INVALID_KERNEL_DEFINITION: return (char *) "Invalid kernel definition"; case CL_INVALID_KERNEL: return (char *) "Invalid kernel"; case CL_INVALID_ARG_INDEX: return (char *) "Invalid argument index"; case CL_INVALID_ARG_VALUE: return (char *) "Invalid argument value"; case CL_INVALID_ARG_SIZE: return (char *) "Invalid argument size"; case CL_INVALID_KERNEL_ARGS: return (char *) "Invalid kernel arguments"; case CL_INVALID_WORK_DIMENSION: return (char *) "Invalid work dimension"; case CL_INVALID_WORK_GROUP_SIZE: return (char *) "Invalid work group size"; case CL_INVALID_WORK_ITEM_SIZE: return (char *) "Invalid work item size"; case CL_INVALID_GLOBAL_OFFSET: return (char *) "Invalid global offset"; case CL_INVALID_EVENT_WAIT_LIST: return (char *) "Invalid event wait list"; case CL_INVALID_EVENT: return (char *) "Invalid event"; case CL_INVALID_OPERATION: return (char *) "Invalid operation"; case CL_INVALID_GL_OBJECT: return (char *) "Invalid OpenGL object"; case CL_INVALID_BUFFER_SIZE: return (char *) "Invalid buffer size"; case CL_INVALID_MIP_LEVEL: return (char *) "Invalid mip-map level"; default: return (char *) "Unknown"; } } <commit_msg>updated opencl utilities<commit_after>#include "openCLUtilities.hpp" #if defined __APPLE__ || defined(MACOSX) #else #if defined WIN32 #else #include <GL/glx.h> #endif #endif cl::Context createCLContext(cl_device_type type, bool GLInterop, cl_vendor vendor) { // Get available platforms cl::vector<cl::Platform> platforms; cl::Platform::get(&platforms); // TODO: create vendor selecting mechanism if(platforms.size() == 0) throw cl::Error(1, "No OpenCL platforms were found"); cl::Platform platform = platforms[0]; // Use the preferred platform and create a context cl_context_properties * cps; if(GLInterop) { #ifdef __APPLE || defined(MACOSX) cps = new cl_context_properties[5]; //TODO: Apple OpenGL interop #else cps = new cl_context_properties[7]; #ifdef WIN32 cps[0] = CL_GL_CONTEXT_KHR; cps[1] = (cl_context_properties)wglGetCurrentContext(); cps[2] = CL_WGL_HDC_KHR; cps[3] = (cl_context_properties)wglGetCurrentDC(); #else cps[0] = CL_GL_CONTEXT_KHR; cps[1] = (cl_context_properties)glXGetCurrentContext(); cps[2] = CL_GLX_DISPLAY_KHR; cps[3] = (cl_context_properties)glXGetCurrentDisplay(); #endif #endif // end if apple cps[4] = CL_CONTEXT_PLATFORM; cps[5] = (cl_context_properties)(platform)(); cps[6] = 0; } else { cps = new cl_context_properties[3]; cps[0] = CL_CONTEXT_PLATFORM; cps[1] = (cl_context_properties)(platform)(); cps[2] = 0; } try { cl::Context context = cl::Context(type, cps); return context; } catch(cl::Error error) { throw cl::Error(1, "Failed to create an OpenCL context!"); } } cl::Program buildProgramFromSource(cl::Context context, std::string filename) { // Read source file std::ifstream sourceFile(filename.c_str()); if(sourceFile.fail()) throw cl::Error(1, "Failed to open OpenCL source file"); std::string sourceCode( std::istreambuf_iterator<char>(sourceFile), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length()+1)); // Make program of the source code in the context cl::Program program = cl::Program(context, source); cl::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); // Build program for these specific devices try{ program.build(devices); } catch(cl::Error error) { if(error.err() == CL_BUILD_PROGRAM_FAILURE) { std::cout << "Build log:" << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl; } throw error; } return program; } char *getCLErrorString(cl_int err) { switch (err) { case CL_SUCCESS: return (char *) "Success!"; case CL_DEVICE_NOT_FOUND: return (char *) "Device not found."; case CL_DEVICE_NOT_AVAILABLE: return (char *) "Device not available"; case CL_COMPILER_NOT_AVAILABLE: return (char *) "Compiler not available"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return (char *) "Memory object allocation failure"; case CL_OUT_OF_RESOURCES: return (char *) "Out of resources"; case CL_OUT_OF_HOST_MEMORY: return (char *) "Out of host memory"; case CL_PROFILING_INFO_NOT_AVAILABLE: return (char *) "Profiling information not available"; case CL_MEM_COPY_OVERLAP: return (char *) "Memory copy overlap"; case CL_IMAGE_FORMAT_MISMATCH: return (char *) "Image format mismatch"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return (char *) "Image format not supported"; case CL_BUILD_PROGRAM_FAILURE: return (char *) "Program build failure"; case CL_MAP_FAILURE: return (char *) "Map failure"; case CL_INVALID_VALUE: return (char *) "Invalid value"; case CL_INVALID_DEVICE_TYPE: return (char *) "Invalid device type"; case CL_INVALID_PLATFORM: return (char *) "Invalid platform"; case CL_INVALID_DEVICE: return (char *) "Invalid device"; case CL_INVALID_CONTEXT: return (char *) "Invalid context"; case CL_INVALID_QUEUE_PROPERTIES: return (char *) "Invalid queue properties"; case CL_INVALID_COMMAND_QUEUE: return (char *) "Invalid command queue"; case CL_INVALID_HOST_PTR: return (char *) "Invalid host pointer"; case CL_INVALID_MEM_OBJECT: return (char *) "Invalid memory object"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return (char *) "Invalid image format descriptor"; case CL_INVALID_IMAGE_SIZE: return (char *) "Invalid image size"; case CL_INVALID_SAMPLER: return (char *) "Invalid sampler"; case CL_INVALID_BINARY: return (char *) "Invalid binary"; case CL_INVALID_BUILD_OPTIONS: return (char *) "Invalid build options"; case CL_INVALID_PROGRAM: return (char *) "Invalid program"; case CL_INVALID_PROGRAM_EXECUTABLE: return (char *) "Invalid program executable"; case CL_INVALID_KERNEL_NAME: return (char *) "Invalid kernel name"; case CL_INVALID_KERNEL_DEFINITION: return (char *) "Invalid kernel definition"; case CL_INVALID_KERNEL: return (char *) "Invalid kernel"; case CL_INVALID_ARG_INDEX: return (char *) "Invalid argument index"; case CL_INVALID_ARG_VALUE: return (char *) "Invalid argument value"; case CL_INVALID_ARG_SIZE: return (char *) "Invalid argument size"; case CL_INVALID_KERNEL_ARGS: return (char *) "Invalid kernel arguments"; case CL_INVALID_WORK_DIMENSION: return (char *) "Invalid work dimension"; case CL_INVALID_WORK_GROUP_SIZE: return (char *) "Invalid work group size"; case CL_INVALID_WORK_ITEM_SIZE: return (char *) "Invalid work item size"; case CL_INVALID_GLOBAL_OFFSET: return (char *) "Invalid global offset"; case CL_INVALID_EVENT_WAIT_LIST: return (char *) "Invalid event wait list"; case CL_INVALID_EVENT: return (char *) "Invalid event"; case CL_INVALID_OPERATION: return (char *) "Invalid operation"; case CL_INVALID_GL_OBJECT: return (char *) "Invalid OpenGL object"; case CL_INVALID_BUFFER_SIZE: return (char *) "Invalid buffer size"; case CL_INVALID_MIP_LEVEL: return (char *) "Invalid mip-map level"; default: return (char *) "Unknown"; } } <|endoftext|>
<commit_before><commit_msg>Made dashesy's changes to for loop that checks for additional parameters in OnFileConfig( )<commit_after><|endoftext|>
<commit_before>/*********************************************************************** filename: CEGuiGLFWSharedBase.cpp created: 12/2/2012 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # include <unistd.h> #endif #include "CEGUISamplesConfig.h" #include "CEGuiGLFWSharedBase.h" #include "SamplesFrameworkBase.h" #include "CEGUI/CEGUI.h" #include <stdexcept> #include <sstream> //----------------------------------------------------------------------------// CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0; double CEGuiGLFWSharedBase::d_frameTime = 0; int CEGuiGLFWSharedBase::d_modifiers = 0; bool CEGuiGLFWSharedBase::d_windowSized = false; int CEGuiGLFWSharedBase::d_newWindowWidth; int CEGuiGLFWSharedBase::d_newWindowHeight; //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::CEGuiGLFWSharedBase() { if (d_appInstance) throw CEGUI::InvalidRequestException( "CEGuiGLFWSharedBase instance already exists!"); d_appInstance = this; } //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase() { } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::run() { d_sampleApp->initialise(); // Input callbacks of glfw for CEGUI glfwSetKeyCallback(glfwKeyCallback); glfwSetCharCallback(glfwCharCallback); glfwSetMouseButtonCallback(glfwMouseButtonCallback); glfwSetMouseWheelCallback(glfwMouseWheelCallback); glfwSetMousePosCallback(glfwMousePosCallback); //Window callbacks glfwSetWindowSizeCallback(glfwWindowResizeCallback); d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set starting time d_frameTime = glfwGetTime(); while (!d_sampleApp->isQuitting() && glfwGetWindowParam(GLFW_OPENED)) { if (d_windowSized) { d_windowSized = false; CEGUI::System::getSingleton(). notifyDisplaySizeChanged( CEGUI::Sizef(static_cast<float>(d_newWindowWidth), static_cast<float>(d_newWindowHeight))); } drawFrame(); } d_sampleApp->deinitialise(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::destroyWindow() { glfwTerminate(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/) { glClear(GL_COLOR_BUFFER_BIT); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::endRendering() { glfwSwapBuffers(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::drawFrame() { // calculate time elapsed since last frame double time_now = glfwGetTime(); const double elapsed = time_now - d_frameTime; d_frameTime = time_now; d_appInstance->renderSingleFrame(static_cast<float>(elapsed)); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h) { // We cache this in order to minimise calls to notifyDisplaySizeChanged, // which happens in the main loop whenever d_windowSized is set to true. d_windowSized = true; d_newWindowWidth = w; d_newWindowHeight = h; } //----------------------------------------------------------------------------// CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey) { switch(glfwKey) { case GLFW_KEY_ESC : return CEGUI::Key::Escape; case GLFW_KEY_F1 : return CEGUI::Key::F1; case GLFW_KEY_F2 : return CEGUI::Key::F2; case GLFW_KEY_F3 : return CEGUI::Key::F3; case GLFW_KEY_F4 : return CEGUI::Key::F4; case GLFW_KEY_F5 : return CEGUI::Key::F5; case GLFW_KEY_F6 : return CEGUI::Key::F6; case GLFW_KEY_F7 : return CEGUI::Key::F7; case GLFW_KEY_F8 : return CEGUI::Key::F8; case GLFW_KEY_F9 : return CEGUI::Key::F9; case GLFW_KEY_F10 : return CEGUI::Key::F10; case GLFW_KEY_F11 : return CEGUI::Key::F11; case GLFW_KEY_F12 : return CEGUI::Key::F12; case GLFW_KEY_F13 : return CEGUI::Key::F13; case GLFW_KEY_F14 : return CEGUI::Key::F14; case GLFW_KEY_F15 : return CEGUI::Key::F15; case GLFW_KEY_UP : return CEGUI::Key::ArrowUp; case GLFW_KEY_DOWN : return CEGUI::Key::ArrowDown; case GLFW_KEY_LEFT : return CEGUI::Key::ArrowLeft; case GLFW_KEY_RIGHT : return CEGUI::Key::ArrowRight; case GLFW_KEY_LSHIFT : return CEGUI::Key::LeftShift; case GLFW_KEY_RSHIFT : return CEGUI::Key::RightShift; case GLFW_KEY_LCTRL : return CEGUI::Key::LeftControl; case GLFW_KEY_RCTRL : return CEGUI::Key::RightControl; case GLFW_KEY_LALT : return CEGUI::Key::LeftAlt; case GLFW_KEY_RALT : return CEGUI::Key::RightAlt; case GLFW_KEY_TAB : return CEGUI::Key::Tab; case GLFW_KEY_ENTER : return CEGUI::Key::Return; case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace; case GLFW_KEY_INSERT : return CEGUI::Key::Insert; case GLFW_KEY_DEL : return CEGUI::Key::Delete; case GLFW_KEY_PAGEUP : return CEGUI::Key::PageUp; case GLFW_KEY_PAGEDOWN : return CEGUI::Key::PageDown; case GLFW_KEY_HOME : return CEGUI::Key::Home; case GLFW_KEY_END : return CEGUI::Key::End; case GLFW_KEY_KP_ENTER : return CEGUI::Key::NumpadEnter; case GLFW_KEY_SPACE : return CEGUI::Key::Space; case 'A' : return CEGUI::Key::A; case 'B' : return CEGUI::Key::B; case 'C' : return CEGUI::Key::C; case 'D' : return CEGUI::Key::D; case 'E' : return CEGUI::Key::E; case 'F' : return CEGUI::Key::F; case 'G' : return CEGUI::Key::G; case 'H' : return CEGUI::Key::H; case 'I' : return CEGUI::Key::I; case 'J' : return CEGUI::Key::J; case 'K' : return CEGUI::Key::K; case 'L' : return CEGUI::Key::L; case 'M' : return CEGUI::Key::M; case 'N' : return CEGUI::Key::N; case 'O' : return CEGUI::Key::O; case 'P' : return CEGUI::Key::P; case 'Q' : return CEGUI::Key::Q; case 'R' : return CEGUI::Key::R; case 'S' : return CEGUI::Key::S; case 'T' : return CEGUI::Key::T; case 'U' : return CEGUI::Key::U; case 'V' : return CEGUI::Key::V; case 'W' : return CEGUI::Key::W; case 'X' : return CEGUI::Key::X; case 'Y' : return CEGUI::Key::Y; case 'Z' : return CEGUI::Key::Z; default : return CEGUI::Key::Unknown; } } //----------------------------------------------------------------------------// CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton) { switch(glfwButton) { case GLFW_MOUSE_BUTTON_LEFT : return CEGUI::LeftButton; case GLFW_MOUSE_BUTTON_RIGHT : return CEGUI::RightButton; case GLFW_MOUSE_BUTTON_MIDDLE : return CEGUI::MiddleButton; default : return CEGUI::NoButton; } } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action) { CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key); if(action == GLFW_PRESS) d_sampleApp->injectKeyDown(ceguiKey); else if (action == GLFW_RELEASE) d_sampleApp->injectKeyUp(ceguiKey); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action) { if(action == GLFW_PRESS) d_sampleApp->injectChar(character); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action) { CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key); if(action == GLFW_PRESS) d_sampleApp->injectMouseButtonDown(ceguiMouseButton); else if (action == GLFW_RELEASE) d_sampleApp->injectMouseButtonUp(ceguiMouseButton); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position) { static int lastPosition = 0; d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition)); lastPosition = position; } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y) { d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y)); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::initGLFW() { if(!glfwInit()) CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW.")); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::createGLFWWindow() { if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 0, 0, 0, 0, 24, 8, GLFW_WINDOW) != GL_TRUE) { CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window.")); glfwTerminate(); } } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::setGLFWAppConfiguration() { glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application"); //Deactivate VSYNC glfwSwapInterval(0); // Disable the mouse position in Non_Debug mode #ifndef DEBUG glfwDisable(GLFW_MOUSE_CURSOR); #endif // Clear Errors by GLFW, even if Setup is correct. glGetError(); } //----------------------------------------------------------------------------// <commit_msg>MOD: Minor adjustment of glfw window creation params<commit_after>/*********************************************************************** filename: CEGuiGLFWSharedBase.cpp created: 12/2/2012 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # include <unistd.h> #endif #include "CEGUISamplesConfig.h" #include "CEGuiGLFWSharedBase.h" #include "SamplesFrameworkBase.h" #include "CEGUI/CEGUI.h" #include <stdexcept> #include <sstream> //----------------------------------------------------------------------------// CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0; double CEGuiGLFWSharedBase::d_frameTime = 0; int CEGuiGLFWSharedBase::d_modifiers = 0; bool CEGuiGLFWSharedBase::d_windowSized = false; int CEGuiGLFWSharedBase::d_newWindowWidth; int CEGuiGLFWSharedBase::d_newWindowHeight; //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::CEGuiGLFWSharedBase() { if (d_appInstance) throw CEGUI::InvalidRequestException( "CEGuiGLFWSharedBase instance already exists!"); d_appInstance = this; } //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase() { } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::run() { d_sampleApp->initialise(); // Input callbacks of glfw for CEGUI glfwSetKeyCallback(glfwKeyCallback); glfwSetCharCallback(glfwCharCallback); glfwSetMouseButtonCallback(glfwMouseButtonCallback); glfwSetMouseWheelCallback(glfwMouseWheelCallback); glfwSetMousePosCallback(glfwMousePosCallback); //Window callbacks glfwSetWindowSizeCallback(glfwWindowResizeCallback); d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set starting time d_frameTime = glfwGetTime(); while (!d_sampleApp->isQuitting() && glfwGetWindowParam(GLFW_OPENED)) { if (d_windowSized) { d_windowSized = false; CEGUI::System::getSingleton(). notifyDisplaySizeChanged( CEGUI::Sizef(static_cast<float>(d_newWindowWidth), static_cast<float>(d_newWindowHeight))); } drawFrame(); } d_sampleApp->deinitialise(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::destroyWindow() { glfwTerminate(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/) { glClear(GL_COLOR_BUFFER_BIT); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::endRendering() { glfwSwapBuffers(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::drawFrame() { // calculate time elapsed since last frame double time_now = glfwGetTime(); const double elapsed = time_now - d_frameTime; d_frameTime = time_now; d_appInstance->renderSingleFrame(static_cast<float>(elapsed)); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h) { // We cache this in order to minimise calls to notifyDisplaySizeChanged, // which happens in the main loop whenever d_windowSized is set to true. d_windowSized = true; d_newWindowWidth = w; d_newWindowHeight = h; } //----------------------------------------------------------------------------// CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey) { switch(glfwKey) { case GLFW_KEY_ESC : return CEGUI::Key::Escape; case GLFW_KEY_F1 : return CEGUI::Key::F1; case GLFW_KEY_F2 : return CEGUI::Key::F2; case GLFW_KEY_F3 : return CEGUI::Key::F3; case GLFW_KEY_F4 : return CEGUI::Key::F4; case GLFW_KEY_F5 : return CEGUI::Key::F5; case GLFW_KEY_F6 : return CEGUI::Key::F6; case GLFW_KEY_F7 : return CEGUI::Key::F7; case GLFW_KEY_F8 : return CEGUI::Key::F8; case GLFW_KEY_F9 : return CEGUI::Key::F9; case GLFW_KEY_F10 : return CEGUI::Key::F10; case GLFW_KEY_F11 : return CEGUI::Key::F11; case GLFW_KEY_F12 : return CEGUI::Key::F12; case GLFW_KEY_F13 : return CEGUI::Key::F13; case GLFW_KEY_F14 : return CEGUI::Key::F14; case GLFW_KEY_F15 : return CEGUI::Key::F15; case GLFW_KEY_UP : return CEGUI::Key::ArrowUp; case GLFW_KEY_DOWN : return CEGUI::Key::ArrowDown; case GLFW_KEY_LEFT : return CEGUI::Key::ArrowLeft; case GLFW_KEY_RIGHT : return CEGUI::Key::ArrowRight; case GLFW_KEY_LSHIFT : return CEGUI::Key::LeftShift; case GLFW_KEY_RSHIFT : return CEGUI::Key::RightShift; case GLFW_KEY_LCTRL : return CEGUI::Key::LeftControl; case GLFW_KEY_RCTRL : return CEGUI::Key::RightControl; case GLFW_KEY_LALT : return CEGUI::Key::LeftAlt; case GLFW_KEY_RALT : return CEGUI::Key::RightAlt; case GLFW_KEY_TAB : return CEGUI::Key::Tab; case GLFW_KEY_ENTER : return CEGUI::Key::Return; case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace; case GLFW_KEY_INSERT : return CEGUI::Key::Insert; case GLFW_KEY_DEL : return CEGUI::Key::Delete; case GLFW_KEY_PAGEUP : return CEGUI::Key::PageUp; case GLFW_KEY_PAGEDOWN : return CEGUI::Key::PageDown; case GLFW_KEY_HOME : return CEGUI::Key::Home; case GLFW_KEY_END : return CEGUI::Key::End; case GLFW_KEY_KP_ENTER : return CEGUI::Key::NumpadEnter; case GLFW_KEY_SPACE : return CEGUI::Key::Space; case 'A' : return CEGUI::Key::A; case 'B' : return CEGUI::Key::B; case 'C' : return CEGUI::Key::C; case 'D' : return CEGUI::Key::D; case 'E' : return CEGUI::Key::E; case 'F' : return CEGUI::Key::F; case 'G' : return CEGUI::Key::G; case 'H' : return CEGUI::Key::H; case 'I' : return CEGUI::Key::I; case 'J' : return CEGUI::Key::J; case 'K' : return CEGUI::Key::K; case 'L' : return CEGUI::Key::L; case 'M' : return CEGUI::Key::M; case 'N' : return CEGUI::Key::N; case 'O' : return CEGUI::Key::O; case 'P' : return CEGUI::Key::P; case 'Q' : return CEGUI::Key::Q; case 'R' : return CEGUI::Key::R; case 'S' : return CEGUI::Key::S; case 'T' : return CEGUI::Key::T; case 'U' : return CEGUI::Key::U; case 'V' : return CEGUI::Key::V; case 'W' : return CEGUI::Key::W; case 'X' : return CEGUI::Key::X; case 'Y' : return CEGUI::Key::Y; case 'Z' : return CEGUI::Key::Z; default : return CEGUI::Key::Unknown; } } //----------------------------------------------------------------------------// CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton) { switch(glfwButton) { case GLFW_MOUSE_BUTTON_LEFT : return CEGUI::LeftButton; case GLFW_MOUSE_BUTTON_RIGHT : return CEGUI::RightButton; case GLFW_MOUSE_BUTTON_MIDDLE : return CEGUI::MiddleButton; default : return CEGUI::NoButton; } } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action) { CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key); if(action == GLFW_PRESS) d_sampleApp->injectKeyDown(ceguiKey); else if (action == GLFW_RELEASE) d_sampleApp->injectKeyUp(ceguiKey); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action) { if(action == GLFW_PRESS) d_sampleApp->injectChar(character); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action) { CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key); if(action == GLFW_PRESS) d_sampleApp->injectMouseButtonDown(ceguiMouseButton); else if (action == GLFW_RELEASE) d_sampleApp->injectMouseButtonUp(ceguiMouseButton); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position) { static int lastPosition = 0; d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition)); lastPosition = position; } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y) { d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y)); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::initGLFW() { if(!glfwInit()) CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW.")); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::createGLFWWindow() { if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 8, 8, 8, 0, 24, 0, GLFW_WINDOW) != GL_TRUE) { CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window.")); glfwTerminate(); } } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::setGLFWAppConfiguration() { glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application"); //Deactivate VSYNC glfwSwapInterval(0); // Disable the mouse position in Non_Debug mode #ifndef DEBUG glfwDisable(GLFW_MOUSE_CURSOR); #endif // Clear Errors by GLFW, even if Setup is correct. glGetError(); } //----------------------------------------------------------------------------// <|endoftext|>
<commit_before>/** * \file * \brief SignalsCatcherControlBlock class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-10 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ namespace distortos { namespace synchronization { /// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals class SignalsCatcherControlBlock { }; } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ <commit_msg>SignalsCatcherControlBlock: add constexpr constructor<commit_after>/** * \file * \brief SignalsCatcherControlBlock class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-16 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ namespace distortos { namespace synchronization { /// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals class SignalsCatcherControlBlock { public: /** * \brief SignalsCatcherControlBlock's constructor */ constexpr SignalsCatcherControlBlock() { } }; } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <ctime> #include <iostream> #include <iterator> #include <nix/util/util.hpp> #include "BaseTestEntity.hpp" #include <cppunit/extensions/HelperMacros.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> using namespace std; using namespace nix; void BaseTestEntity::testId() { CPPUNIT_ASSERT(block.id().size() == 36); CPPUNIT_ASSERT(util::toId(block).compare(block.id()) == 0); } void BaseTestEntity::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); CPPUNIT_ASSERT(util::toName(block).compare(block.name()) == 0); } void BaseTestEntity::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void BaseTestEntity::testDefinition() { string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); block.definition(nix::none); CPPUNIT_ASSERT(block.definition() == nix::none); } void BaseTestEntity::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void BaseTestEntity::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); } void BaseTestEntity::testIsValidEntity() { CPPUNIT_ASSERT(block.isValidEntity()); Source s = block.createSource("test", "test"); CPPUNIT_ASSERT(s.isValidEntity()); block.deleteSource(s.name()); CPPUNIT_ASSERT(!s.isValidEntity()); } <commit_msg>[file_backend/TestEntity] enable file_backend tests for Entity<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <ctime> #include <iostream> #include <iterator> #include <nix/util/util.hpp> #include "BaseTestEntity.hpp" #include <cppunit/extensions/HelperMacros.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> using namespace std; using namespace nix; void BaseTestEntity::testId() { CPPUNIT_ASSERT(block.id().size() == 36); CPPUNIT_ASSERT(util::toId(block).compare(block.id()) == 0); } void BaseTestEntity::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); CPPUNIT_ASSERT(util::toName(block).compare(block.name()) == 0); } void BaseTestEntity::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void BaseTestEntity::testDefinition() { string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); block.definition(nix::none); CPPUNIT_ASSERT(block.definition() == nix::none); } void BaseTestEntity::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void BaseTestEntity::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); CPPUNIT_ASSERT(block_fs.updatedAt() >= startup_time); } void BaseTestEntity::testIsValidEntity() { CPPUNIT_ASSERT(block.isValidEntity()); Source s = block.createSource("test", "test"); CPPUNIT_ASSERT(s.isValidEntity()); block.deleteSource(s.name()); CPPUNIT_ASSERT(!s.isValidEntity()); } void TestEntity::testOperators() { CPPUNIT_ASSERT(null == false); CPPUNIT_ASSERT(null == none); CPPUNIT_ASSERT(block != false); CPPUNIT_ASSERT(block != none); CPPUNIT_ASSERT(block == block); CPPUNIT_ASSERT(block != block_other); block_other = block; CPPUNIT_ASSERT(block_other == block); } <|endoftext|>
<commit_before>#include "ValueViewerTable.h" #include "CCAPI/Common.h" #include "CCAPI/Helpers.h" #include <iostream> #include <fstream> #include <FL/fl_draw.H> #include <FL/Fl_Widget.H> #include "ui_main.h" using namespace std; #define ADDRESS_COL 0 #define VALUE_COL 1 #define HEX_COL 2 #define VALUE_COLS 3 ValueViewerTable::ValueViewerTable(int X, int Y, int W, int H, const char *l) : Fl_Table_Row(X,Y,W,H,l) { m_operator = 0; m_selectedType = SEARCH_VALUE_TYPE_1BYTE; rkWindow::addObject(this); rows(DEFAULT_ROWS); row_header(0); row_height_all(25); row_resize(0); cols(VALUE_COLS); col_header(1); col_width_all(110); col_width(VALUE_COL, 250); col_resize(1); viewer = 0; m_codeTable = 0; m_startAddress = m_focusAddress = 0; m_signed = false; type(SELECT_MULTI); end(); callback(tableClickedCB); Fl::add_timeout(0.5, redraw, this); } void ValueViewerTable::redraw(void *v) { ValueViewerTable *t = (ValueViewerTable *)v; t->damage(FL_DAMAGE_ALL); Fl::repeat_timeout(1.0, ValueViewerTable::redraw, v); } void ValueViewerTable::addSelectedAddresses() { if (m_codeTable == 0 || !hasSelection()) return; for (int i=0; i<rows(); ++i) { if (i > DEFAULT_ROWS) break; if (row_selected(i)) m_codeTable->addEntry("Value Viewer Entry", m_startAddress+i, 0, m_selectedType); } } bool ValueViewerTable::hasSelection() { int t,b,l,r; get_selection(t,l,b,r); return (t > -1 && b > -1); } void ValueViewerTable::draw_cell(TableContext context, int ROW, int COL, int X, int Y, int W, int H){ static char s[40]; int x,y,w,h; switch ( context ) { case CONTEXT_STARTPAGE: // before page is drawn.. fl_font(FL_HELVETICA, 14); // set the font for our drawing operations return; case CONTEXT_RC_RESIZE: { int X, Y, W, H; int index = 0; for ( int r = 0; r<rows(); r++ ) { for ( int c = 0; c<cols(); c++ ) { if ( index >= children() ) break; find_cell(CONTEXT_TABLE, r, c, X, Y, W, H); child(index)->resize(X,Y,W,H); index++; } } init_sizes(); // tell group children resized return; } case CONTEXT_COL_HEADER: // Draw column headers switch (COL) { case ADDRESS_COL: DrawHeader("Address",X,Y,W,H); break; case VALUE_COL: DrawHeader("Value",X,Y,W,H); break; case HEX_COL: DrawHeader("Hex",X,Y,W,H); break; default: break; } return; case CONTEXT_ROW_HEADER: // Draw row headers fl_font(FL_HELVETICA, 14); // set the font for our drawing operations sprintf(s,"%03d:",COL); // "001:", "002:", etc DrawHeader(s,X,Y,W,H); return; case CONTEXT_CELL: // Draw data in cells if (ROW > DEFAULT_ROWS) break; fl_font(FL_HELVETICA, 14); // set the font for our drawing operations fl_push_clip(X, Y, W, H); { // BG COLOR if (ROW == (m_focusAddress - m_startAddress) ) fl_color( row_selected(ROW) ? selection_color() : FL_GREEN); else fl_color( row_selected(ROW) ? selection_color() : FL_WHITE); fl_rectf(X, Y, W, H); // TEXT fl_color(FL_BLACK); if ((unsigned int)ROW < DEFAULT_ROWS) { unsigned long tmpLong = BSWAP32(*(unsigned long*)(&m_memory[ROW])); unsigned short tmpShort = BSWAP16(*(unsigned short*)(&m_memory[ROW])); switch(COL) { case ADDRESS_COL: sprintf(s,"0x%08X",m_startAddress+ROW); break; case VALUE_COL: switch (m_selectedType) { case SEARCH_VALUE_TYPE_FLOAT: sprintf(s,"%f", *(float*)(&tmpLong) ); break; case SEARCH_VALUE_TYPE_1BYTE: if (m_signed) sprintf(s,"%hd", (char)m_memory[ROW]); else sprintf(s,"%hu", (unsigned char)m_memory[ROW]); break; case SEARCH_VALUE_TYPE_2BYTE: if (m_signed) sprintf(s,"%hd", (short) tmpShort); else sprintf(s,"%hu", (unsigned short) tmpShort); break; default: if (m_signed) sprintf(s,"%d", (long) tmpLong); else sprintf(s,"%u", (unsigned long) tmpLong); break; } break; case HEX_COL: switch (m_selectedType) { case SEARCH_VALUE_TYPE_FLOAT: sprintf(s,"%X", tmpLong); break; case SEARCH_VALUE_TYPE_1BYTE: sprintf(s,"%X", m_memory[ROW]); break; case SEARCH_VALUE_TYPE_2BYTE: sprintf(s,"%X", tmpShort); break; default: sprintf(s,"%X", tmpLong); break; } break; default: break; } DrawData(s,X,Y,W,H); } // BORDER fl_color(FL_LIGHT2); fl_rect(X, Y, W, H); } fl_pop_clip(); return; default: return; } } int ValueViewerTable::handle(int evt) { int res = 0; when(FL_WHEN_NEVER); res = Fl_Table_Row::handle(evt); return res; } void ValueViewerTable::DrawData(const char *s, int X, int Y, int W, int H) { fl_push_clip(X,Y,W,H); // Draw cell bg //fl_color(FL_WHITE); fl_rectf(X,Y,W,H); // Draw cell data fl_color(FL_GRAY0); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER); // Draw box border fl_color(color()); fl_rect(X,Y,W,H); fl_pop_clip(); } void ValueViewerTable::DrawHeader(const char *s, int X, int Y, int W, int H) { fl_push_clip(X,Y,W,H); fl_draw_box(FL_THIN_UP_BOX, X,Y,W,H, row_header_color()); fl_color(FL_BLACK); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER); fl_pop_clip(); } void ValueViewerTable::onCellDoubleClicked(int row, int col) { #if 0 long long int_val; if (data[row].sign) int_val = (signed long)data[row]->value; else int_val = (unsigned long) data[row]->value; unsigned long address = data[row]->address; char hex[50]; float float_val = *(float*)&data[row]->value; switch (col) { case DESC_COL: current_cell_widget = data[row]->widget->description; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->description->show(); data[row]->widget->description->value(data[row]->description.c_str()); data[row]->widget->description->take_focus(); } last_cell_widget = current_cell_widget; break; case ADDRESS_COL: //address current_cell_widget = data[row]->widget->address_input; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->address_input->show(); sprintf(hex, "%.8X", address); data[row]->widget->address_input->value(hex); data[row]->widget->address_input->take_focus(); } last_cell_widget = current_cell_widget; break; case VALUE_COL: //input current_cell_widget = data[row]->widget->value_input; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->value_input->show(); data[row]->widget->value_input->take_focus(); if (data[row]->type == SEARCH_VALUE_TYPE_FLOAT) data[row]->widget->value_input->value(to_string(float_val).c_str()); else { switch (data[row]->type) { case SEARCH_VALUE_TYPE_1BYTE: data[row]->widget->value_input->value(data[row]->sign ? to_string((char)int_val).c_str() : to_string((unsigned char)int_val).c_str()); break; case SEARCH_VALUE_TYPE_2BYTE: data[row]->widget->value_input->value(data[row]->sign ? to_string((short)int_val).c_str() : to_string((unsigned short)int_val).c_str()); break; default: data[row]->widget->value_input->value(data[row]->sign ? to_string((long)int_val).c_str() : to_string((unsigned long)int_val).c_str()); break; } } } last_cell_widget = current_cell_widget; break; case TYPE_COL: //type current_cell_widget = data[row]->widget->type; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->type->show(); data[row]->widget->type->take_focus(); } last_cell_widget = current_cell_widget; break; case FREEZE_COL: //freeze current_cell_widget = data[row]->widget->freeze; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->freeze->take_focus(); } last_cell_widget = 0; break; } #endif } void ValueViewerTable::onCellRightClicked(int row, int col) { #if 0 const Fl_Menu_Item *m = 0; if (col == ADDRESS_COL) { Fl_Menu_Item rclick_menu[] = { { "View Nearby...", 0, viewer, (void*)this }, { 0 } }; m = rclick_menu->popup(Fl::event_x(), Fl::event_y(), 0, 0, 0); //if ( m ) m->do_callback(0, m->user_data()); if ( m ) m->do_callback(0, data[row].get()); } #endif } void ValueViewerTable::onTableClicked() { } void ValueViewerTable::doDeactivate() { //if (!Fl::event_inside(this->parent())) // select_all_rows(0); } void ValueViewerTable::setMemoryOperator(MemoryOperator *op) { m_operator = op; } void ValueViewerTable::startMemoryRead() { if (m_operator == 0) return; m_startAddress = 0; if ((long long)m_focusAddress - (DEFAULT_ROWS/2) < 0) m_startAddress = 0; else if ((long long)m_focusAddress + (DEFAULT_ROWS/2) > 0xFFFFFFFF) m_startAddress = 0xFFFFFFFF - (DEFAULT_ROWS/2); else m_startAddress = m_focusAddress - (DEFAULT_ROWS/2); m_operator->setChunkReadMemoryOperation(m_startAddress, DEFAULT_ROWS+3, m_memory, true); row_position(m_focusAddress - m_startAddress); } void ValueViewerTable::stopMemoryRead() { if (m_operator == 0) return; m_operator->removeMemoryOperation(MEMORY_COMMAND_READCHUNK, m_startAddress); } <commit_msg>fixed issue with 1 byte hex values.<commit_after>#include "ValueViewerTable.h" #include "CCAPI/Common.h" #include "CCAPI/Helpers.h" #include <iostream> #include <fstream> #include <FL/fl_draw.H> #include <FL/Fl_Widget.H> #include "ui_main.h" using namespace std; #define ADDRESS_COL 0 #define VALUE_COL 1 #define HEX_COL 2 #define VALUE_COLS 3 ValueViewerTable::ValueViewerTable(int X, int Y, int W, int H, const char *l) : Fl_Table_Row(X,Y,W,H,l) { m_operator = 0; m_selectedType = SEARCH_VALUE_TYPE_1BYTE; rkWindow::addObject(this); rows(DEFAULT_ROWS); row_header(0); row_height_all(25); row_resize(0); cols(VALUE_COLS); col_header(1); col_width_all(110); col_width(VALUE_COL, 250); col_resize(1); viewer = 0; m_codeTable = 0; m_startAddress = m_focusAddress = 0; m_signed = false; type(SELECT_MULTI); end(); callback(tableClickedCB); Fl::add_timeout(0.5, redraw, this); } void ValueViewerTable::redraw(void *v) { ValueViewerTable *t = (ValueViewerTable *)v; t->damage(FL_DAMAGE_ALL); Fl::repeat_timeout(1.0, ValueViewerTable::redraw, v); } void ValueViewerTable::addSelectedAddresses() { if (m_codeTable == 0 || !hasSelection()) return; for (int i=0; i<rows(); ++i) { if (i > DEFAULT_ROWS) break; if (row_selected(i)) m_codeTable->addEntry("Value Viewer Entry", m_startAddress+i, 0, m_selectedType); } } bool ValueViewerTable::hasSelection() { int t,b,l,r; get_selection(t,l,b,r); return (t > -1 && b > -1); } void ValueViewerTable::draw_cell(TableContext context, int ROW, int COL, int X, int Y, int W, int H){ static char s[40]; int x,y,w,h; switch ( context ) { case CONTEXT_STARTPAGE: // before page is drawn.. fl_font(FL_HELVETICA, 14); // set the font for our drawing operations return; case CONTEXT_RC_RESIZE: { int X, Y, W, H; int index = 0; for ( int r = 0; r<rows(); r++ ) { for ( int c = 0; c<cols(); c++ ) { if ( index >= children() ) break; find_cell(CONTEXT_TABLE, r, c, X, Y, W, H); child(index)->resize(X,Y,W,H); index++; } } init_sizes(); // tell group children resized return; } case CONTEXT_COL_HEADER: // Draw column headers switch (COL) { case ADDRESS_COL: DrawHeader("Address",X,Y,W,H); break; case VALUE_COL: DrawHeader("Value",X,Y,W,H); break; case HEX_COL: DrawHeader("Hex",X,Y,W,H); break; default: break; } return; case CONTEXT_ROW_HEADER: // Draw row headers fl_font(FL_HELVETICA, 14); // set the font for our drawing operations sprintf(s,"%03d:",COL); // "001:", "002:", etc DrawHeader(s,X,Y,W,H); return; case CONTEXT_CELL: // Draw data in cells if (ROW > DEFAULT_ROWS) break; fl_font(FL_HELVETICA, 14); // set the font for our drawing operations fl_push_clip(X, Y, W, H); { // BG COLOR if (ROW == (m_focusAddress - m_startAddress) ) fl_color( row_selected(ROW) ? selection_color() : FL_GREEN); else fl_color( row_selected(ROW) ? selection_color() : FL_WHITE); fl_rectf(X, Y, W, H); // TEXT fl_color(FL_BLACK); if ((unsigned int)ROW < DEFAULT_ROWS) { unsigned long tmpLong = BSWAP32(*(unsigned long*)(&m_memory[ROW])); unsigned short tmpShort = BSWAP16(*(unsigned short*)(&m_memory[ROW])); switch(COL) { case ADDRESS_COL: sprintf(s,"0x%08X",m_startAddress+ROW); break; case VALUE_COL: switch (m_selectedType) { case SEARCH_VALUE_TYPE_FLOAT: sprintf(s,"%f", *(float*)(&tmpLong) ); break; case SEARCH_VALUE_TYPE_1BYTE: if (m_signed) sprintf(s,"%hd", (char)m_memory[ROW]); else sprintf(s,"%hu", (unsigned char)m_memory[ROW]); break; case SEARCH_VALUE_TYPE_2BYTE: if (m_signed) sprintf(s,"%hd", (short) tmpShort); else sprintf(s,"%hu", (unsigned short) tmpShort); break; default: if (m_signed) sprintf(s,"%d", (long) tmpLong); else sprintf(s,"%u", (unsigned long) tmpLong); break; } break; case HEX_COL: switch (m_selectedType) { case SEARCH_VALUE_TYPE_FLOAT: sprintf(s,"%X", tmpLong); break; case SEARCH_VALUE_TYPE_1BYTE: sprintf(s,"%X", (unsigned char)m_memory[ROW]); break; case SEARCH_VALUE_TYPE_2BYTE: sprintf(s,"%X", tmpShort); break; default: sprintf(s,"%X", tmpLong); break; } break; default: break; } DrawData(s,X,Y,W,H); } // BORDER fl_color(FL_LIGHT2); fl_rect(X, Y, W, H); } fl_pop_clip(); return; default: return; } } int ValueViewerTable::handle(int evt) { int res = 0; when(FL_WHEN_NEVER); res = Fl_Table_Row::handle(evt); return res; } void ValueViewerTable::DrawData(const char *s, int X, int Y, int W, int H) { fl_push_clip(X,Y,W,H); // Draw cell bg //fl_color(FL_WHITE); fl_rectf(X,Y,W,H); // Draw cell data fl_color(FL_GRAY0); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER); // Draw box border fl_color(color()); fl_rect(X,Y,W,H); fl_pop_clip(); } void ValueViewerTable::DrawHeader(const char *s, int X, int Y, int W, int H) { fl_push_clip(X,Y,W,H); fl_draw_box(FL_THIN_UP_BOX, X,Y,W,H, row_header_color()); fl_color(FL_BLACK); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER); fl_pop_clip(); } void ValueViewerTable::onCellDoubleClicked(int row, int col) { #if 0 long long int_val; if (data[row].sign) int_val = (signed long)data[row]->value; else int_val = (unsigned long) data[row]->value; unsigned long address = data[row]->address; char hex[50]; float float_val = *(float*)&data[row]->value; switch (col) { case DESC_COL: current_cell_widget = data[row]->widget->description; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->description->show(); data[row]->widget->description->value(data[row]->description.c_str()); data[row]->widget->description->take_focus(); } last_cell_widget = current_cell_widget; break; case ADDRESS_COL: //address current_cell_widget = data[row]->widget->address_input; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->address_input->show(); sprintf(hex, "%.8X", address); data[row]->widget->address_input->value(hex); data[row]->widget->address_input->take_focus(); } last_cell_widget = current_cell_widget; break; case VALUE_COL: //input current_cell_widget = data[row]->widget->value_input; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->value_input->show(); data[row]->widget->value_input->take_focus(); if (data[row]->type == SEARCH_VALUE_TYPE_FLOAT) data[row]->widget->value_input->value(to_string(float_val).c_str()); else { switch (data[row]->type) { case SEARCH_VALUE_TYPE_1BYTE: data[row]->widget->value_input->value(data[row]->sign ? to_string((char)int_val).c_str() : to_string((unsigned char)int_val).c_str()); break; case SEARCH_VALUE_TYPE_2BYTE: data[row]->widget->value_input->value(data[row]->sign ? to_string((short)int_val).c_str() : to_string((unsigned short)int_val).c_str()); break; default: data[row]->widget->value_input->value(data[row]->sign ? to_string((long)int_val).c_str() : to_string((unsigned long)int_val).c_str()); break; } } } last_cell_widget = current_cell_widget; break; case TYPE_COL: //type current_cell_widget = data[row]->widget->type; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->type->show(); data[row]->widget->type->take_focus(); } last_cell_widget = current_cell_widget; break; case FREEZE_COL: //freeze current_cell_widget = data[row]->widget->freeze; if (current_cell_widget != last_cell_widget) //click on a new widget { if (last_cell_widget) last_cell_widget->hide(); data[row]->widget->freeze->take_focus(); } last_cell_widget = 0; break; } #endif } void ValueViewerTable::onCellRightClicked(int row, int col) { #if 0 const Fl_Menu_Item *m = 0; if (col == ADDRESS_COL) { Fl_Menu_Item rclick_menu[] = { { "View Nearby...", 0, viewer, (void*)this }, { 0 } }; m = rclick_menu->popup(Fl::event_x(), Fl::event_y(), 0, 0, 0); //if ( m ) m->do_callback(0, m->user_data()); if ( m ) m->do_callback(0, data[row].get()); } #endif } void ValueViewerTable::onTableClicked() { } void ValueViewerTable::doDeactivate() { //if (!Fl::event_inside(this->parent())) // select_all_rows(0); } void ValueViewerTable::setMemoryOperator(MemoryOperator *op) { m_operator = op; } void ValueViewerTable::startMemoryRead() { if (m_operator == 0) return; m_startAddress = 0; if ((long long)m_focusAddress - (DEFAULT_ROWS/2) < 0) m_startAddress = 0; else if ((long long)m_focusAddress + (DEFAULT_ROWS/2) > 0xFFFFFFFF) m_startAddress = 0xFFFFFFFF - (DEFAULT_ROWS/2); else m_startAddress = m_focusAddress - (DEFAULT_ROWS/2); m_operator->setChunkReadMemoryOperation(m_startAddress, DEFAULT_ROWS+3, m_memory, true); row_position(m_focusAddress - m_startAddress); } void ValueViewerTable::stopMemoryRead() { if (m_operator == 0) return; m_operator->removeMemoryOperation(MEMORY_COMMAND_READCHUNK, m_startAddress); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2016 ETH Zurich ** 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 ETH Zurich 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 HOLDER 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 "SpecialCases.h" #include "ExportHelpers.h" #include "CodeComposite.h" #include "visitors/CppPrintContext.h" #include "visitors/DeclarationVisitor.h" #include "visitors/ExpressionVisitor.h" #include "visitors/ElementVisitor.h" #include "visitors/StatementVisitor.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/TypeAlias.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "OOModel/src/expressions/MetaCallExpression.h" #include "OOModel/src/expressions/BooleanLiteral.h" #include "OOModel/src/expressions/ReferenceExpression.h" namespace CppExport { void SpecialCases::handleQT_Flags(OOModel::Class* classs, Export::CompositeFragment* fragment) { auto specialCaseFragment = fragment->append(new Export::CompositeFragment{classs}); for (auto subDeclaration : *classs->subDeclarations()) if (auto typeAlias = DCast<OOModel::TypeAlias>(subDeclaration)) if (auto reference = DCast<OOModel::ReferenceExpression>(typeAlias->typeExpression())) if (reference->name() == "QFlags") *specialCaseFragment << "Q_DECLARE_OPERATORS_FOR_FLAGS(" << classs->name() << "::" << typeAlias->name() << ")"; } bool SpecialCases::isTestClass(OOModel::Class* classs) { if (!classs) return false; return classs->methods()->size() == 1 && (classs->methods()->first()->name() == "test" || classs->methods()->first()->name() == "init"); } void SpecialCases::overrideFlag(OOModel::Method* method, Export::CompositeFragment* fragment) { for (auto expression : *method->metaCalls()) if (auto metaCall = DCast<OOModel::MetaCallExpression>(expression)) if (auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee())) if (reference->name() == "SET_OVERRIDE_FLAG") { *fragment << " OVERRIDE"; return; } } Export::CompositeFragment* SpecialCases::overrideFlagArgumentTransformation(OOModel::MetaCallExpression* metaCall) { Export::CompositeFragment* fragment{}; if (auto metaDefinition = metaCall->metaDefinition()) if (metaDefinition->arguments()->size() == 1 && metaCall->arguments()->size() == 1) if (metaDefinition->arguments()->first()->name() == "OVERRIDE") if (auto booleanLiteral = DCast<OOModel::BooleanLiteral>(metaCall->arguments()->first())) { fragment = new Export::CompositeFragment{metaCall->arguments(), "argsList"}; *fragment << (booleanLiteral->value() ? "override" : ""); } return fragment; } bool SpecialCases::hasTemplatePrefixArgument(OOModel::MetaDefinition* metaDefinition) { for (auto argument : *metaDefinition->arguments()) if (argument->name() == "templatePrefix") return true; return false; } bool SpecialCases::isMainMethod(OOModel::Method* method) { return method && method->symbolName() == "main"; } bool SpecialCases::isTemplateArgumentNameOnlyDependency(OOModel::ReferenceExpression* parentReference, OOModel::ReferenceExpression*) { return parentReference->name() == "unique_ptr" || parentReference->name() == "shared_ptr"; } Export::SourceFragment* SpecialCases::printXMacroDataBlock(OOModel::MetaCallExpression* metaCall) { auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee()); Q_ASSERT(reference->name().startsWith("BEGIN_")); auto fragment = new Export::CompositeFragment{metaCall, "sections"}; auto beginCallFragment = fragment->append(new Export::CompositeFragment{metaCall}); *beginCallFragment << reference->name(); auto argumentsFragment = beginCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"}); CppPrintContext printContext{nullptr}; for (auto i = 0; i < metaCall->arguments()->size() - 1; i++) if (auto expression = DCast<OOModel::Expression>(metaCall->arguments()->at(i))) *argumentsFragment << ExpressionVisitor{printContext}.visit(expression); else Q_ASSERT(false); Q_ASSERT(metaCall->arguments()->size() > 0); auto childMetaCallsList = DCast<Model::List>(metaCall->arguments()->last()); auto childMetaCallsFragment = fragment->append(new Export::CompositeFragment{childMetaCallsList, "bodyNoBraces"}); Q_ASSERT(childMetaCallsList); for (auto childMetaCallCandidate : *childMetaCallsList) { auto childMetaCall = DCast<OOModel::MetaCallExpression>(childMetaCallCandidate); Q_ASSERT(childMetaCall); *childMetaCallsFragment << ExpressionVisitor{printContext}.visit(childMetaCall); } *fragment << "END_STANDARD_EXPRESSION_VISUALIZATION"; return fragment; } Export::CompositeFragment* SpecialCases::printPartialBeginMacroSpecialization(OOModel::MetaDefinition* metaDefinition, bool isHeaderFile) { Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && metaDefinition->metaBindings()->isEmpty()); auto macro = new Export::CompositeFragment{metaDefinition, "macro"}; auto fragment = macro->append(new Export::CompositeFragment{metaDefinition, "sections"}); auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition}); *metaDefinitionFragment << "#define " << metaDefinition->name(); auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(), "argsList"}); CppPrintContext printContext{nullptr}; for (auto i = 0; i < metaDefinition->arguments()->size() - 1; i++) *argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i)); if (auto metaCall = DCast<OOModel::MetaCallExpression>(metaDefinition->context()->metaCalls()->first())) { auto metaCallFragment = fragment->append(new Export::CompositeFragment{metaCall}); *metaCallFragment << ExpressionVisitor{printContext}.visit(metaCall->callee()); auto argumentsFragment = metaCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"}); for (auto i = 0; i < metaCall->arguments()->size() - (isHeaderFile ? 2 : 3); i++) if (auto argument = DCast<OOModel::Expression>(metaCall->arguments()->at(i))) *argumentsFragment << ExpressionVisitor{printContext}.visit(argument); if (!isHeaderFile) { Q_ASSERT(metaCall->arguments()->size() > 0); auto statementList = DCast<Model::List>(metaCall->arguments()->at(metaCall->arguments()->size() - 2)); Q_ASSERT(statementList); auto statementListFragment = fragment->append(new Export::CompositeFragment{statementList, "bodyNoBraces"}); for (auto statementCandidate : *statementList) if (auto statement = DCast<OOModel::StatementItem>(statementCandidate)) *statementListFragment << StatementVisitor{printContext}.visit(statement); else Q_ASSERT(false); } } else Q_ASSERT(false); return macro; } Export::CompositeFragment* SpecialCases::printPartialBeginMacroBase(OOModel::MetaDefinition* metaDefinition, bool isHeaderFile) { Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && !metaDefinition->metaBindings()->isEmpty()); auto fragment = new Export::CompositeFragment{metaDefinition, "macro"}; auto context = DCast<OOModel::Module>(metaDefinition->context()); auto classs = context->classes()->first(); CppPrintContext printContext{isHeaderFile ? classs : nullptr, isHeaderFile ? CppPrintContext::IsHeaderPart : CppPrintContext::None | CppPrintContext::XMacro}; auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition}); *metaDefinitionFragment << "#define " << metaDefinition->name(); auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(), "argsList"}); for (auto i = 0; i < metaDefinition->arguments()->size() - (isHeaderFile ? 2 : 3); i++) *argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i)); *metaDefinitionFragment << "\n"; *fragment << DeclarationVisitor{printContext}.visit(classs); return fragment; } Export::SourceFragment* SpecialCases::includeXMacroData(CodeComposite* codeComposite, Export::SourceFragment* baseFragment, bool isSourceFile) { auto fragment = new Export::CompositeFragment{baseFragment->node(), "sections"}; *fragment << baseFragment << "\n" << "namespace OOVisualization {" << "#include \"" + XMACRO_DATA_FILENAME + ".h\"" << "}"; for (auto unit : codeComposite->units()) if (auto metaDefinition = DCast<OOModel::MetaDefinition>(unit->node())) if (metaDefinition->name().startsWith("BEGIN_") || (metaDefinition->name().endsWith("_CPP") == isSourceFile)) *fragment << "#undef " + ExportHelpers::strip_CPPFromName(metaDefinition); return fragment; } } <commit_msg>use additional formatting fragments to avoid manual newline printing<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2016 ETH Zurich ** 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 ETH Zurich 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 HOLDER 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 "SpecialCases.h" #include "ExportHelpers.h" #include "CodeComposite.h" #include "visitors/CppPrintContext.h" #include "visitors/DeclarationVisitor.h" #include "visitors/ExpressionVisitor.h" #include "visitors/ElementVisitor.h" #include "visitors/StatementVisitor.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/TypeAlias.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "OOModel/src/expressions/MetaCallExpression.h" #include "OOModel/src/expressions/BooleanLiteral.h" #include "OOModel/src/expressions/ReferenceExpression.h" namespace CppExport { void SpecialCases::handleQT_Flags(OOModel::Class* classs, Export::CompositeFragment* fragment) { auto specialCaseFragment = fragment->append(new Export::CompositeFragment{classs}); for (auto subDeclaration : *classs->subDeclarations()) if (auto typeAlias = DCast<OOModel::TypeAlias>(subDeclaration)) if (auto reference = DCast<OOModel::ReferenceExpression>(typeAlias->typeExpression())) if (reference->name() == "QFlags") *specialCaseFragment << "Q_DECLARE_OPERATORS_FOR_FLAGS(" << classs->name() << "::" << typeAlias->name() << ")"; } bool SpecialCases::isTestClass(OOModel::Class* classs) { if (!classs) return false; return classs->methods()->size() == 1 && (classs->methods()->first()->name() == "test" || classs->methods()->first()->name() == "init"); } void SpecialCases::overrideFlag(OOModel::Method* method, Export::CompositeFragment* fragment) { for (auto expression : *method->metaCalls()) if (auto metaCall = DCast<OOModel::MetaCallExpression>(expression)) if (auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee())) if (reference->name() == "SET_OVERRIDE_FLAG") { *fragment << " OVERRIDE"; return; } } Export::CompositeFragment* SpecialCases::overrideFlagArgumentTransformation(OOModel::MetaCallExpression* metaCall) { Export::CompositeFragment* fragment{}; if (auto metaDefinition = metaCall->metaDefinition()) if (metaDefinition->arguments()->size() == 1 && metaCall->arguments()->size() == 1) if (metaDefinition->arguments()->first()->name() == "OVERRIDE") if (auto booleanLiteral = DCast<OOModel::BooleanLiteral>(metaCall->arguments()->first())) { fragment = new Export::CompositeFragment{metaCall->arguments(), "argsList"}; *fragment << (booleanLiteral->value() ? "override" : ""); } return fragment; } bool SpecialCases::hasTemplatePrefixArgument(OOModel::MetaDefinition* metaDefinition) { for (auto argument : *metaDefinition->arguments()) if (argument->name() == "templatePrefix") return true; return false; } bool SpecialCases::isMainMethod(OOModel::Method* method) { return method && method->symbolName() == "main"; } bool SpecialCases::isTemplateArgumentNameOnlyDependency(OOModel::ReferenceExpression* parentReference, OOModel::ReferenceExpression*) { return parentReference->name() == "unique_ptr" || parentReference->name() == "shared_ptr"; } Export::SourceFragment* SpecialCases::printXMacroDataBlock(OOModel::MetaCallExpression* metaCall) { auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee()); Q_ASSERT(reference->name().startsWith("BEGIN_")); auto fragment = new Export::CompositeFragment{metaCall, "sections"}; auto beginCallFragment = fragment->append(new Export::CompositeFragment{metaCall}); *beginCallFragment << reference->name(); auto argumentsFragment = beginCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"}); CppPrintContext printContext{nullptr}; for (auto i = 0; i < metaCall->arguments()->size() - 1; i++) if (auto expression = DCast<OOModel::Expression>(metaCall->arguments()->at(i))) *argumentsFragment << ExpressionVisitor{printContext}.visit(expression); else Q_ASSERT(false); Q_ASSERT(metaCall->arguments()->size() > 0); auto childMetaCallsList = DCast<Model::List>(metaCall->arguments()->last()); auto childMetaCallsFragment = fragment->append(new Export::CompositeFragment{childMetaCallsList, "bodyNoBraces"}); Q_ASSERT(childMetaCallsList); for (auto childMetaCallCandidate : *childMetaCallsList) { auto childMetaCall = DCast<OOModel::MetaCallExpression>(childMetaCallCandidate); Q_ASSERT(childMetaCall); *childMetaCallsFragment << ExpressionVisitor{printContext}.visit(childMetaCall); } *fragment << "END_STANDARD_EXPRESSION_VISUALIZATION"; return fragment; } Export::CompositeFragment* SpecialCases::printPartialBeginMacroSpecialization(OOModel::MetaDefinition* metaDefinition, bool isHeaderFile) { Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && metaDefinition->metaBindings()->isEmpty()); auto macro = new Export::CompositeFragment{metaDefinition, "macro"}; auto fragment = macro->append(new Export::CompositeFragment{metaDefinition, "sections"}); auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition}); *metaDefinitionFragment << "#define " << metaDefinition->name(); auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(), "argsList"}); CppPrintContext printContext{nullptr}; for (auto i = 0; i < metaDefinition->arguments()->size() - 1; i++) *argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i)); if (auto metaCall = DCast<OOModel::MetaCallExpression>(metaDefinition->context()->metaCalls()->first())) { auto metaCallFragment = fragment->append(new Export::CompositeFragment{metaCall}); *metaCallFragment << ExpressionVisitor{printContext}.visit(metaCall->callee()); auto argumentsFragment = metaCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"}); for (auto i = 0; i < metaCall->arguments()->size() - (isHeaderFile ? 2 : 3); i++) if (auto argument = DCast<OOModel::Expression>(metaCall->arguments()->at(i))) *argumentsFragment << ExpressionVisitor{printContext}.visit(argument); if (!isHeaderFile) { Q_ASSERT(metaCall->arguments()->size() > 0); auto statementList = DCast<Model::List>(metaCall->arguments()->at(metaCall->arguments()->size() - 2)); Q_ASSERT(statementList); auto statementListFragment = fragment->append(new Export::CompositeFragment{statementList, "bodyNoBraces"}); for (auto statementCandidate : *statementList) if (auto statement = DCast<OOModel::StatementItem>(statementCandidate)) *statementListFragment << StatementVisitor{printContext}.visit(statement); else Q_ASSERT(false); } } else Q_ASSERT(false); return macro; } Export::CompositeFragment* SpecialCases::printPartialBeginMacroBase(OOModel::MetaDefinition* metaDefinition, bool isHeaderFile) { Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && !metaDefinition->metaBindings()->isEmpty()); auto fragment = new Export::CompositeFragment{metaDefinition, "macro"}; auto macroFragment = fragment->append(new Export::CompositeFragment{metaDefinition, "sections"}); auto context = DCast<OOModel::Module>(metaDefinition->context()); auto classs = context->classes()->first(); CppPrintContext printContext{isHeaderFile ? classs : nullptr, isHeaderFile ? CppPrintContext::IsHeaderPart : CppPrintContext::None | CppPrintContext::XMacro}; auto metaDefinitionFragment = macroFragment->append(new Export::CompositeFragment{metaDefinition}); *metaDefinitionFragment << "#define " << metaDefinition->name(); auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(), "argsList"}); for (auto i = 0; i < metaDefinition->arguments()->size() - (isHeaderFile ? 2 : 3); i++) *argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i)); *macroFragment << DeclarationVisitor{printContext}.visit(classs); return fragment; } Export::SourceFragment* SpecialCases::includeXMacroData(CodeComposite* codeComposite, Export::SourceFragment* baseFragment, bool isSourceFile) { auto dataInclusionFragment = new Export::CompositeFragment{baseFragment->node(), "sections"}; *dataInclusionFragment << "namespace OOVisualization {" << "#include \"" + XMACRO_DATA_FILENAME + ".h\"" << "}"; auto fragment = new Export::CompositeFragment{baseFragment->node(), "spacedSections"}; *fragment << baseFragment << dataInclusionFragment; for (auto unit : codeComposite->units()) if (auto metaDefinition = DCast<OOModel::MetaDefinition>(unit->node())) if (metaDefinition->name().startsWith("BEGIN_") || (metaDefinition->name().endsWith("_CPP") == isSourceFile)) *fragment << "#undef " + ExportHelpers::strip_CPPFromName(metaDefinition); return fragment; } } <|endoftext|>
<commit_before>// MsOfficeDocumentInformation.h: Schnittstelle f�r die Klasse MsOfficeDocumentInformation. // ////////////////////////////////////////////////////////////////////// #ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_ #define _REGISTRATIONCONTEXTINFORMATION_HXX_ #pragma warning(push, 1) /* disable warnings within system headers */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <msi.h> #pragma warning(pop) #include <string> /** A simple implementation class that returns the appropriate display names for the Microsoft Office document types. Under Windows 9x this class checks if the document display name is convertable to an ANSI string and if not returns an english default. So we avoid garbage if soemone for instance installs an japanese StarOffice/OpenOffice under a German Windows 98 for instance. */ class RegistrationContextInformation { public: enum SHELL_COMMAND {New, Open, Print, Printto}; enum OFFICE_APPLICATION {Office, Writer, Calc, Impress}; RegistrationContextInformation(MSIHANDLE hMsi, const std::wstring& OpenOfficeExecutablePath); /** Word document information The icon index is the index of the icon in soffice.exe to be associated with word document files */ std::wstring GetWordDocumentDisplayName() const; std::wstring GetWordDocumentFileExtension() const; std::wstring GetWordDocumentDefaultIconEntry() const; std::wstring GetWordDocumentDefaultShellCommand() const; /** Word template information The icon index is the index of the icon in soffice.exe to be associated with word template files */ std::wstring GetWordTemplateDisplayName() const; std::wstring GetWordTemplateFileExtension() const; std::wstring GetWordTemplateDefaultIconEntry() const; std::wstring GetWordTemplateDefaultShellCommand() const; /** Rtf document information The icon index is the index of the icon in soffice.exe to be associated with rtf document files */ std::wstring GetRtfDocumentDisplayName() const; std::wstring GetRtfDocumentFileExtension() const; std::wstring GetRtfDocumentDefaultIconEntry() const; std::wstring GetRtfDocumentDefaultShellCommand() const; /** Excel sheet information The icon index is the index of the icon in soffice.exe to be associated with Excel sheets */ std::wstring GetExcelSheetDisplayName() const; std::wstring GetExcelSheetFileExtension() const; std::wstring GetExcelSheetDefaultIconEntry() const; std::wstring GetExcelSheetDefaultShellCommand() const; /** Excel template information The icon index is the index of the icon in soffice.exe to be associated with Excel template files */ std::wstring GetExcelTemplateDisplayName() const; std::wstring GetExcelTemplateFileExtension() const; std::wstring GetExcelTemplateDefaultIconEntry() const; std::wstring GetExcelTemplateDefaultShellCommand() const; /** PowerPoint document information The icon index is the index of the icon in soffice.exe to be associated with PowerPoint document files */ std::wstring GetPowerPointDocumentDisplayName() const; std::wstring GetPowerPointDocumentFileExtension() const; std::wstring GetPowerPointDocumentDefaultIconEntry() const; std::wstring GetPowerPointDocumentDefaultShellCommand() const; /** PowerPoint template information The icon index is the index of the icon in soffice.exe to be associated with PowerPoint template files */ std::wstring GetPowerPointTemplateDisplayName() const; std::wstring GetPowerPointTemplateFileExtension() const; std::wstring GetPowerPointTemplateDefaultIconEntry() const; std::wstring GetPowerPointTemplateDefaultShellCommand() const; /** PowerPoint Show information */ std::wstring GetPowerPointShowDisplayName() const; std::wstring GetPowerPointShowFileExtension() const; std::wstring GetPowerPointShowDefaultIconEntry() const; std::wstring GetPowerPointShowDefaultShellCommand() const; /** The string for the "New" command that should appear in the Explorer context menu when someone right clicks a Microsoft document */ std::wstring ShellNewCommandDisplayName() const; /** The string for the "Edit" command that should appear in the Explorer context menu when someone right clicks a document */ std::wstring ShellEditCommandDisplayName() const; /** A friendly name for the application */ std::wstring GetOpenOfficeFriendlyAppName() const; /** The path to the StarOffice/OpenOffice executable */ std::wstring GetOpenOfficeExecutablePath() const; /** The name of the executable (currently "soffice.exe" but may change in the future, who knows) */ std::wstring GetOpenOfficeExecutableName() const; /** A command line for the specified shell command */ std::wstring GetOpenOfficeCommandline(SHELL_COMMAND ShellCommand, OFFICE_APPLICATION OfficeApp) const; private: bool IsConvertableToAnsi(const std::wstring& String) const; void ExtractOpenOfficeExecNameFromPath(); private: MSIHANDLE msihandle_; bool m_IsWin9x; std::wstring m_OOExecPath; std::wstring m_OOExecName; }; #endif <commit_msg>INTEGRATION: CWS mingwport06 (1.3.44); FILE MERGED 2007/08/24 13:12:57 vg 1.3.44.1: #i75499# pragma is for MSVC<commit_after>// MsOfficeDocumentInformation.h: Schnittstelle f�r die Klasse MsOfficeDocumentInformation. // ////////////////////////////////////////////////////////////////////// #ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_ #define _REGISTRATIONCONTEXTINFORMATION_HXX_ #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <msi.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> /** A simple implementation class that returns the appropriate display names for the Microsoft Office document types. Under Windows 9x this class checks if the document display name is convertable to an ANSI string and if not returns an english default. So we avoid garbage if soemone for instance installs an japanese StarOffice/OpenOffice under a German Windows 98 for instance. */ class RegistrationContextInformation { public: enum SHELL_COMMAND {New, Open, Print, Printto}; enum OFFICE_APPLICATION {Office, Writer, Calc, Impress}; RegistrationContextInformation(MSIHANDLE hMsi, const std::wstring& OpenOfficeExecutablePath); /** Word document information The icon index is the index of the icon in soffice.exe to be associated with word document files */ std::wstring GetWordDocumentDisplayName() const; std::wstring GetWordDocumentFileExtension() const; std::wstring GetWordDocumentDefaultIconEntry() const; std::wstring GetWordDocumentDefaultShellCommand() const; /** Word template information The icon index is the index of the icon in soffice.exe to be associated with word template files */ std::wstring GetWordTemplateDisplayName() const; std::wstring GetWordTemplateFileExtension() const; std::wstring GetWordTemplateDefaultIconEntry() const; std::wstring GetWordTemplateDefaultShellCommand() const; /** Rtf document information The icon index is the index of the icon in soffice.exe to be associated with rtf document files */ std::wstring GetRtfDocumentDisplayName() const; std::wstring GetRtfDocumentFileExtension() const; std::wstring GetRtfDocumentDefaultIconEntry() const; std::wstring GetRtfDocumentDefaultShellCommand() const; /** Excel sheet information The icon index is the index of the icon in soffice.exe to be associated with Excel sheets */ std::wstring GetExcelSheetDisplayName() const; std::wstring GetExcelSheetFileExtension() const; std::wstring GetExcelSheetDefaultIconEntry() const; std::wstring GetExcelSheetDefaultShellCommand() const; /** Excel template information The icon index is the index of the icon in soffice.exe to be associated with Excel template files */ std::wstring GetExcelTemplateDisplayName() const; std::wstring GetExcelTemplateFileExtension() const; std::wstring GetExcelTemplateDefaultIconEntry() const; std::wstring GetExcelTemplateDefaultShellCommand() const; /** PowerPoint document information The icon index is the index of the icon in soffice.exe to be associated with PowerPoint document files */ std::wstring GetPowerPointDocumentDisplayName() const; std::wstring GetPowerPointDocumentFileExtension() const; std::wstring GetPowerPointDocumentDefaultIconEntry() const; std::wstring GetPowerPointDocumentDefaultShellCommand() const; /** PowerPoint template information The icon index is the index of the icon in soffice.exe to be associated with PowerPoint template files */ std::wstring GetPowerPointTemplateDisplayName() const; std::wstring GetPowerPointTemplateFileExtension() const; std::wstring GetPowerPointTemplateDefaultIconEntry() const; std::wstring GetPowerPointTemplateDefaultShellCommand() const; /** PowerPoint Show information */ std::wstring GetPowerPointShowDisplayName() const; std::wstring GetPowerPointShowFileExtension() const; std::wstring GetPowerPointShowDefaultIconEntry() const; std::wstring GetPowerPointShowDefaultShellCommand() const; /** The string for the "New" command that should appear in the Explorer context menu when someone right clicks a Microsoft document */ std::wstring ShellNewCommandDisplayName() const; /** The string for the "Edit" command that should appear in the Explorer context menu when someone right clicks a document */ std::wstring ShellEditCommandDisplayName() const; /** A friendly name for the application */ std::wstring GetOpenOfficeFriendlyAppName() const; /** The path to the StarOffice/OpenOffice executable */ std::wstring GetOpenOfficeExecutablePath() const; /** The name of the executable (currently "soffice.exe" but may change in the future, who knows) */ std::wstring GetOpenOfficeExecutableName() const; /** A command line for the specified shell command */ std::wstring GetOpenOfficeCommandline(SHELL_COMMAND ShellCommand, OFFICE_APPLICATION OfficeApp) const; private: bool IsConvertableToAnsi(const std::wstring& String) const; void ExtractOpenOfficeExecNameFromPath(); private: MSIHANDLE msihandle_; bool m_IsWin9x; std::wstring m_OOExecPath; std::wstring m_OOExecName; }; #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP #define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/rev/fun/typedefs.hpp> #include <tbb/task_arena.h> #include <tbb/parallel_reduce.h> #include <tbb/blocked_range.h> #include <iostream> #include <iterator> #include <vector> namespace stan { namespace math { namespace internal { template <typename ReduceFunction, typename ReturnType, typename M, typename... Args> struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M, Args...> { struct recursive_reducer { size_t num_terms_; const std::vector<M>& vmapped_; std::tuple<const Args&...> args_tuple_; double sum_; Eigen::VectorXd args_adjoints_; recursive_reducer(size_t num_terms, const std::vector<M>& vmapped, const Args&... args) : num_terms_(num_terms), vmapped_(vmapped), args_tuple_(args...), sum_(0.0), args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {} recursive_reducer(recursive_reducer& other, tbb::split) : num_terms_(other.num_terms_), vmapped_(other.vmapped_), args_tuple_(other.args_tuple_), sum_(other.sum_), args_adjoints_(other.args_adjoints_) {} template <typename T> T& deep_copy(T& arg) { return arg; } var deep_copy(const var& arg) { return var(arg.val()); } std::vector<var> deep_copy(const std::vector<var>& arg) { std::vector<var> copy(arg.size()); for (size_t i = 0; i < arg.size(); ++i) { copy[i] = arg[i].val(); } return copy; } template <int RowType, int ColType> Eigen::Matrix<var, RowType, ColType> deep_copy( const Eigen::Matrix<var, RowType, ColType>& arg) { Eigen::Matrix<var, RowType, ColType> copy(arg.size()); for (size_t i = 0; i < arg.size(); ++i) { copy(i) = arg(i).val(); } return copy; } template <typename... Pargs> void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) { *dest += x.adj(); accumulate_adjoints(dest + 1, args...); } // Works with anything that has operator[Integral] defined template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...> void accumulate_adjoints(double* dest, const Vec& x, const Pargs&... args) { for (size_t i = 0; i < x.size(); ++i) { dest[i] += x[i].adj(); } accumulate_adjoints(dest + x.size(), args...); } // Fails to compile if type T does not have member operator(Integral) template <typename T> using operator_paren_access_t = decltype(std::declval<T>()(int{})); // Works on anything with a operator() template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>..., require_t<is_var<value_type_t<Mat>>>...> void accumulate_adjoints(double* dest, const Mat& x, const Pargs&... args) { for (size_t i = 0; i < x.size(); ++i) { dest[i] += x(i).adj(); } accumulate_adjoints(dest + x.size(), args...); } // Anything with a scalar type of Arithmetic gets tossed template <typename Arith, require_arithmetic_t<scalar_type_t<Arith>>..., typename... Pargs> void accumulate_adjoints(double* dest, Arith&& x, const Pargs&... args) { accumulate_adjoints(dest, args...); } void accumulate_adjoints(double*) {} void operator()(const tbb::blocked_range<size_t>& r) { if (r.empty()) return; auto start = vmapped_.begin(); std::advance(start, r.begin()); auto end = vmapped_.begin(); std::advance(end, r.end()); const std::vector<M> sub_slice(start, end); try { start_nested(); // create a deep copy of all var's so that these are not // linked to any outer AD tree auto args_tuple_local_copy = apply( [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); }, args_tuple_); var sub_sum_v = apply( [&](auto&&... args) { return ReduceFunction()(r.begin(), r.end() - 1, sub_slice, args...); }, args_tuple_local_copy); sub_sum_v.grad(); sum_ += sub_sum_v.val(); // This should accumulate the adjoints from args_tuple_local_copy into // the memory of args_adjoints_ apply( [&](auto&&... args) { accumulate_adjoints(args_adjoints_.data(), args...); }, args_tuple_local_copy); } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } void join(const recursive_reducer& rhs) { sum_ += rhs.sum_; args_adjoints_ += rhs.args_adjoints_; } }; // Fails to compile if type T does not have callable member size() template <typename T> using member_size_t = decltype(std::declval<T>().size()); // TODO(Steve): add requires for generic containers template <typename Container, require_t<is_detected<Container, member_size_t>>..., require_t<is_var<value_type_t<Container>>>..., typename... Pargs> size_t count_var_impl(size_t count, const Container& x, const Pargs&... args) const { return count_var_impl(count + x.size(), args...); } template <typename Container, require_t<is_detected<Container, member_size_t>>..., require_t<std::is_arithmetic<value_type_t<Container>>>..., typename... Pargs> size_t count_var_impl(size_t count, const Container& x, const Pargs&... args) const { return count_var_impl(count, args...); } template <typename... Pargs> size_t count_var_impl(size_t count, const var& x, const Pargs&... args) const { return count_var_impl(count + 1, args...); } template <typename... Pargs, typename Arith, require_arithmetic_t<scalar_type_t<Arith>>...> size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const { return count_var_impl(count, args...); } size_t count_var_impl(size_t count) const { return count; } /** * Count the number of scalars of type T in the input argument list * * @tparam Pargs Types of input arguments * @return Number of scalars of type T in input */ template <typename... Pargs> size_t count_var(const Pargs&... args) const { return count_var_impl(0, args...); } template <typename... Pargs> void save_varis(vari** dest, const var& x, const Pargs&... args) const { *dest = x.vi_; save_varis(dest + 1, args...); } template <typename... Pargs> void save_varis(vari** dest, const std::vector<var>& x, const Pargs&... args) const { for (size_t i = 0; i < x.size(); ++i) { dest[i] = x[i].vi_; } save_varis(dest + x.size(), args...); } template <typename... Pargs, int RowType, int ColType> void save_varis(vari** dest, const Eigen::Matrix<var, RowType, ColType>& x, const Pargs&... args) const { for (size_t i = 0; i < x.size(); ++i) { dest[i] = x(i).vi_; } save_varis(dest + x.size(), args...); } template <typename R, typename... Pargs> void save_varis(vari** dest, const R& x, const Pargs&... args) const { save_varis(dest, args...); } void save_varis(vari**) const {} var operator()(const std::vector<M>& vmapped, std::size_t grainsize, const Args&... args) const { const std::size_t num_jobs = vmapped.size(); if (num_jobs == 0) return var(0.0); const std::size_t num_terms = count_var(args...); recursive_reducer worker(num_terms, vmapped, args...); #ifdef STAN_DETERMINISTIC tbb::static_partitioner partitioner; tbb::parallel_deterministic_reduce( tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker, partitioner); #else tbb::parallel_reduce( tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker); #endif vari** varis = ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms); double* partials = ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms); save_varis(varis, args...); for (size_t i = 0; i < num_terms; ++i) { partials[i] = worker.args_adjoints_(i); } return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis, partials)); } }; } // namespace internal } // namespace math } // namespace stan #endif <commit_msg>move operator_paren checker out one scope<commit_after>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP #define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/rev/fun/typedefs.hpp> #include <tbb/task_arena.h> #include <tbb/parallel_reduce.h> #include <tbb/blocked_range.h> #include <iostream> #include <iterator> #include <vector> namespace stan { namespace math { namespace internal { template <typename ReduceFunction, typename ReturnType, typename M, typename... Args> struct reduce_sum_impl<ReduceFunction, require_var_t<ReturnType>, ReturnType, M, Args...> { // TODO(Steve): Move this somewhere smarter // Fails to compile if type T does not have member operator(Integral) template <typename T> using operator_paren_access_t = decltype(std::declval<T>()(int{})); struct recursive_reducer { size_t num_terms_; const std::vector<M>& vmapped_; std::tuple<const Args&...> args_tuple_; double sum_; Eigen::VectorXd args_adjoints_; recursive_reducer(size_t num_terms, const std::vector<M>& vmapped, const Args&... args) : num_terms_(num_terms), vmapped_(vmapped), args_tuple_(args...), sum_(0.0), args_adjoints_(Eigen::VectorXd::Zero(num_terms)) {} recursive_reducer(recursive_reducer& other, tbb::split) : num_terms_(other.num_terms_), vmapped_(other.vmapped_), args_tuple_(other.args_tuple_), sum_(other.sum_), args_adjoints_(other.args_adjoints_) {} template <typename T> T& deep_copy(T& arg) { return arg; } var deep_copy(const var& arg) { return var(arg.val()); } std::vector<var> deep_copy(const std::vector<var>& arg) { std::vector<var> copy(arg.size()); for (size_t i = 0; i < arg.size(); ++i) { copy[i] = arg[i].val(); } return copy; } template <int RowType, int ColType> Eigen::Matrix<var, RowType, ColType> deep_copy( const Eigen::Matrix<var, RowType, ColType>& arg) { Eigen::Matrix<var, RowType, ColType> copy(arg.size()); for (size_t i = 0; i < arg.size(); ++i) { copy(i) = arg(i).val(); } return copy; } template <typename... Pargs> void accumulate_adjoints(double* dest, const var& x, const Pargs&... args) { *dest += x.adj(); accumulate_adjoints(dest + 1, args...); } // Works with anything that has operator[Integral] defined template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...> void accumulate_adjoints(double* dest, const Vec& x, const Pargs&... args) { for (size_t i = 0; i < x.size(); ++i) { dest[i] += x[i].adj(); } accumulate_adjoints(dest + x.size(), args...); } // Works on anything with a operator() template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>..., require_t<is_var<value_type_t<Mat>>>...> void accumulate_adjoints(double* dest, const Mat& x, const Pargs&... args) { for (size_t i = 0; i < x.size(); ++i) { dest[i] += x(i).adj(); } accumulate_adjoints(dest + x.size(), args...); } // Anything with a scalar type of Arithmetic gets tossed template <typename Arith, require_arithmetic_t<scalar_type_t<Arith>>..., typename... Pargs> void accumulate_adjoints(double* dest, Arith&& x, const Pargs&... args) { accumulate_adjoints(dest, args...); } void accumulate_adjoints(double*) {} void operator()(const tbb::blocked_range<size_t>& r) { if (r.empty()) return; auto start = vmapped_.begin(); std::advance(start, r.begin()); auto end = vmapped_.begin(); std::advance(end, r.end()); const std::vector<M> sub_slice(start, end); try { start_nested(); // create a deep copy of all var's so that these are not // linked to any outer AD tree auto args_tuple_local_copy = apply( [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); }, args_tuple_); var sub_sum_v = apply( [&](auto&&... args) { return ReduceFunction()(r.begin(), r.end() - 1, sub_slice, args...); }, args_tuple_local_copy); sub_sum_v.grad(); sum_ += sub_sum_v.val(); // This should accumulate the adjoints from args_tuple_local_copy into // the memory of args_adjoints_ apply( [&](auto&&... args) { accumulate_adjoints(args_adjoints_.data(), args...); }, args_tuple_local_copy); } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } void join(const recursive_reducer& rhs) { sum_ += rhs.sum_; args_adjoints_ += rhs.args_adjoints_; } }; // Fails to compile if type T does not have callable member size() template <typename T> using member_size_t = decltype(std::declval<T>().size()); // TODO(Steve): add requires for generic containers template <typename Container, require_t<is_detected<Container, member_size_t>>..., require_t<is_var<value_type_t<Container>>>..., typename... Pargs> size_t count_var_impl(size_t count, const Container& x, const Pargs&... args) const { return count_var_impl(count + x.size(), args...); } template <typename Container, require_t<is_detected<Container, member_size_t>>..., require_t<std::is_arithmetic<value_type_t<Container>>>..., typename... Pargs> size_t count_var_impl(size_t count, const Container& x, const Pargs&... args) const { return count_var_impl(count, args...); } template <typename... Pargs> size_t count_var_impl(size_t count, const var& x, const Pargs&... args) const { return count_var_impl(count + 1, args...); } template <typename... Pargs, typename Arith, require_arithmetic_t<scalar_type_t<Arith>>...> size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const { return count_var_impl(count, args...); } size_t count_var_impl(size_t count) const { return count; } /** * Count the number of scalars of type T in the input argument list * * @tparam Pargs Types of input arguments * @return Number of scalars of type T in input */ template <typename... Pargs> size_t count_var(const Pargs&... args) const { return count_var_impl(0, args...); } template <typename... Pargs> void save_varis(vari** dest, const var& x, const Pargs&... args) const { *dest = x.vi_; save_varis(dest + 1, args...); } template <typename... Pargs, typename Vec, require_vector_like_vt<is_var, Vec>...> void save_varis(vari** dest, const Vec& x, const Pargs&... args) const { for (size_t i = 0; i < x.size(); ++i) { dest[i] = x[i].vi_; } save_varis(dest + x.size(), args...); } template <typename... Pargs, typename Mat, require_t<is_detected<Mat, operator_paren_access_t>>..., require_t<is_var<value_type_t<Mat>>>...> void save_varis(vari** dest, const Mat& x, const Pargs&... args) const { for (size_t i = 0; i < x.size(); ++i) { dest[i] = x(i).vi_; } save_varis(dest + x.size(), args...); } template <typename R, typename... Pargs> void save_varis(vari** dest, const R& x, const Pargs&... args) const { save_varis(dest, args...); } void save_varis(vari**) const {} var operator()(const std::vector<M>& vmapped, std::size_t grainsize, const Args&... args) const { const std::size_t num_jobs = vmapped.size(); if (num_jobs == 0) return var(0.0); const std::size_t num_terms = count_var(args...); recursive_reducer worker(num_terms, vmapped, args...); #ifdef STAN_DETERMINISTIC tbb::static_partitioner partitioner; tbb::parallel_deterministic_reduce( tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker, partitioner); #else tbb::parallel_reduce( tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker); #endif vari** varis = ChainableStack::instance_->memalloc_.alloc_array<vari*>(num_terms); double* partials = ChainableStack::instance_->memalloc_.alloc_array<double>(num_terms); save_varis(varis, args...); for (size_t i = 0; i < num_terms; ++i) { partials[i] = worker.args_adjoints_(i); } return var(new precomputed_gradients_vari(worker.sum_, num_terms, varis, partials)); } }; } // namespace internal } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/******************************* Copyright (C) 2013-2015 gregoire ANGERAND This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 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, see <http://www.gnu.org/licenses/>. **********************************/ #include "ToneMapRenderer.h" #include "ShaderCombinaison.h" #include "VertexArrayObject.h" #include <n/utils.h> namespace n { namespace graphics { const Material &getMaterial() { static Material mat; if(mat.isNull()) { MaterialData i; i.depth = MaterialData::Always; mat = Material(i); } return mat; } ShaderCombinaison *getToneShader(bool debug = false) { static ShaderCombinaison *shaders[2] = {0, 0}; if(!shaders[debug]) { static core::String deb[2] = {"", "\n#define DEBUG\n"}; shaders[debug] = new ShaderCombinaison(new Shader<FragmentShader>( deb[debug] + "uniform sampler2D n_0;" "uniform sampler2D n_1;" "uniform float logMin;" "uniform float logMax;" "uniform float exposure;" "uniform float white;" "in vec2 n_TexCoord;" "out vec4 n_Out;" "float rgbLum(vec3 rgb) {" "return dot(vec3(0.299, 0.587, 0.114), rgb);" "}" "float clampLum(float l) {" "return clamp(l, logMin, logMax);" "}" "vec3 reinhard(vec3 col, float exp, float key, float w) {" "float cL = rgbLum(col);" "float lum = cL * exp / key;" "float W = 1 + lum / sqr(w);" "lum *= W / (lum + 1);" "return col * lum / cL;" "}" "vec3 gamma(vec3 col) {" "return pow(col, vec3(1.0 / 2.2));" "}" "void main() {" "vec2 offset = 0.5 / textureSize(n_1, 0);" "vec4 avgLum4 = textureGather(n_1, offset, 0);" "float avgLum = exp(clampLum((avgLum4.x + avgLum4.y + avgLum4.z + avgLum4.w) * 0.25));" "vec4 color = texture(n_0, n_TexCoord);" "vec3 rein = reinhard(color.rgb, exposure, avgLum, white);" "n_Out = vec4(rein, color.a);" "\n#ifdef DEBUG\n" "if(color.x > 1 || color.y > 1 || color.z > 1) { n_Out = vec4(1, 0, 0, 1); }" "if(n_TexCoord.x < 0.1 && n_TexCoord.y > 0.9) { n_Out = vec4(avgLum); }" "if(n_TexCoord.x > 0.5) { n_Out = color; }" "\n#endif\n" "}"), ShaderProgram::NoProjectionShader); } return shaders[debug]; } ShaderCombinaison *getLogShader() { static ShaderCombinaison *shader = 0; if(!shader) { shader = new ShaderCombinaison(new Shader<FragmentShader>( "uniform sampler2D n_0;" "in vec2 n_TexCoord;" "out float n_Out;" "float rgbLum(vec3 rgb) {" "return dot(vec3(0.299, 0.587, 0.114), rgb);" "}" "const float epsilon = 0.0001;" "void main() {" "vec4 color = texture(n_0, n_TexCoord);" "float lum = rgbLum(color.rgb);" "n_Out = log(epsilon + lum);" "}"), ShaderProgram::NoProjectionShader); } return shader; } ShaderCombinaison *getDSShader() { static ShaderCombinaison *shader = 0; if(!shader) { shader = new ShaderCombinaison(new Shader<FragmentShader>( "uniform sampler2D n_0;" "in vec2 n_TexCoord;" "out float n_Out;" "uniform float scale;" "vec2 rescale(vec2 tex) {" "tex *= scale;" "vec2 h = vec2(0); (0.5 / textureSize(n_0, 0));" "return tex * (1.0 - 2 * h) + h;" "}" "void main() {" "vec4 avgLum = textureGather(n_0, rescale(n_TexCoord), 0);" //"vec4 maxLum = textureGather(n_0, rescale(n_TexCoord), 1);" "n_Out.x = (avgLum.x + avgLum.y + avgLum.z + avgLum.w) * 0.25;" //"n_Out.y = max(max(maxLum.x, maxLum.y), max(maxLum.z, maxLum.w));" "}"), new Shader<VertexShader>( "layout(location = 0) in vec3 n_VertexPosition;" "layout(location = 3) in vec2 n_VertexCoord;" "uniform float scale;" "out vec2 n_TexCoord;" "void main() {" "vec3 vp = n_VertexPosition * 0.5 + 0.5;" "vp *= 0.5 * scale;" "vp = vp * 2.0 - 1.0;" "gl_Position = vec4(vp, 1.0);" "n_TexCoord = n_VertexCoord;" "}")); } return shader; } Texture computeLum(const Texture &in, FrameBuffer *buffers[]) { ShaderCombinaison *sh = getLogShader(); sh->bind(); sh->setValue("n_0", in); buffers[0]->bind(); GLContext::getContext()->getScreen().draw(Material()); sh = getDSShader(); sh->bind(); float scale = 1.0; bool last = false; uint baseSize = buffers[0]->getSize().x(); while(baseSize != 2) { sh->setValue("n_0", buffers[last]->getAttachement(0)); sh->setValue("scale", scale); buffers[!last]->bind(); last = !last; scale *= 0.5; baseSize /= 2; GLContext::getContext()->getScreen().draw(Material()); } return buffers[last]->getAttachement(0); } ToneMapRenderer::ToneMapRenderer(BufferedRenderer *c, uint s) : BufferableRenderer(), child(c), slot(s), exposure(0.35), white(1.5), range(0.055, 10000), debug(false) { } ToneMapRenderer::~ToneMapRenderer() { } void *ToneMapRenderer::prepare() { return child->prepare(); } void ToneMapRenderer::render(void *ptr) { const FrameBuffer *fb = GLContext::getContext()->getFrameBuffer(); child->render(ptr); uint ls = core::log2ui(child->getFrameBuffer().getSize().min()); math::Vec2ui size = math::Vec2ui(1 << ls); FrameBuffer *buffers[] = {GLContext::getContext()->getFrameBufferPool().get(size, false, ImageFormat::R32F), GLContext::getContext()->getFrameBufferPool().get(size, false, ImageFormat::R32F)}; Texture lum = computeLum(child->getFrameBuffer().getAttachement(slot), buffers); if(fb) { fb->bind(); } else { FrameBuffer::unbind(); } ShaderCombinaison *sh = getToneShader(debug); sh->bind(); sh->setValue("logMin", log(range.x())); sh->setValue("logMax", log(range.y())); sh->setValue("exposure", exposure); sh->setValue("white", white); sh->setValue("n_0", child->getFrameBuffer().getAttachement(slot)); sh->setValue("n_1", lum); /*float lums[2] = { -1, -1 }; gl::glGetTextureSubImage(lum.getHandle(), 0, 0, 0, 0, 1, 1, 1, GL_RG, GL_FLOAT, 2 * sizeof(float), lums); std::cout<<lum.getHandle()<<" max = "<<lums[1]<<", avg = "<<exp(lums[0])<<std::endl;*/ GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader); GLContext::getContext()->getFrameBufferPool().add(buffers[0]); GLContext::getContext()->getFrameBufferPool().add(buffers[1]); } } } <commit_msg>Fixed tone-mapper broken by the new material pipeline.<commit_after>/******************************* Copyright (C) 2013-2015 gregoire ANGERAND This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 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, see <http://www.gnu.org/licenses/>. **********************************/ #include "ToneMapRenderer.h" #include "ShaderCombinaison.h" #include "VertexArrayObject.h" #include <n/utils.h> namespace n { namespace graphics { const Material &getMaterial() { static Material mat; if(mat.isNull()) { MaterialData i; i.depth = MaterialData::Always; mat = Material(i); } return mat; } ShaderCombinaison *getToneShader(bool debug = false) { static ShaderCombinaison *shaders[2] = {0, 0}; if(!shaders[debug]) { static core::String deb[2] = {"", "\n#define DEBUG\n"}; shaders[debug] = new ShaderCombinaison(new Shader<FragmentShader>( deb[debug] + "uniform sampler2D n_0;" "uniform sampler2D n_1;" "uniform float logMin;" "uniform float logMax;" "uniform float exposure;" "uniform float white;" "in vec2 n_TexCoord;" "out vec4 n_Out;" "float rgbLum(vec3 rgb) {" "return dot(vec3(0.299, 0.587, 0.114), rgb);" "}" "float clampLum(float l) {" "return clamp(l, logMin, logMax);" "}" "vec3 reinhard(vec3 col, float exp, float key, float w) {" "float cL = rgbLum(col);" "float lum = cL * exp / key;" "float W = 1 + lum / sqr(w);" "lum *= W / (lum + 1);" "return col * lum / cL;" "}" "vec3 gamma(vec3 col) {" "return pow(col, vec3(1.0 / 2.2));" "}" "void main() {" "vec2 offset = 0.5 / textureSize(n_1, 0);" "vec4 avgLum4 = textureGather(n_1, offset, 0);" "float avgLum = exp(clampLum((avgLum4.x + avgLum4.y + avgLum4.z + avgLum4.w) * 0.25));" "vec4 color = texture(n_0, n_TexCoord);" "vec3 rein = reinhard(color.rgb, exposure, avgLum, white);" "n_Out = vec4(rein, color.a);" "\n#ifdef DEBUG\n" "if(color.x > 1 || color.y > 1 || color.z > 1) { n_Out = vec4(1, 0, 0, 1); }" "if(n_TexCoord.x < 0.1 && n_TexCoord.y > 0.9) { n_Out = vec4(log(avgLum)); }" "if(n_TexCoord.x > 0.5) { n_Out = color; }" "\n#endif\n" "}"), ShaderProgram::NoProjectionShader); } return shaders[debug]; } ShaderCombinaison *getLogShader() { static ShaderCombinaison *shader = 0; if(!shader) { shader = new ShaderCombinaison(new Shader<FragmentShader>( "uniform sampler2D n_0;" "in vec2 n_TexCoord;" "out float n_Out;" "float rgbLum(vec3 rgb) {" "return dot(vec3(0.299, 0.587, 0.114), rgb);" "}" "const float epsilon = 0.0001;" "void main() {" "vec4 color = texture(n_0, n_TexCoord);" "float lum = rgbLum(color.rgb);" "n_Out = log(epsilon + lum);" "}"), ShaderProgram::NoProjectionShader); } return shader; } ShaderCombinaison *getDSShader() { static ShaderCombinaison *shader = 0; if(!shader) { shader = new ShaderCombinaison(new Shader<FragmentShader>( "uniform sampler2D n_0;" "in vec2 n_TexCoord;" "out float n_Out;" "uniform float scale;" "vec2 rescale(vec2 tex) {" "tex *= scale;" "vec2 h = vec2(0); (0.5 / textureSize(n_0, 0));" "return tex * (1.0 - 2 * h) + h;" "}" "void main() {" "vec4 avgLum = textureGather(n_0, rescale(n_TexCoord), 0);" //"vec4 maxLum = textureGather(n_0, rescale(n_TexCoord), 1);" "n_Out.x = (avgLum.x + avgLum.y + avgLum.z + avgLum.w) * 0.25;" //"n_Out.y = max(max(maxLum.x, maxLum.y), max(maxLum.z, maxLum.w));" "}"), new Shader<VertexShader>( "layout(location = 0) in vec3 n_VertexPosition;" "layout(location = 3) in vec2 n_VertexCoord;" "uniform float scale;" "out vec2 n_TexCoord;" "void main() {" "vec3 vp = n_VertexPosition * 0.5 + 0.5;" "vp *= 0.5 * scale;" "vp = vp * 2.0 - 1.0;" "gl_Position = vec4(vp, 1.0);" "n_TexCoord = n_VertexCoord;" "}")); } return shader; } Texture computeLum(const Texture &in, FrameBuffer *buffers[]) { ShaderCombinaison *sh = getLogShader(); sh->bind(); sh->setValue("n_0", in); buffers[0]->bind(); GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader); sh = getDSShader(); sh->bind(); float scale = 1.0; bool last = false; uint baseSize = buffers[0]->getSize().x(); while(baseSize != 2) { sh->setValue("n_0", buffers[last]->getAttachement(0)); sh->setValue("scale", scale); buffers[!last]->bind(); last = !last; scale *= 0.5; baseSize /= 2; GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader); } return buffers[last]->getAttachement(0); } ToneMapRenderer::ToneMapRenderer(BufferedRenderer *c, uint s) : BufferableRenderer(), child(c), slot(s), exposure(0.1), white(1.5), range(0.055, 10000), debug(false) { } ToneMapRenderer::~ToneMapRenderer() { } void *ToneMapRenderer::prepare() { return child->prepare(); } void ToneMapRenderer::render(void *ptr) { const FrameBuffer *fb = GLContext::getContext()->getFrameBuffer(); child->render(ptr); uint ls = core::log2ui(child->getSize().min()); math::Vec2ui size = math::Vec2ui(1 << ls); FrameBuffer *buffers[] = {GLContext::getContext()->getFrameBufferPool().get(size, false, ImageFormat::R32F), GLContext::getContext()->getFrameBufferPool().get(size, false, ImageFormat::R32F)}; Texture lum = computeLum(child->getFrameBuffer().getAttachement(slot), buffers); if(fb) { fb->bind(); } else { FrameBuffer::unbind(); } ShaderCombinaison *sh = getToneShader(debug); sh->bind(); sh->setValue("logMin", log(range.x())); sh->setValue("logMax", log(range.y())); sh->setValue("exposure", exposure); sh->setValue("white", white); sh->setValue("n_0", child->getFrameBuffer().getAttachement(slot)); sh->setValue("n_1", lum); /*float lums[2] = { -1, -1 }; gl::glGetTextureSubImage(lum.getHandle(), 0, 0, 0, 0, 1, 1, 1, GL_RG, GL_FLOAT, 2 * sizeof(float), lums); std::cout<<lum.getHandle()<<" max = "<<lums[1]<<", avg = "<<exp(lums[0])<<std::endl;*/ GLContext::getContext()->getScreen().draw(getMaterial(), VertexAttribs(), RenderFlag::NoShader); GLContext::getContext()->getFrameBufferPool().add(buffers[0]); GLContext::getContext()->getFrameBufferPool().add(buffers[1]); } } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "net/AsyncHttp.h" #include "common/StringConverter.h" #include "net/URI.h" #include "common/RhodesApp.h" #include "common/RhoAppAdapter.h" namespace rho { using namespace rho::common; namespace net { IMPLEMENT_LOGCLASS(CAsyncHttp, "AsyncHttp"); CAsyncHttp* CAsyncHttp::m_pInstance = 0; /*static*/ CAsyncHttp* CAsyncHttp::Create() { if ( m_pInstance ) return m_pInstance; m_pInstance = new CAsyncHttp( ); return m_pInstance; } /*static*/void CAsyncHttp::Destroy() { if ( m_pInstance ) delete m_pInstance; m_pInstance = 0; } CAsyncHttp::CAsyncHttp() : CThreadQueue() { CThreadQueue::setLogCategory(getLogCategory()); setPollInterval(QUEUE_POLL_INTERVAL_INFINITE); } CAsyncHttp::~CAsyncHttp(void) { stop(-1); LOG(INFO) + "Thread shutdown"; } unsigned long CAsyncHttp::addHttpCommand(IQueueCommand* pCmd) { if (((CHttpCommand*)pCmd)->m_strCallback.length()==0) { processCommandBase(pCmd); unsigned long ret = ((CHttpCommand*)pCmd)->getRetValue(); delete pCmd; return ret; } CThreadQueue::addQueueCommand(pCmd); start(epLow); return ((CHttpCommand*)pCmd)->getRetValue(); } void CAsyncHttp::cancelRequest(const char* szCallback) { if (!szCallback || !*szCallback ) { LOG(INFO) + "Cancel callback should not be empty. Use * for cancel all"; return; } synchronized(getCommandLock()); CHttpCommand* pCmd = (CHttpCommand*)getCurCommand(); if ( pCmd != null && ( *szCallback == '*' || pCmd->m_strCallback.compare(szCallback) == 0) ) pCmd->cancel(); if ( *szCallback == '*' ) getCommands().clear(); else { for (int i = getCommands().size()-1; i >= 0; i--) { CHttpCommand* pCmd1 = (CHttpCommand*)getCommands().get(i); if ( pCmd1 != null && pCmd1->m_strCallback.compare(szCallback) == 0 ) getCommands().remove(i); } } } void CAsyncHttp::processCommand(IQueueCommand* pCmd) { ((CHttpCommand*)pCmd)->execute(); } extern "C" void header_iter(const char* szName, const char* szValue, void* pHash) { ((Hashtable<String,String>*)pHash)->put(szName, szValue); } CAsyncHttp::CHttpCommand::CHttpCommand(String strCmd, rho_param *p) : m_params(p) { m_eCmd = translateCommand(strCmd); m_strCallback = m_params.getString("callback"); m_strCallbackParams = m_params.getString("callback_param"); m_params.getHash("headers", m_mapHeaders); if(m_params.has("ssl_verify_peer")) m_NetRequest.setSslVerifyPeer(m_params.getBool("ssl_verify_peer")); } void CAsyncHttp::CHttpCommand::execute() { NetResponse resp; switch( m_eCmd ) { case hcGet: resp = getNet().doRequest( m_params.getString("http_command", "GET").c_str(), m_params.getString("url"), m_params.getString("body"), null, &m_mapHeaders); break; case hcPost: resp = getNet().doRequest(m_params.getString("http_command", "POST").c_str(), m_params.getString("url"), m_params.getString("body"), null, &m_mapHeaders); break; case hcDownload: resp = getNet().pullFile(m_params.getString("url"), m_params.getString("filename"), null, &m_mapHeaders); break; case hcUpload: { VectorPtr<net::CMultipartItem*> arMultipartItems; CRhoParamArray arParams( m_params, "multipart"); if ( arParams.size() > 0 ) { for( int i = 0; i < arParams.size(); i++) { CRhoParams oItem = arParams.getItem(i); net::CMultipartItem* pItem = new net::CMultipartItem(); String strFilePath = oItem.getString("filename"); if ( strFilePath.length() == 0 ) { pItem->m_strBody = oItem.getString("body"); pItem->m_strContentType = oItem.getString("content_type", ""); } else { pItem->m_strFilePath = strFilePath; pItem->m_strContentType = oItem.getString("content_type", "application/octet-stream"); } pItem->m_strName = oItem.getString("name"); pItem->m_strFileName = oItem.getString("filename_base"); arMultipartItems.addElement(pItem); } }else { net::CMultipartItem* pItem = new net::CMultipartItem(); pItem->m_strFilePath = m_params.getString("filename"); pItem->m_strContentType = m_params.getString("file_content_type", "application/octet-stream"); pItem->m_strName = m_params.getString("name"); pItem->m_strFileName = m_params.getString("filename_base"); arMultipartItems.addElement(pItem); String strBody = m_params.getString("body"); if ( strBody.length() > 0 ) { net::CMultipartItem* pItem2 = new net::CMultipartItem(); pItem2->m_strBody = strBody; pItem2->m_strContentType = m_mapHeaders.get("content-type"); arMultipartItems.addElement(pItem2); } } resp = getNet().pushMultipartData( m_params.getString("url"), arMultipartItems, null, &m_mapHeaders ); break; } default: ; } if ( !m_NetRequest.isCancelled()) callNotify(resp,0); m_params.free_params(); } unsigned long CAsyncHttp::CHttpCommand::getRetValue() { if ( m_strCallback.length() == 0 ) { if(getLogCategory().getName() == "NO_LOGGING") return atoi(m_strResBody.c_str()); else return rho_ruby_create_string(m_strResBody.c_str()); } return rho_ruby_get_NIL(); } String CAsyncHttp::CHttpCommand::makeHeadersString() { String strRes = ""; for ( Hashtable<String,String>::iterator it = m_mapHeaders.begin(); it != m_mapHeaders.end(); ++it ) { if ( strRes.length() > 0) strRes += "&"; strRes += "headers["; URI::urlEncode(it->first,strRes); strRes += "]="; URI::urlEncode(it->second,strRes); } return strRes; } void CAsyncHttp::CHttpCommand::callNotify(NetResponse& resp, int nError ) { m_strResBody = "rho_callback=1"; m_strResBody += "&status="; if ( nError > 0 ) { m_strResBody += "error&error_code=" + nError; }else { if ( resp.isSuccess() ) { m_strResBody += "ok"; if ( resp.isResponseRecieved()) m_strResBody += "&http_error=" + convertToStringA(resp.getRespCode()); } else { m_strResBody += "error&error_code="; m_strResBody += convertToStringA(RhoAppAdapter.getErrorFromResponse(resp)); if ( resp.isResponseRecieved()) m_strResBody += "&http_error=" + convertToStringA(resp.getRespCode()); } String cookies = resp.getCookies(); if (cookies.length()>0) m_strResBody += "&cookies=" + URI::urlEncode(cookies); String strHeaders = makeHeadersString(); if (strHeaders.length() > 0 ) m_strResBody += "&" + strHeaders; m_strResBody += "&" + RHODESAPP().addCallbackObject( new CAsyncHttpResponse(resp, m_mapHeaders.get("content-type"), m_mapHeaders.get("content-encoding")), "body"); } if ( m_strCallbackParams.length() > 0 ) m_strResBody += "&" + m_strCallbackParams; if ( m_strCallback.length() > 0 ) { String strFullUrl = m_NetRequest.resolveUrl(m_strCallback); LOG(TRACE) + "Callback:" + m_strCallback + "Result body: " + m_strResBody; getNet().pushData( strFullUrl, m_strResBody, null ); } } CAsyncHttp::CAsyncHttpResponse::~CAsyncHttpResponse(){} extern "C" VALUE rjson_tokener_parse(const char *str, char** pszError ); unsigned long CAsyncHttp::CAsyncHttpResponse::getObjectValue() { if (m_NetResponse.isSuccess()) { if ( m_strContentType.find("application/json") != String::npos && m_strContentEncoding.find("gzip") == String::npos) { char* szError = 0; unsigned long valBody = rjson_tokener_parse(m_NetResponse.getCharData(), &szError); if ( valBody != 0 ) return valBody; LOG(ERROR) + "Incorrect json body.Error:" + (szError ? szError : ""); if ( szError ) free(szError); } } return rho_ruby_create_string_withlen2(m_NetResponse.getCharData(), m_NetResponse.getDataSize() ); } } // namespace net } // namespace rho extern "C" { using namespace rho::net; void rho_asynchttp_cancel(const char* cancel_callback) { if ( CAsyncHttp::getInstance() != null ) CAsyncHttp::getInstance()->cancelRequest(cancel_callback); } unsigned long rho_asynchttp_request(const char* command, rho_param *p) { CAsyncHttp::Create(); return CAsyncHttp::getInstance()->addHttpCommand(new CAsyncHttp::CHttpCommand( command, p )); } } <commit_msg>asynchttp: remove check for gzip<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "net/AsyncHttp.h" #include "common/StringConverter.h" #include "net/URI.h" #include "common/RhodesApp.h" #include "common/RhoAppAdapter.h" namespace rho { using namespace rho::common; namespace net { IMPLEMENT_LOGCLASS(CAsyncHttp, "AsyncHttp"); CAsyncHttp* CAsyncHttp::m_pInstance = 0; /*static*/ CAsyncHttp* CAsyncHttp::Create() { if ( m_pInstance ) return m_pInstance; m_pInstance = new CAsyncHttp( ); return m_pInstance; } /*static*/void CAsyncHttp::Destroy() { if ( m_pInstance ) delete m_pInstance; m_pInstance = 0; } CAsyncHttp::CAsyncHttp() : CThreadQueue() { CThreadQueue::setLogCategory(getLogCategory()); setPollInterval(QUEUE_POLL_INTERVAL_INFINITE); } CAsyncHttp::~CAsyncHttp(void) { stop(-1); LOG(INFO) + "Thread shutdown"; } unsigned long CAsyncHttp::addHttpCommand(IQueueCommand* pCmd) { if (((CHttpCommand*)pCmd)->m_strCallback.length()==0) { processCommandBase(pCmd); unsigned long ret = ((CHttpCommand*)pCmd)->getRetValue(); delete pCmd; return ret; } CThreadQueue::addQueueCommand(pCmd); start(epLow); return ((CHttpCommand*)pCmd)->getRetValue(); } void CAsyncHttp::cancelRequest(const char* szCallback) { if (!szCallback || !*szCallback ) { LOG(INFO) + "Cancel callback should not be empty. Use * for cancel all"; return; } synchronized(getCommandLock()); CHttpCommand* pCmd = (CHttpCommand*)getCurCommand(); if ( pCmd != null && ( *szCallback == '*' || pCmd->m_strCallback.compare(szCallback) == 0) ) pCmd->cancel(); if ( *szCallback == '*' ) getCommands().clear(); else { for (int i = getCommands().size()-1; i >= 0; i--) { CHttpCommand* pCmd1 = (CHttpCommand*)getCommands().get(i); if ( pCmd1 != null && pCmd1->m_strCallback.compare(szCallback) == 0 ) getCommands().remove(i); } } } void CAsyncHttp::processCommand(IQueueCommand* pCmd) { ((CHttpCommand*)pCmd)->execute(); } extern "C" void header_iter(const char* szName, const char* szValue, void* pHash) { ((Hashtable<String,String>*)pHash)->put(szName, szValue); } CAsyncHttp::CHttpCommand::CHttpCommand(String strCmd, rho_param *p) : m_params(p) { m_eCmd = translateCommand(strCmd); m_strCallback = m_params.getString("callback"); m_strCallbackParams = m_params.getString("callback_param"); m_params.getHash("headers", m_mapHeaders); if(m_params.has("ssl_verify_peer")) m_NetRequest.setSslVerifyPeer(m_params.getBool("ssl_verify_peer")); } void CAsyncHttp::CHttpCommand::execute() { NetResponse resp; switch( m_eCmd ) { case hcGet: resp = getNet().doRequest( m_params.getString("http_command", "GET").c_str(), m_params.getString("url"), m_params.getString("body"), null, &m_mapHeaders); break; case hcPost: resp = getNet().doRequest(m_params.getString("http_command", "POST").c_str(), m_params.getString("url"), m_params.getString("body"), null, &m_mapHeaders); break; case hcDownload: resp = getNet().pullFile(m_params.getString("url"), m_params.getString("filename"), null, &m_mapHeaders); break; case hcUpload: { VectorPtr<net::CMultipartItem*> arMultipartItems; CRhoParamArray arParams( m_params, "multipart"); if ( arParams.size() > 0 ) { for( int i = 0; i < arParams.size(); i++) { CRhoParams oItem = arParams.getItem(i); net::CMultipartItem* pItem = new net::CMultipartItem(); String strFilePath = oItem.getString("filename"); if ( strFilePath.length() == 0 ) { pItem->m_strBody = oItem.getString("body"); pItem->m_strContentType = oItem.getString("content_type", ""); } else { pItem->m_strFilePath = strFilePath; pItem->m_strContentType = oItem.getString("content_type", "application/octet-stream"); } pItem->m_strName = oItem.getString("name"); pItem->m_strFileName = oItem.getString("filename_base"); arMultipartItems.addElement(pItem); } }else { net::CMultipartItem* pItem = new net::CMultipartItem(); pItem->m_strFilePath = m_params.getString("filename"); pItem->m_strContentType = m_params.getString("file_content_type", "application/octet-stream"); pItem->m_strName = m_params.getString("name"); pItem->m_strFileName = m_params.getString("filename_base"); arMultipartItems.addElement(pItem); String strBody = m_params.getString("body"); if ( strBody.length() > 0 ) { net::CMultipartItem* pItem2 = new net::CMultipartItem(); pItem2->m_strBody = strBody; pItem2->m_strContentType = m_mapHeaders.get("content-type"); arMultipartItems.addElement(pItem2); } } resp = getNet().pushMultipartData( m_params.getString("url"), arMultipartItems, null, &m_mapHeaders ); break; } default: ; } if ( !m_NetRequest.isCancelled()) callNotify(resp,0); m_params.free_params(); } unsigned long CAsyncHttp::CHttpCommand::getRetValue() { if ( m_strCallback.length() == 0 ) { if(getLogCategory().getName() == "NO_LOGGING") return atoi(m_strResBody.c_str()); else return rho_ruby_create_string(m_strResBody.c_str()); } return rho_ruby_get_NIL(); } String CAsyncHttp::CHttpCommand::makeHeadersString() { String strRes = ""; for ( Hashtable<String,String>::iterator it = m_mapHeaders.begin(); it != m_mapHeaders.end(); ++it ) { if ( strRes.length() > 0) strRes += "&"; strRes += "headers["; URI::urlEncode(it->first,strRes); strRes += "]="; URI::urlEncode(it->second,strRes); } return strRes; } void CAsyncHttp::CHttpCommand::callNotify(NetResponse& resp, int nError ) { m_strResBody = "rho_callback=1"; m_strResBody += "&status="; if ( nError > 0 ) { m_strResBody += "error&error_code=" + nError; }else { if ( resp.isSuccess() ) { m_strResBody += "ok"; if ( resp.isResponseRecieved()) m_strResBody += "&http_error=" + convertToStringA(resp.getRespCode()); } else { m_strResBody += "error&error_code="; m_strResBody += convertToStringA(RhoAppAdapter.getErrorFromResponse(resp)); if ( resp.isResponseRecieved()) m_strResBody += "&http_error=" + convertToStringA(resp.getRespCode()); } String cookies = resp.getCookies(); if (cookies.length()>0) m_strResBody += "&cookies=" + URI::urlEncode(cookies); String strHeaders = makeHeadersString(); if (strHeaders.length() > 0 ) m_strResBody += "&" + strHeaders; m_strResBody += "&" + RHODESAPP().addCallbackObject( new CAsyncHttpResponse(resp, m_mapHeaders.get("content-type"), m_mapHeaders.get("content-encoding")), "body"); } if ( m_strCallbackParams.length() > 0 ) m_strResBody += "&" + m_strCallbackParams; if ( m_strCallback.length() > 0 ) { String strFullUrl = m_NetRequest.resolveUrl(m_strCallback); LOG(TRACE) + "Callback:" + m_strCallback + "Result body: " + m_strResBody; getNet().pushData( strFullUrl, m_strResBody, null ); } } CAsyncHttp::CAsyncHttpResponse::~CAsyncHttpResponse(){} extern "C" VALUE rjson_tokener_parse(const char *str, char** pszError ); unsigned long CAsyncHttp::CAsyncHttpResponse::getObjectValue() { if (m_NetResponse.isSuccess()) { if ( m_strContentType.find("application/json") != String::npos/* && m_strContentEncoding.find("gzip") == String::npos*/ ) { char* szError = 0; unsigned long valBody = rjson_tokener_parse(m_NetResponse.getCharData(), &szError); if ( valBody != 0 ) return valBody; LOG(ERROR) + "Incorrect json body.Error:" + (szError ? szError : ""); if ( szError ) free(szError); } } return rho_ruby_create_string_withlen2(m_NetResponse.getCharData(), m_NetResponse.getDataSize() ); } } // namespace net } // namespace rho extern "C" { using namespace rho::net; void rho_asynchttp_cancel(const char* cancel_callback) { if ( CAsyncHttp::getInstance() != null ) CAsyncHttp::getInstance()->cancelRequest(cancel_callback); } unsigned long rho_asynchttp_request(const char* command, rho_param *p) { CAsyncHttp::Create(); return CAsyncHttp::getInstance()->addHttpCommand(new CAsyncHttp::CHttpCommand( command, p )); } } <|endoftext|>
<commit_before>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "DexStructure.h" #include <boost/algorithm/string/predicate.hpp> #include <vector> #include "DexClass.h" #include "Util.h" namespace { struct PenaltyPattern { const char* suffix; unsigned penalty; PenaltyPattern(const char* str, unsigned penalty) : suffix(str), penalty(penalty) {} }; const PenaltyPattern PENALTY_PATTERNS[] = { {"Layout;", 1500}, {"View;", 1500}, {"ViewGroup;", 1800}, {"Activity;", 1500}, }; constexpr unsigned VTABLE_SLOT_SIZE = 4; constexpr unsigned OBJECT_VTABLE = 48; constexpr unsigned METHOD_SIZE = 52; constexpr unsigned INSTANCE_FIELD_SIZE = 16; constexpr unsigned MAX_METHOD_REFS = (1 << 16) - 1; constexpr unsigned MAX_FIELD_REFS = (1 << 16) - 1; bool matches_penalty(const char* str, unsigned* penalty) { for (auto const& pattern : PENALTY_PATTERNS) { if (boost::algorithm::ends_with(str, pattern.suffix)) { *penalty = pattern.penalty; return true; } } return false; } /** * Estimates the linear alloc space consumed by the class at runtime. */ unsigned estimate_linear_alloc(const DexClass* clazz) { unsigned lasize = 0; // VTable guesstimate. Technically we could do better here, but only so much. // Try to stay bug-compatible with DalvikStatsTool. if (!is_interface(clazz)) { unsigned vtablePenalty = OBJECT_VTABLE; if (!matches_penalty(clazz->get_type()->get_name()->c_str(), &vtablePenalty) && clazz->get_super_class() != nullptr) { // TODO: we could be redexing object some day... :) matches_penalty(clazz->get_super_class()->get_name()->c_str(), &vtablePenalty); } lasize += vtablePenalty; lasize += clazz->get_vmethods().size() * VTABLE_SLOT_SIZE; } lasize += clazz->get_dmethods().size() * METHOD_SIZE; lasize += clazz->get_vmethods().size() * METHOD_SIZE; lasize += clazz->get_ifields().size() * INSTANCE_FIELD_SIZE; return lasize; } /** * Removes the elements of b from a. Runs in O(size(a)), so it works best if * size(a) << size(b). */ template <typename T> std::unordered_set<T> set_difference(const std::unordered_set<T>& a, const std::unordered_set<T>& b) { std::unordered_set<T> result; for (auto& v : a) { if (!b.count(v)) { result.emplace(v); } } return result; } } // namespace namespace interdex { bool DexesStructure::add_class_to_current_dex(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { always_assert_log(m_classes.count(clazz) == 0, "Can't emit the same class twice!\n", SHOW(clazz)); if (m_current_dex.add_class_if_fits(clazz_mrefs, clazz_frefs, m_linear_alloc_limit, clazz)) { update_stats(clazz_mrefs, clazz_frefs, clazz); m_classes.emplace(clazz); return true; } return false; } void DexesStructure::add_class_no_checks(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { always_assert_log(m_classes.count(clazz) == 0, "Can't emit the same class twice!\n", SHOW(clazz)); auto laclazz = estimate_linear_alloc(clazz); m_current_dex.add_class_no_checks(clazz_mrefs, clazz_frefs, laclazz, clazz); m_classes.emplace(clazz); update_stats(clazz_mrefs, clazz_frefs, clazz); } DexClasses DexesStructure::end_dex(DexInfo dex_info) { m_info.num_dexes++; if (!dex_info.primary) { m_info.num_secondary_dexes++; } if (dex_info.coldstart) { m_info.num_coldstart_dexes++; } if (dex_info.extended) { m_info.num_extended_set_dexes++; } if (dex_info.mixed_mode) { m_info.num_mixed_mode_dexes++; } if (dex_info.scroll) { m_info.num_scroll_dexes++; } m_current_dex.check_refs_count(); DexClasses all_classes = std::move(m_current_dex.take_all_classes()); m_current_dex = DexStructure(); return all_classes; } void DexesStructure::update_stats(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { for (DexMethod* method : clazz->get_dmethods()) { if (is_static(method)) { m_stats.num_static_meths++; } } m_stats.num_dmethods += clazz->get_dmethods().size(); m_stats.num_vmethods += clazz->get_vmethods().size(); m_stats.num_mrefs += clazz_mrefs.size(); m_stats.num_frefs += clazz_frefs.size(); } bool DexStructure::add_class_if_fits(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, size_t linear_alloc_limit, DexClass* clazz) { unsigned laclazz = estimate_linear_alloc(clazz); if (m_linear_alloc_size + laclazz > linear_alloc_limit) { TRACE(IDEX, 6, "[warning]: Class won't fit current dex since it will go " "over the linear alloc limit: %s\n", SHOW(clazz)); return false; } auto extra_mrefs = set_difference(clazz_mrefs, m_mrefs); auto extra_frefs = set_difference(clazz_frefs, m_frefs); if (m_mrefs.size() + extra_mrefs.size() >= MAX_METHOD_REFS || m_frefs.size() + extra_frefs.size() >= MAX_FIELD_REFS) { TRACE(IDEX, 6, "[warning]: Class won't fit current dex since it will go " "over the method or field refs limit: %d / %d : %s\n", m_mrefs.size() + extra_mrefs.size(), m_frefs.size() + extra_frefs.size(), SHOW(clazz)); return false; } add_class_no_checks(clazz_mrefs, clazz_frefs, laclazz, clazz); return true; } void DexStructure::add_class_no_checks(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, unsigned laclazz, DexClass* clazz) { TRACE(IDEX, 7, "Adding class: %s\n", SHOW(clazz)); m_mrefs.insert(clazz_mrefs.begin(), clazz_mrefs.end()); m_frefs.insert(clazz_frefs.begin(), clazz_frefs.end()); m_linear_alloc_size += laclazz; m_classes.push_back(clazz); } /* * Sanity check: did gather_refs return all the refs that ultimately ended up * in the dex? */ void DexStructure::check_refs_count() { std::vector<DexMethodRef*> mrefs; for (DexClass* cls : m_classes) { cls->gather_methods(mrefs); } std::unordered_set<DexMethodRef*> mrefs_set(mrefs.begin(), mrefs.end()); if (mrefs_set.size() > m_mrefs.size()) { for (DexMethodRef* mr : mrefs_set) { if (!m_mrefs.count(mr)) { TRACE(IDEX, 4, "WARNING: Could not find %s in predicted mrefs set\n", SHOW(mr)); } } } std::vector<DexFieldRef*> frefs; for (DexClass* cls : m_classes) { cls->gather_fields(frefs); } std::unordered_set<DexFieldRef*> frefs_set(frefs.begin(), frefs.end()); if (frefs_set.size() > m_frefs.size()) { for (auto* fr : frefs_set) { if (!m_frefs.count(fr)) { TRACE(IDEX, 4, "WARNING: Could not find %s in predicted frefs set\n", SHOW(fr)); } } } // TODO: do we need to re-check linear_alloc_limit? } } // namespace interdex <commit_msg>Emit class when duplicated<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "DexStructure.h" #include <boost/algorithm/string/predicate.hpp> #include <vector> #include "DexClass.h" #include "Util.h" namespace { struct PenaltyPattern { const char* suffix; unsigned penalty; PenaltyPattern(const char* str, unsigned penalty) : suffix(str), penalty(penalty) {} }; const PenaltyPattern PENALTY_PATTERNS[] = { {"Layout;", 1500}, {"View;", 1500}, {"ViewGroup;", 1800}, {"Activity;", 1500}, }; constexpr unsigned VTABLE_SLOT_SIZE = 4; constexpr unsigned OBJECT_VTABLE = 48; constexpr unsigned METHOD_SIZE = 52; constexpr unsigned INSTANCE_FIELD_SIZE = 16; constexpr unsigned MAX_METHOD_REFS = (1 << 16) - 1; constexpr unsigned MAX_FIELD_REFS = (1 << 16) - 1; bool matches_penalty(const char* str, unsigned* penalty) { for (auto const& pattern : PENALTY_PATTERNS) { if (boost::algorithm::ends_with(str, pattern.suffix)) { *penalty = pattern.penalty; return true; } } return false; } /** * Estimates the linear alloc space consumed by the class at runtime. */ unsigned estimate_linear_alloc(const DexClass* clazz) { unsigned lasize = 0; // VTable guesstimate. Technically we could do better here, but only so much. // Try to stay bug-compatible with DalvikStatsTool. if (!is_interface(clazz)) { unsigned vtablePenalty = OBJECT_VTABLE; if (!matches_penalty(clazz->get_type()->get_name()->c_str(), &vtablePenalty) && clazz->get_super_class() != nullptr) { // TODO: we could be redexing object some day... :) matches_penalty(clazz->get_super_class()->get_name()->c_str(), &vtablePenalty); } lasize += vtablePenalty; lasize += clazz->get_vmethods().size() * VTABLE_SLOT_SIZE; } lasize += clazz->get_dmethods().size() * METHOD_SIZE; lasize += clazz->get_vmethods().size() * METHOD_SIZE; lasize += clazz->get_ifields().size() * INSTANCE_FIELD_SIZE; return lasize; } /** * Removes the elements of b from a. Runs in O(size(a)), so it works best if * size(a) << size(b). */ template <typename T> std::unordered_set<T> set_difference(const std::unordered_set<T>& a, const std::unordered_set<T>& b) { std::unordered_set<T> result; for (auto& v : a) { if (!b.count(v)) { result.emplace(v); } } return result; } } // namespace namespace interdex { bool DexesStructure::add_class_to_current_dex(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { always_assert_log(m_classes.count(clazz) == 0, "Can't emit the same class twice!\n", SHOW(clazz)); if (m_current_dex.add_class_if_fits(clazz_mrefs, clazz_frefs, m_linear_alloc_limit, clazz)) { update_stats(clazz_mrefs, clazz_frefs, clazz); m_classes.emplace(clazz); return true; } return false; } void DexesStructure::add_class_no_checks(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { always_assert_log(m_classes.count(clazz) == 0, "Can't emit the same class twice: %s!\n", SHOW(clazz)); auto laclazz = estimate_linear_alloc(clazz); m_current_dex.add_class_no_checks(clazz_mrefs, clazz_frefs, laclazz, clazz); m_classes.emplace(clazz); update_stats(clazz_mrefs, clazz_frefs, clazz); } DexClasses DexesStructure::end_dex(DexInfo dex_info) { m_info.num_dexes++; if (!dex_info.primary) { m_info.num_secondary_dexes++; } if (dex_info.coldstart) { m_info.num_coldstart_dexes++; } if (dex_info.extended) { m_info.num_extended_set_dexes++; } if (dex_info.mixed_mode) { m_info.num_mixed_mode_dexes++; } if (dex_info.scroll) { m_info.num_scroll_dexes++; } m_current_dex.check_refs_count(); DexClasses all_classes = std::move(m_current_dex.take_all_classes()); m_current_dex = DexStructure(); return all_classes; } void DexesStructure::update_stats(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, DexClass* clazz) { for (DexMethod* method : clazz->get_dmethods()) { if (is_static(method)) { m_stats.num_static_meths++; } } m_stats.num_dmethods += clazz->get_dmethods().size(); m_stats.num_vmethods += clazz->get_vmethods().size(); m_stats.num_mrefs += clazz_mrefs.size(); m_stats.num_frefs += clazz_frefs.size(); } bool DexStructure::add_class_if_fits(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, size_t linear_alloc_limit, DexClass* clazz) { unsigned laclazz = estimate_linear_alloc(clazz); if (m_linear_alloc_size + laclazz > linear_alloc_limit) { TRACE(IDEX, 6, "[warning]: Class won't fit current dex since it will go " "over the linear alloc limit: %s\n", SHOW(clazz)); return false; } auto extra_mrefs = set_difference(clazz_mrefs, m_mrefs); auto extra_frefs = set_difference(clazz_frefs, m_frefs); if (m_mrefs.size() + extra_mrefs.size() >= MAX_METHOD_REFS || m_frefs.size() + extra_frefs.size() >= MAX_FIELD_REFS) { TRACE(IDEX, 6, "[warning]: Class won't fit current dex since it will go " "over the method or field refs limit: %d / %d : %s\n", m_mrefs.size() + extra_mrefs.size(), m_frefs.size() + extra_frefs.size(), SHOW(clazz)); return false; } add_class_no_checks(clazz_mrefs, clazz_frefs, laclazz, clazz); return true; } void DexStructure::add_class_no_checks(const MethodRefs& clazz_mrefs, const FieldRefs& clazz_frefs, unsigned laclazz, DexClass* clazz) { TRACE(IDEX, 7, "Adding class: %s\n", SHOW(clazz)); m_mrefs.insert(clazz_mrefs.begin(), clazz_mrefs.end()); m_frefs.insert(clazz_frefs.begin(), clazz_frefs.end()); m_linear_alloc_size += laclazz; m_classes.push_back(clazz); } /* * Sanity check: did gather_refs return all the refs that ultimately ended up * in the dex? */ void DexStructure::check_refs_count() { std::vector<DexMethodRef*> mrefs; for (DexClass* cls : m_classes) { cls->gather_methods(mrefs); } std::unordered_set<DexMethodRef*> mrefs_set(mrefs.begin(), mrefs.end()); if (mrefs_set.size() > m_mrefs.size()) { for (DexMethodRef* mr : mrefs_set) { if (!m_mrefs.count(mr)) { TRACE(IDEX, 4, "WARNING: Could not find %s in predicted mrefs set\n", SHOW(mr)); } } } std::vector<DexFieldRef*> frefs; for (DexClass* cls : m_classes) { cls->gather_fields(frefs); } std::unordered_set<DexFieldRef*> frefs_set(frefs.begin(), frefs.end()); if (frefs_set.size() > m_frefs.size()) { for (auto* fr : frefs_set) { if (!m_frefs.count(fr)) { TRACE(IDEX, 4, "WARNING: Could not find %s in predicted frefs set\n", SHOW(fr)); } } } // TODO: do we need to re-check linear_alloc_limit? } } // namespace interdex <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: doctemplateslocal.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP #include <com/sun/star/xml/sax/XParser.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #include "doctemplateslocal.hxx" #include "attributelist.hxx" using namespace ::com::sun::star; // ----------------------------------- uno::Sequence< beans::StringPair > DocTemplLocaleHelper::ReadGroupLocalizationSequence( const uno::Reference< io::XInputStream >& xInStream, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { ::rtl::OUString aStringID = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "groupuinames.xml" ) ); return ReadLocalizationSequence_Impl( xInStream, aStringID, xFactory ); } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::WriteGroupLocalizationSequence( const uno::Reference< io::XOutputStream >& xOutStream, const uno::Sequence< beans::StringPair >& aSequence, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { if ( !xOutStream.is() ) throw uno::RuntimeException(); uno::Reference< io::XActiveDataSource > xWriterSource( xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" ) ) ), uno::UNO_QUERY_THROW ); uno::Reference< xml::sax::XDocumentHandler > xWriterHandler( xWriterSource, uno::UNO_QUERY_THROW ); xWriterSource->setOutputStream( xOutStream ); ::rtl::OUString aGroupListElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group-list" ) ); ::rtl::OUString aGroupElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group" ) ); ::rtl::OUString aNameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:name" ) ); ::rtl::OUString aUINameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:default-ui-name" ) ); ::rtl::OUString aCDATAString( RTL_CONSTASCII_USTRINGPARAM ( "CDATA" ) ); ::rtl::OUString aWhiteSpace( RTL_CONSTASCII_USTRINGPARAM ( " " ) ); // write the namespace AttributeList* pRootAttrList = new AttributeList; uno::Reference< xml::sax::XAttributeList > xRootAttrList( pRootAttrList ); pRootAttrList->AddAttribute( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "xmlns" ) ), aCDATAString, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "http://openoffice.org/2006/groupuinames" ) ) ); xWriterHandler->startDocument(); xWriterHandler->startElement( aGroupListElement, xRootAttrList ); for ( sal_Int32 nInd = 0; nInd < aSequence.getLength(); nInd++ ) { AttributeList *pAttrList = new AttributeList; uno::Reference< xml::sax::XAttributeList > xAttrList( pAttrList ); pAttrList->AddAttribute( aNameAttr, aCDATAString, aSequence[nInd].First ); pAttrList->AddAttribute( aUINameAttr, aCDATAString, aSequence[nInd].Second ); xWriterHandler->startElement( aGroupElement, xAttrList ); xWriterHandler->ignorableWhitespace( aWhiteSpace ); xWriterHandler->endElement( aGroupElement ); } xWriterHandler->ignorableWhitespace( aWhiteSpace ); xWriterHandler->endElement( aGroupListElement ); xWriterHandler->endDocument(); } // ================================================================================== // ----------------------------------- uno::Sequence< beans::StringPair > SAL_CALL DocTemplLocaleHelper::ReadLocalizationSequence_Impl( const uno::Reference< io::XInputStream >& xInStream, const ::rtl::OUString& aStringID, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { if ( !xFactory.is() || !xInStream.is() ) throw uno::RuntimeException(); uno::Sequence< beans::StringPair > aResult; uno::Reference< xml::sax::XParser > xParser( xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY_THROW ); DocTemplLocaleHelper* pHelper = new DocTemplLocaleHelper(); uno::Reference< xml::sax::XDocumentHandler > xHelper( static_cast< xml::sax::XDocumentHandler* >( pHelper ) ); xml::sax::InputSource aParserInput; aParserInput.aInputStream = xInStream; aParserInput.sSystemId = aStringID; xParser->setDocumentHandler( xHelper ); xParser->parseStream( aParserInput ); xParser->setDocumentHandler( uno::Reference < xml::sax::XDocumentHandler > () ); return pHelper->GetParsingResult(); } // ----------------------------------- DocTemplLocaleHelper::DocTemplLocaleHelper() : m_aGroupListElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group-list" ) ) , m_aGroupElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group" ) ) , m_aNameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:name" ) ) , m_aUINameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:default-ui-name" ) ) { } // ----------------------------------- DocTemplLocaleHelper::~DocTemplLocaleHelper() { } // ----------------------------------- uno::Sequence< beans::StringPair > DocTemplLocaleHelper::GetParsingResult() { if ( m_aElementsSeq.getLength() ) throw uno::RuntimeException(); // the parsing has still not finished! return m_aResultSeq; } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::startDocument() throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::endDocument() throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::startElement( const ::rtl::OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs ) throw( xml::sax::SAXException, uno::RuntimeException ) { if ( aName == m_aGroupListElement ) { sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( nNewLength != 1 ) throw xml::sax::SAXException(); // TODO: this element must be the first level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; return; // nothing to do } else if ( aName == m_aGroupElement ) { sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( nNewLength != 2 ) throw xml::sax::SAXException(); // TODO: this element must be the second level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; sal_Int32 nNewEntryNum = m_aResultSeq.getLength() + 1; m_aResultSeq.realloc( nNewEntryNum ); ::rtl::OUString aNameValue = xAttribs->getValueByName( m_aNameAttr ); if ( !aNameValue.getLength() ) throw xml::sax::SAXException(); // TODO: the ID value must present ::rtl::OUString aUINameValue = xAttribs->getValueByName( m_aUINameAttr ); if ( !aUINameValue.getLength() ) throw xml::sax::SAXException(); // TODO: the ID value must present m_aResultSeq[nNewEntryNum-1].First = aNameValue; m_aResultSeq[nNewEntryNum-1].Second = aUINameValue; } else { // accept future extensions sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( !nNewLength ) throw xml::sax::SAXException(); // TODO: the extension element must not be the first level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; } } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::endElement( const ::rtl::OUString& aName ) throw( xml::sax::SAXException, uno::RuntimeException ) { sal_Int32 nLength = m_aElementsSeq.getLength(); if ( nLength <= 0 ) throw xml::sax::SAXException(); // TODO: no other end elements expected! if ( !m_aElementsSeq[nLength-1].equals( aName ) ) throw xml::sax::SAXException(); // TODO: unexpected element ended m_aElementsSeq.realloc( nLength - 1 ); } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::characters( const ::rtl::OUString& /*aChars*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::ignorableWhitespace( const ::rtl::OUString& /*aWhitespaces*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::processingInstruction( const ::rtl::OUString& /*aTarget*/, const ::rtl::OUString& /*aData*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } <commit_msg>INTEGRATION: CWS xmlfix2 (1.3.428); FILE MERGED 2008/05/15 17:28:01 mst 1.3.428.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/31 15:14:12 mst 1.3.428.1: remove duplicated XAttributeList implementations - sfx2/source/doc/attributelist.{hxx,cxx}: + removed - sfx2/source/doc/makefile.mk: + remove attributelist.cxx - sfx2/source/doc/doctemplateslocal.cxx: + use comphelper/attributelist.hxx<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: doctemplateslocal.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP #include <com/sun/star/xml/sax/XParser.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #include <comphelper/attributelist.hxx> #include "doctemplateslocal.hxx" using namespace ::com::sun::star; // ----------------------------------- uno::Sequence< beans::StringPair > DocTemplLocaleHelper::ReadGroupLocalizationSequence( const uno::Reference< io::XInputStream >& xInStream, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { ::rtl::OUString aStringID = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "groupuinames.xml" ) ); return ReadLocalizationSequence_Impl( xInStream, aStringID, xFactory ); } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::WriteGroupLocalizationSequence( const uno::Reference< io::XOutputStream >& xOutStream, const uno::Sequence< beans::StringPair >& aSequence, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { if ( !xOutStream.is() ) throw uno::RuntimeException(); uno::Reference< io::XActiveDataSource > xWriterSource( xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" ) ) ), uno::UNO_QUERY_THROW ); uno::Reference< xml::sax::XDocumentHandler > xWriterHandler( xWriterSource, uno::UNO_QUERY_THROW ); xWriterSource->setOutputStream( xOutStream ); ::rtl::OUString aGroupListElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group-list" ) ); ::rtl::OUString aGroupElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group" ) ); ::rtl::OUString aNameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:name" ) ); ::rtl::OUString aUINameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:default-ui-name" ) ); ::rtl::OUString aCDATAString( RTL_CONSTASCII_USTRINGPARAM ( "CDATA" ) ); ::rtl::OUString aWhiteSpace( RTL_CONSTASCII_USTRINGPARAM ( " " ) ); // write the namespace ::comphelper::AttributeList* pRootAttrList = new ::comphelper::AttributeList; uno::Reference< xml::sax::XAttributeList > xRootAttrList( pRootAttrList ); pRootAttrList->AddAttribute( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "xmlns" ) ), aCDATAString, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "http://openoffice.org/2006/groupuinames" ) ) ); xWriterHandler->startDocument(); xWriterHandler->startElement( aGroupListElement, xRootAttrList ); for ( sal_Int32 nInd = 0; nInd < aSequence.getLength(); nInd++ ) { ::comphelper::AttributeList *pAttrList = new ::comphelper::AttributeList; uno::Reference< xml::sax::XAttributeList > xAttrList( pAttrList ); pAttrList->AddAttribute( aNameAttr, aCDATAString, aSequence[nInd].First ); pAttrList->AddAttribute( aUINameAttr, aCDATAString, aSequence[nInd].Second ); xWriterHandler->startElement( aGroupElement, xAttrList ); xWriterHandler->ignorableWhitespace( aWhiteSpace ); xWriterHandler->endElement( aGroupElement ); } xWriterHandler->ignorableWhitespace( aWhiteSpace ); xWriterHandler->endElement( aGroupListElement ); xWriterHandler->endDocument(); } // ================================================================================== // ----------------------------------- uno::Sequence< beans::StringPair > SAL_CALL DocTemplLocaleHelper::ReadLocalizationSequence_Impl( const uno::Reference< io::XInputStream >& xInStream, const ::rtl::OUString& aStringID, const uno::Reference< lang::XMultiServiceFactory > xFactory ) throw( uno::Exception ) { if ( !xFactory.is() || !xInStream.is() ) throw uno::RuntimeException(); uno::Sequence< beans::StringPair > aResult; uno::Reference< xml::sax::XParser > xParser( xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY_THROW ); DocTemplLocaleHelper* pHelper = new DocTemplLocaleHelper(); uno::Reference< xml::sax::XDocumentHandler > xHelper( static_cast< xml::sax::XDocumentHandler* >( pHelper ) ); xml::sax::InputSource aParserInput; aParserInput.aInputStream = xInStream; aParserInput.sSystemId = aStringID; xParser->setDocumentHandler( xHelper ); xParser->parseStream( aParserInput ); xParser->setDocumentHandler( uno::Reference < xml::sax::XDocumentHandler > () ); return pHelper->GetParsingResult(); } // ----------------------------------- DocTemplLocaleHelper::DocTemplLocaleHelper() : m_aGroupListElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group-list" ) ) , m_aGroupElement( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:template-group" ) ) , m_aNameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:name" ) ) , m_aUINameAttr( RTL_CONSTASCII_USTRINGPARAM( "groupuinames:default-ui-name" ) ) { } // ----------------------------------- DocTemplLocaleHelper::~DocTemplLocaleHelper() { } // ----------------------------------- uno::Sequence< beans::StringPair > DocTemplLocaleHelper::GetParsingResult() { if ( m_aElementsSeq.getLength() ) throw uno::RuntimeException(); // the parsing has still not finished! return m_aResultSeq; } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::startDocument() throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::endDocument() throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::startElement( const ::rtl::OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs ) throw( xml::sax::SAXException, uno::RuntimeException ) { if ( aName == m_aGroupListElement ) { sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( nNewLength != 1 ) throw xml::sax::SAXException(); // TODO: this element must be the first level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; return; // nothing to do } else if ( aName == m_aGroupElement ) { sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( nNewLength != 2 ) throw xml::sax::SAXException(); // TODO: this element must be the second level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; sal_Int32 nNewEntryNum = m_aResultSeq.getLength() + 1; m_aResultSeq.realloc( nNewEntryNum ); ::rtl::OUString aNameValue = xAttribs->getValueByName( m_aNameAttr ); if ( !aNameValue.getLength() ) throw xml::sax::SAXException(); // TODO: the ID value must present ::rtl::OUString aUINameValue = xAttribs->getValueByName( m_aUINameAttr ); if ( !aUINameValue.getLength() ) throw xml::sax::SAXException(); // TODO: the ID value must present m_aResultSeq[nNewEntryNum-1].First = aNameValue; m_aResultSeq[nNewEntryNum-1].Second = aUINameValue; } else { // accept future extensions sal_Int32 nNewLength = m_aElementsSeq.getLength() + 1; if ( !nNewLength ) throw xml::sax::SAXException(); // TODO: the extension element must not be the first level element m_aElementsSeq.realloc( nNewLength ); m_aElementsSeq[nNewLength-1] = aName; } } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::endElement( const ::rtl::OUString& aName ) throw( xml::sax::SAXException, uno::RuntimeException ) { sal_Int32 nLength = m_aElementsSeq.getLength(); if ( nLength <= 0 ) throw xml::sax::SAXException(); // TODO: no other end elements expected! if ( !m_aElementsSeq[nLength-1].equals( aName ) ) throw xml::sax::SAXException(); // TODO: unexpected element ended m_aElementsSeq.realloc( nLength - 1 ); } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::characters( const ::rtl::OUString& /*aChars*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::ignorableWhitespace( const ::rtl::OUString& /*aWhitespaces*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::processingInstruction( const ::rtl::OUString& /*aTarget*/, const ::rtl::OUString& /*aData*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } // ----------------------------------- void SAL_CALL DocTemplLocaleHelper::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ ) throw(xml::sax::SAXException, uno::RuntimeException) { } <|endoftext|>
<commit_before>#include <iostream> #include "DDImage/ddImageVersionNumbers.h" int main(int, char*[]) { std::cout << kDDImageVersion; return 0; } <commit_msg>Build Nuke stuff into lib/nuke${MAJOR}.${MINOR} (e.g lib/nuke6.2)<commit_after>#include <iostream> #include "DDImage/ddImageVersionNumbers.h" int main(int, char*[]) { // Print a Nuke API identifier number, used to make the // lib/nuke${API_NUMBER} directory // Nuke aims to maintain API compatibilty between "v" releases, so // compiling for 6.1v1 will work with 6.1v2 etc (but not // 6.2v1). Only exception has been 5.1v5 and 5.1v6 (because it was // supposed to be 5.2v1) std::cout << kDDImageVersionMajorNum << "." << kDDImageVersionMinorNum; return 0; } <|endoftext|>
<commit_before>#include "ARVersion.h" #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliCDBStorage.h" #include "AliCDBId.h" #include "AliCDBMetaData.h" #include "AliGeomManager.h" #include <TROOT.h> #include "AliRun.h" #include <TGeoManager.h> #include <TString.h> #endif void UpdateCDBIdealGeom(const char* cdbUri, const char* cfgFile){ // Produce the ideal geometry and store it in the specified CDB // The second argument allows to specify the config file to be used // in particular for giving the choice to generate either a full or // a partial geometry. // AliCDBManager* cdb = AliCDBManager::Instance(); // we set the default storage to the repository because some dets require // already at the time of geometry creation to find calibration objects in the cdb AliCDBStorage* storage = 0; if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT"); storage = cdb->GetStorage(cdbUri); if(!storage) { Printf("unable to create valid storage from: %s", cdbUri); return; } cdb->SetRun(0); AliCDBId id("GRP/Geometry/Data",0,AliCDBRunRange::Infinity()); AliCDBMetaData *md= new AliCDBMetaData(); // Get root and AliRoot versions const char* rootv = gROOT->GetVersion(); TString av(ALIROOT_SVN_BRANCH); Int_t revnum = ALIROOT_SVN_REVISION; Printf("root version: %s. AliRoot %s, revision number %d",rootv,av.Data(),revnum); md->SetAliRootVersion(av.Data()); md->SetComment(Form("Geometry produced with root version %s and AliRoot %s, revision number %d",rootv,av.Data(),revnum)); gAlice->Init(cfgFile); if(!gGeoManager){ Printf("Unable to produce a valid geometry to be put in the CDB!"); return; } Printf("Storing in CDB geometry produced with root version %s and AliRoot version %s",rootv,av.Data()); storage->Put(gGeoManager,id,md); // This is to allow macros lauched after this one in the same session to find the // newly produced geometry. storage->QueryCDB(cdb->GetRun()); } <commit_msg>Setting default colours for the geometry (suggested by Mateusz)<commit_after>#include "ARVersion.h" #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliCDBStorage.h" #include "AliCDBId.h" #include "AliCDBMetaData.h" #include "AliGeomManager.h" #include <TROOT.h> #include "AliRun.h" #include <TGeoManager.h> #include <TString.h> #endif void UpdateCDBIdealGeom(const char* cdbUri, const char* cfgFile){ // Produce the ideal geometry and store it in the specified CDB // The second argument allows to specify the config file to be used // in particular for giving the choice to generate either a full or // a partial geometry. // AliCDBManager* cdb = AliCDBManager::Instance(); // we set the default storage to the repository because some dets require // already at the time of geometry creation to find calibration objects in the cdb AliCDBStorage* storage = 0; if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT"); storage = cdb->GetStorage(cdbUri); if(!storage) { Printf("unable to create valid storage from: %s", cdbUri); return; } cdb->SetRun(0); AliCDBId id("GRP/Geometry/Data",0,AliCDBRunRange::Infinity()); AliCDBMetaData *md= new AliCDBMetaData(); // Get root and AliRoot versions const char* rootv = gROOT->GetVersion(); TString av(ALIROOT_SVN_BRANCH); Int_t revnum = ALIROOT_SVN_REVISION; Printf("root version: %s. AliRoot %s, revision number %d",rootv,av.Data(),revnum); md->SetAliRootVersion(av.Data()); md->SetComment(Form("Geometry produced with root version %s and AliRoot %s, revision number %d",rootv,av.Data(),revnum)); gAlice->Init(cfgFile); if(!gGeoManager){ Printf("Unable to produce a valid geometry to be put in the CDB!"); return; } gGeoManager->DefaultColors(); // assign default colors according to Z of material // (many colors turned into dark gray nuances some time ago, when the root palette was changed) Printf("Storing in CDB geometry produced with root version %s and AliRoot version %s",rootv,av.Data()); storage->Put(gGeoManager,id,md); // This is to allow macros lauched after this one in the same session to find the // newly produced geometry. storage->QueryCDB(cdb->GetRun()); } <|endoftext|>
<commit_before>#include <iostream> #include <pwd.h> #include <sys/time.h> #include <unordered_set> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <fnmatch.h> #include "f2db_Options.h" #include "buildRmapT.h" #include "epoch.h" #include "xalt_user.h" #include "xalt_fgets_alloc.h" int buildUserSet(Set& userSet) { int count = 0; char* xalt_user_str = getenv("XALT_USERS"); if (xalt_user_str == NULL) return count; std::string userName; char* start = xalt_user_str; bool done = false; while(! done) { char * p = strchr(start,':'); if (p) userName.assign(start); else { done = true; userName.assign(start, p - start); } start = p+1; count++; userSet(userName); } return count; } int findFilesInDir(std::string& dir, const char* filePattern, Vstring& fileA) { DIR* dirp = opendir(dir.c_str()); if (dirp == NULL) return 0; struct dirent* dp; while( (dp = readdir(dirp)) != NULL) { if (fnmatch(filePattern, dp->d_name, 0) == 0) { std::string fullName(dir); fullName.append("/"); fullName.append(dp->d_name); fileA.push_back(fullName); } } closedir(dirp); return fileA.size(); } void removeFiles(Vstring& fileA) { for (auto it = fileA.begin(); it < fileA.end(); ++it) unlink(it->c_str()); } int link_json_fileA_to_db(Options& options, Table& rmapT, Vstring& fileA) { jsmn_parser parser; jsmntok_t* tokens; int maxTokens = 1000; int num = 0; for (auto it = fileA.begin(); it < fileA.end(); ++it) { Set funcSet; std::vector<Libpair> libA; Vstring linkLineA; Table resultT; std::string jsonStr; char* buf = NULL; size_t sz = 0; FILE* fp = fopen(it->c_str(),"r"); if (fp == NULL) continue; if (options.reportFn()) fprintf(stdout, "Processing link file: %s\n", it->c_str()); while(xalt_fgets_alloc(fp, &buf, &sz)) jsonStr.append(buf); free(buf); parseLinkJsonStr(jsonStr, linklineA, resultT, libA, funcSet); link_direct2db(Options.confFn().c_str(), linklineA, resultT, libA, funcSet, rmapT); num++; } return num; } int run_json_fileA_to_db(Options& options, Table& rmapT, Vstring& fileA) { jsmn_parser parser; jsmntok_t* tokens; int maxTokens = 1000; int num = 0; for (auto it = fileA.begin(); it < fileA.end(); ++it) { Vstring cmdlineA; std::string hash_id; Table envT; Table userT; Table recordT; std::vector<Libpair> libA; std::string jsonStr; char* buf = NULL; size_t sz = 0; FILE* fp = fopen(it->c_str(),"r"); if (fp == NULL) continue; if (options.reportFn()) fprintf(stdout, "Processing run file: %s\n", it->c_str()); while(xalt_fgets_alloc(fp, &buf, &sz)) jsonStr.append(buf); free(buf); parseRunJsonStr(jsonStr, cmdlineA, hash_id, envT, userT, recordT, libA); std::string usr_cmdline = ""; run_direct2db(Options.confFn().c_str(), usr_cmdline, hash_id, rmapT, envT, userT, recordT, libA); num++; } return num; } int main(int argc, char* argv[]) { Options options(argc, argv); double t1 = epoch(); Set userSet; int num = buildUserSet(userSet); bool haveUserSet = false; if (num == 0) { // Count the number of passwd entries: setpwent(); while ( (pw = getpwent()) != NULL ) num++; endpwent(); } else haveUserSet = true; ProcessBar pbar(num); Vstring xlibmapA; Table rmapT; buildRmapT(rmapT, xlibmapA); int icnt = 0; int iuser = 0; int lnkCnt = 0; int runCnt = 0; setpwent(); while ( (pw = getpwent()) != NULL ) { const char* userName = pw->pw_user; if (haveUserSet) { Set::const_iterator got = userSet.find(userName); if (got == userSet.end()) continue; } pbar.update(icnt++); // form directory xaltDir = "$HOME/.xalt.d" std::string xaltDir(pw->pw_dir); xaltDir.append("/.xalt.d"); if (isDirectory(xaltDir.c_str())) { Vstring linkFnA; int nlink = findFilesInDir(xaltDir, "link.*.json", linkFnA); linkCnt += link_json_fileA_to_db(options, rmapT, linkFnA); if (options.deleteFn()) removeFiles(linkFnA); Vstring runFnA; int nrun = findFilesInDir(xaltDir, "run.*.json", runFnA); runCnt += run_json_fileA_to_db(options, rmapT, runFnA); if (options.deleteFn()) removeFiles(runFnA); if (nlink + nrun > 0) iuser++; } } endpwent(); pbar.fini(); double rt = epoch() - t1; if (options.timer()) { const int dateSz = 100; char dateStr[dateSz]; strFtime(dateStr, dateSz, "%T", gmtime(&rt)); printf("Time: %s\n", dateStr); } printf("num users: %d, num links: %d, num runs: %d\n", iuser, lnkCnt, runCnt); return 0; } <commit_msg>Fixed the user password iterator when using XALT_USERS<commit_after>#include <iostream> #include <pwd.h> #include <sys/time.h> #include <unordered_set> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <fnmatch.h> #include "f2db_Options.h" #include "buildRmapT.h" #include "epoch.h" #include "xalt_user.h" #include "xalt_fgets_alloc.h" int buildUserTable(Table& users) { char* xalt_user_str = getenv("XALT_USERS"); if (xalt_user_str == NULL) return 0; std::string value; std::string userName; std::string homeDir; char* start = xalt_user_str; bool done = false; while(! done) { char * p = strchr(start,':'); if (p) value.assign(start); else { done = true; value.assign(start, p - start); } size_t idx = value.find(";"); if (idx == std::string::npos) { // find passwd record from systems: userName = value; struct passwd pw = getpwnam(userName.c_str()); if (pw) users[userName] = pw->pw_dir; } else { userName.assign(value,0,idx); homeDir.assign(value,idx+1); users[userName] = homeDir; } start = p+1; } return users.size(); } int findFilesInDir(std::string& dir, const char* filePattern, Vstring& fileA) { DIR* dirp = opendir(dir.c_str()); if (dirp == NULL) return 0; struct dirent* dp; while( (dp = readdir(dirp)) != NULL) { if (fnmatch(filePattern, dp->d_name, 0) == 0) { std::string fullName(dir); fullName.append("/"); fullName.append(dp->d_name); fileA.push_back(fullName); } } closedir(dirp); return fileA.size(); } void removeFiles(Vstring& fileA) { for (auto it = fileA.begin(); it < fileA.end(); ++it) unlink(it->c_str()); } int link_json_fileA_to_db(Options& options, Table& rmapT, Vstring& fileA) { jsmn_parser parser; jsmntok_t* tokens; int maxTokens = 1000; int num = 0; for (auto it = fileA.begin(); it < fileA.end(); ++it) { Set funcSet; std::vector<Libpair> libA; Vstring linkLineA; Table resultT; std::string jsonStr; char* buf = NULL; size_t sz = 0; FILE* fp = fopen(it->c_str(),"r"); if (fp == NULL) continue; if (options.reportFn()) fprintf(stdout, "Processing link file: %s\n", it->c_str()); while(xalt_fgets_alloc(fp, &buf, &sz)) jsonStr.append(buf); free(buf); parseLinkJsonStr(jsonStr, linklineA, resultT, libA, funcSet); link_direct2db(Options.confFn().c_str(), linklineA, resultT, libA, funcSet, rmapT); num++; } return num; } int run_json_fileA_to_db(Options& options, Table& rmapT, Vstring& fileA) { jsmn_parser parser; jsmntok_t* tokens; int maxTokens = 1000; int num = 0; for (auto it = fileA.begin(); it < fileA.end(); ++it) { Vstring cmdlineA; std::string hash_id; Table envT; Table userT; Table recordT; std::vector<Libpair> libA; std::string jsonStr; char* buf = NULL; size_t sz = 0; FILE* fp = fopen(it->c_str(),"r"); if (fp == NULL) continue; if (options.reportFn()) fprintf(stdout, "Processing run file: %s\n", it->c_str()); while(xalt_fgets_alloc(fp, &buf, &sz)) jsonStr.append(buf); free(buf); parseRunJsonStr(jsonStr, cmdlineA, hash_id, envT, userT, recordT, libA); std::string usr_cmdline = ""; run_direct2db(Options.confFn().c_str(), usr_cmdline, hash_id, rmapT, envT, userT, recordT, libA); num++; } return num; } int main(int argc, char* argv[]) { Options options(argc, argv); double t1 = epoch(); Table users; int num = buildUserTable(users); bool haveUserTable = false; if (num == 0) { // Count the number of passwd entries: setpwent(); while ( (pw = getpwent()) != NULL ) num++; endpwent(); } else haveUserTable = true; ProcessBar pbar(num); Vstring xlibmapA; Table rmapT; buildRmapT(rmapT, xlibmapA); int icnt = 0; int iuser = 0; int lnkCnt = 0; int runCnt = 0; std::string xaltDir; setpwent(); while ( (pw = getpwent()) != NULL ) { const char* userName = pw->pw_user; if (haveUserTable) { Set::const_iterator got = users.find(userName); if (got == users.end()) continue; xaltDir.assign((*got).second); } else xaltDir.assign(pw->pw_dir); pbar.update(icnt++); // form directory xaltDir = "$HOME/.xalt.d" xaltDir.append("/.xalt.d"); if (isDirectory(xaltDir.c_str())) { Vstring linkFnA; int nlink = findFilesInDir(xaltDir, "link.*.json", linkFnA); linkCnt += link_json_fileA_to_db(options, rmapT, linkFnA); if (options.deleteFn()) removeFiles(linkFnA); Vstring runFnA; int nrun = findFilesInDir(xaltDir, "run.*.json", runFnA); runCnt += run_json_fileA_to_db(options, rmapT, runFnA); if (options.deleteFn()) removeFiles(runFnA); if (nlink + nrun > 0) iuser++; } } endpwent(); pbar.fini(); double rt = epoch() - t1; if (options.timer()) { const int dateSz = 100; char dateStr[dateSz]; strFtime(dateStr, dateSz, "%T", gmtime(&rt)); printf("Time: %s\n", dateStr); } printf("num users: %d, num links: %d, num runs: %d\n", iuser, lnkCnt, runCnt); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkMovieMaker.h" #include "QmitkMovieMakerControls.h" #include "QmitkTreeNodeSelector.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "mitkOpenGLRenderer.h" #include "mitkMovieGenerator.h" #include "mitkGlobalInteraction.h" #include "icon.xpm" #include <iostream> #include <vtkRenderer.h> #include <vtkCamera.h> #include <qaction.h> #include <qfiledialog.h> #include <qtimer.h> #include <qdatetime.h> #include <qspinbox.h> #include <qcombobox.h> QmitkMovieMaker::QmitkMovieMaker( QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it ) : QmitkFunctionality(parent, name, it), m_Controls(NULL), m_StepperAdapter(NULL), m_MultiWidget(mitkStdMultiWidget), m_Looping(true), m_Direction(0), m_Aspect(0) { this->SetAvailability(true); m_Timer = new QTimer(this); m_Time = new QTime(); m_FocusManagerCallback = MemberCommand::New(); m_FocusManagerCallback->SetCallbackFunction( this, &QmitkMovieMaker::FocusChange ); mitk::GlobalInteraction::GetInstance()->GetFocusManager()->AddObserver( mitk::FocusEvent(), m_FocusManagerCallback ); } QmitkMovieMaker::~QmitkMovieMaker() { delete m_StepperAdapter; delete m_Timer; delete m_Time; } mitk::BaseController* QmitkMovieMaker::GetSpatialController() { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocus(); if ( m_MultiWidget->GetRenderWindow1()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow1()->GetController(); } else if ( m_MultiWidget->GetRenderWindow2()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow2()->GetController(); } else if ( m_MultiWidget->GetRenderWindow3()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow3()->GetController(); } else if ( m_MultiWidget->GetRenderWindow4()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow4()->GetController(); } return m_MultiWidget->GetRenderWindow4()->GetController(); } mitk::BaseController* QmitkMovieMaker::GetTemporalController() { return m_MultiWidget->GetTimeNavigationController(); } QWidget* QmitkMovieMaker::CreateMainWidget(QWidget *parent) { return NULL; } QWidget* QmitkMovieMaker::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkMovieMakerControls(parent); m_StepperAdapter = new QmitkStepperAdapter( (QObject*) m_Controls->slidAngle, this->GetSpatialController()->GetSlice(), "AngleStepperToMovieMakerFunctionality" ); // Initialize "Selected Window" combo box const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(); iter != rws.end(); ++iter) { m_Controls->cmbSelectedWindow->insertItem((*iter)->GetName(), -1); } } return m_Controls; } void QmitkMovieMaker::CreateConnections() { if ( m_Controls ) { // start / pause / stop playing connect( (QObject*) m_Controls, SIGNAL(StartPlaying()), this, SLOT(StartPlaying()) ); connect( (QObject*) m_Controls, SIGNAL(PausePlaying()), this, SLOT(PausePlaying()) ); connect( (QObject*) m_Controls, SIGNAL(StopPlaying()), this, SLOT(StopPlaying()) ); // radio button group: forward, backward, ping-pong connect( (QObject*) m_Controls, SIGNAL(SwitchDirection(int)), this, SLOT(SetDirection(int)) ); // radio button group: spatial, temporal connect( (QObject*) m_Controls, SIGNAL(SwitchAspect(int)), this, SLOT(SetAspect(int)) ); // window selection connect( (QObject*) m_Controls, SIGNAL(SwitchSelectedWindow(int)), this, SLOT(SetWindow(int)) ); // camera rotation // every timer tick connect( (QObject*) m_Timer, SIGNAL(timeout()), this, SLOT(RotateCamera()) ); // movie generation // when the movie button is clickethe movie button is clicked connect( (QObject*) m_Controls->btnMovie, SIGNAL(clicked()), this, SLOT(GenerateMovie()) ); connect( (QObject*) m_Controls->btnScreenshot, SIGNAL(clicked()), this, SLOT(GenerateScreenshot()) ); // blocking of ui elements during movie generation connect( (QObject*) this, SIGNAL(StartBlockControls()), (QObject*) m_Controls , SLOT(BlockControls()) ); connect( (QObject*) this, SIGNAL(EndBlockControls()), (QObject*) m_Controls , SLOT(UnBlockControls()) ); } } QAction* QmitkMovieMaker::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "MovieMaker" ), QPixmap((const char**)icon_xpm), tr( "Camera Path" ), Qt::CTRL + Qt::Key_G, parent, "MovieMaker" ); return action; } void QmitkMovieMaker::Activated() { QmitkFunctionality::Activated(); // Initialize steppers etc. this->FocusChange(); } void QmitkMovieMaker::FocusChange() { mitk::Stepper *stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper( stepper ); // Make the stepper movement non-inverted stepper->InverseDirectionOff(); // Set stepping direction and aspect (spatial / temporal) for new stepper this->UpdateLooping(); this->UpdateDirection(); // Set newly focused window as active in "Selected Window" combo box const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); int i; mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(), i = 0; iter != rws.end(); ++iter, ++i) { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocusManager()->GetFocused(); if ( focusedRenderer == (*iter)->GetRenderer() ) { m_Controls->cmbSelectedWindow->setCurrentItem( i ); break; } } } void QmitkMovieMaker::RotateCamera() { // This method is called when a timer timeout occurs. It increases the // stepper value according to the elapsed time and camera rotation inteval. // Note that a screen refresh is not forced, but merely requested, and may // occur only after more calls to RotateCamera(). mitk::Stepper* stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper( stepper ); int elapsedTime = m_Time->elapsed(); m_Time->restart(); static double increment = 0.0; increment = increment - static_cast< int >( increment ); increment += elapsedTime * stepper->GetSteps() / ( m_Controls->spnDuration->value() * 1000.0 ); int i, n = static_cast< int >( increment ); for ( i = 0; i < n; ++i ) { stepper->Next(); } } void QmitkMovieMaker::StartPlaying() { // Restart timer with 5 msec interval - this should be fine-grained enough // even for high display refresh frequencies m_Timer->start( 5 ); m_Time->restart(); } void QmitkMovieMaker::PausePlaying() { m_Timer->stop(); } void QmitkMovieMaker::StopPlaying() { m_Timer->stop(); switch ( m_Direction ) { case 0: case 2: this->GetAspectStepper()->First(); break; case 1: this->GetAspectStepper()->Last(); break; } // Reposition slider GUI element m_StepperAdapter->SetStepper( this->GetAspectStepper() ); } void QmitkMovieMaker::SetLooping( bool looping ) { m_Looping = looping; this->UpdateLooping(); } void QmitkMovieMaker::SetDirection( int direction ) { m_Direction = direction; this->UpdateDirection(); } void QmitkMovieMaker::SetAspect( int aspect ) { m_Aspect = aspect; this->UpdateLooping(); this->UpdateDirection(); } void QmitkMovieMaker::SetWindow( int window ) { // Set newly selected window / renderer as focused const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); int i; mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(), i = 0; iter != rws.end(); ++iter, ++i) { if ( i == window ) { mitk::GlobalInteraction::GetInstance()->GetFocusManager() ->SetFocused( (*iter)->GetRenderer() ); break; } } } void QmitkMovieMaker::UpdateLooping() { this->GetAspectStepper()->SetAutoRepeat( m_Looping ); } void QmitkMovieMaker::UpdateDirection() { mitk::Stepper* stepper = this->GetAspectStepper(); switch ( m_Direction ) { case 0: stepper->InverseDirectionOff(); stepper->PingPongOff(); break; case 1: stepper->InverseDirectionOn(); stepper->PingPongOff(); break; case 2: stepper->PingPongOn(); break; } } mitk::Stepper* QmitkMovieMaker::GetAspectStepper() { if (m_Aspect == 0) { m_Stepper = NULL; return this->GetSpatialController()->GetSlice(); } else if (m_Aspect == 1) { m_Stepper = NULL; return this->GetTemporalController()->GetTime(); } else if (m_Aspect == 2) { if (m_Stepper.IsNull()) { int rel = m_Controls->spatialTimeRelation->value(); int timeRepeat =1 ; int sliceRepeat = 1; if (rel < 0 ) { sliceRepeat = -rel; } else if (rel > 0) { timeRepeat = rel; } m_Stepper = mitk::MultiStepper::New(); m_Stepper->AddStepper(this->GetSpatialController()->GetSlice(),sliceRepeat); m_Stepper->AddStepper(this->GetTemporalController()->GetTime(),timeRepeat); } return m_Stepper.GetPointer(); } else { // should never get here return 0; } } void QmitkMovieMaker::GenerateMovie() { emit StartBlockControls(); // provide the movie generator with the stepper and rotate the camera each step mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New(); if ( movieGenerator.IsNotNull() ) { movieGenerator->SetStepper( this->GetAspectStepper() ); movieGenerator->SetRenderer( mitk::GlobalInteraction::GetInstance()->GetFocus() ); QString movieFileName = QFileDialog::getSaveFileName( QString::null, "Movie (*.avi)", 0, "movie file dialog", "Choose a file name" ); if(movieFileName.isEmpty() == false) { movieGenerator->SetFileName( movieFileName.ascii() ); movieGenerator->WriteMovie(); } } else { std::cerr << "Either mitk::MovieGenerator is not implemented for your"; std::cerr << " platform or an error occurred during"; std::cerr << " mitk::MovieGenerator::New()" << std::endl; } emit EndBlockControls(); } void QmitkMovieMaker::GenerateScreenshot() { emit StartBlockControls(); CommonFunctionality::SaveScreenshot( mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow() ); emit EndBlockControls(); } <commit_msg>ENH: Method name change<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkMovieMaker.h" #include "QmitkMovieMakerControls.h" #include "QmitkTreeNodeSelector.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "QmitkCommonFunctionality.h" #include "mitkOpenGLRenderer.h" #include "mitkMovieGenerator.h" #include "mitkGlobalInteraction.h" #include "icon.xpm" #include <iostream> #include <vtkRenderer.h> #include <vtkCamera.h> #include <qaction.h> #include <qfiledialog.h> #include <qtimer.h> #include <qdatetime.h> #include <qspinbox.h> #include <qcombobox.h> QmitkMovieMaker::QmitkMovieMaker( QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it ) : QmitkFunctionality(parent, name, it), m_Controls(NULL), m_StepperAdapter(NULL), m_MultiWidget(mitkStdMultiWidget), m_Looping(true), m_Direction(0), m_Aspect(0) { this->SetAvailability(true); m_Timer = new QTimer(this); m_Time = new QTime(); m_FocusManagerCallback = MemberCommand::New(); m_FocusManagerCallback->SetCallbackFunction( this, &QmitkMovieMaker::FocusChange ); mitk::GlobalInteraction::GetInstance()->GetFocusManager()->AddObserver( mitk::FocusEvent(), m_FocusManagerCallback ); } QmitkMovieMaker::~QmitkMovieMaker() { delete m_StepperAdapter; delete m_Timer; delete m_Time; } mitk::BaseController* QmitkMovieMaker::GetSpatialController() { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocus(); if ( m_MultiWidget->GetRenderWindow1()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow1()->GetController(); } else if ( m_MultiWidget->GetRenderWindow2()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow2()->GetController(); } else if ( m_MultiWidget->GetRenderWindow3()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow3()->GetController(); } else if ( m_MultiWidget->GetRenderWindow4()->GetRenderer() == focusedRenderer ) { return m_MultiWidget->GetRenderWindow4()->GetController(); } return m_MultiWidget->GetRenderWindow4()->GetController(); } mitk::BaseController* QmitkMovieMaker::GetTemporalController() { return m_MultiWidget->GetTimeNavigationController(); } QWidget* QmitkMovieMaker::CreateMainWidget(QWidget *parent) { return NULL; } QWidget* QmitkMovieMaker::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkMovieMakerControls(parent); m_StepperAdapter = new QmitkStepperAdapter( (QObject*) m_Controls->slidAngle, this->GetSpatialController()->GetSlice(), "AngleStepperToMovieMakerFunctionality" ); // Initialize "Selected Window" combo box const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(); iter != rws.end(); ++iter) { m_Controls->cmbSelectedWindow->insertItem((*iter)->GetName(), -1); } } return m_Controls; } void QmitkMovieMaker::CreateConnections() { if ( m_Controls ) { // start / pause / stop playing connect( (QObject*) m_Controls, SIGNAL(StartPlaying()), this, SLOT(StartPlaying()) ); connect( (QObject*) m_Controls, SIGNAL(PausePlaying()), this, SLOT(PausePlaying()) ); connect( (QObject*) m_Controls, SIGNAL(StopPlaying()), this, SLOT(StopPlaying()) ); // radio button group: forward, backward, ping-pong connect( (QObject*) m_Controls, SIGNAL(SwitchDirection(int)), this, SLOT(SetDirection(int)) ); // radio button group: spatial, temporal connect( (QObject*) m_Controls, SIGNAL(SwitchAspect(int)), this, SLOT(SetAspect(int)) ); // window selection connect( (QObject*) m_Controls, SIGNAL(SwitchSelectedWindow(int)), this, SLOT(SetWindow(int)) ); // advance the animation // every timer tick connect( (QObject*) m_Timer, SIGNAL(timeout()), this, SLOT(AdvanceAnimation()) ); // movie generation // when the movie button is clickethe movie button is clicked connect( (QObject*) m_Controls->btnMovie, SIGNAL(clicked()), this, SLOT(GenerateMovie()) ); connect( (QObject*) m_Controls->btnScreenshot, SIGNAL(clicked()), this, SLOT(GenerateScreenshot()) ); // blocking of ui elements during movie generation connect( (QObject*) this, SIGNAL(StartBlockControls()), (QObject*) m_Controls , SLOT(BlockControls()) ); connect( (QObject*) this, SIGNAL(EndBlockControls()), (QObject*) m_Controls , SLOT(UnBlockControls()) ); } } QAction* QmitkMovieMaker::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "MovieMaker" ), QPixmap((const char**)icon_xpm), tr( "Camera Path" ), Qt::CTRL + Qt::Key_G, parent, "MovieMaker" ); return action; } void QmitkMovieMaker::Activated() { QmitkFunctionality::Activated(); // Initialize steppers etc. this->FocusChange(); } void QmitkMovieMaker::FocusChange() { mitk::Stepper *stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper( stepper ); // Make the stepper movement non-inverted stepper->InverseDirectionOff(); // Set stepping direction and aspect (spatial / temporal) for new stepper this->UpdateLooping(); this->UpdateDirection(); // Set newly focused window as active in "Selected Window" combo box const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); int i; mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(), i = 0; iter != rws.end(); ++iter, ++i) { mitk::BaseRenderer* focusedRenderer = mitk::GlobalInteraction::GetInstance()->GetFocusManager()->GetFocused(); if ( focusedRenderer == (*iter)->GetRenderer() ) { m_Controls->cmbSelectedWindow->setCurrentItem( i ); break; } } } void QmitkMovieMaker::AdvanceAnimation() { // This method is called when a timer timeout occurs. It increases the // stepper value according to the elapsed time and the stepper interval. // Note that a screen refresh is not forced, but merely requested, and may // occur only after more calls to AdvanceAnimation(). mitk::Stepper* stepper = this->GetAspectStepper(); m_StepperAdapter->SetStepper( stepper ); int elapsedTime = m_Time->elapsed(); m_Time->restart(); static double increment = 0.0; increment = increment - static_cast< int >( increment ); increment += elapsedTime * stepper->GetSteps() / ( m_Controls->spnDuration->value() * 1000.0 ); int i, n = static_cast< int >( increment ); for ( i = 0; i < n; ++i ) { stepper->Next(); } } void QmitkMovieMaker::StartPlaying() { // Restart timer with 5 msec interval - this should be fine-grained enough // even for high display refresh frequencies m_Timer->start( 5 ); m_Time->restart(); } void QmitkMovieMaker::PausePlaying() { m_Timer->stop(); } void QmitkMovieMaker::StopPlaying() { m_Timer->stop(); switch ( m_Direction ) { case 0: case 2: this->GetAspectStepper()->First(); break; case 1: this->GetAspectStepper()->Last(); break; } // Reposition slider GUI element m_StepperAdapter->SetStepper( this->GetAspectStepper() ); } void QmitkMovieMaker::SetLooping( bool looping ) { m_Looping = looping; this->UpdateLooping(); } void QmitkMovieMaker::SetDirection( int direction ) { m_Direction = direction; this->UpdateDirection(); } void QmitkMovieMaker::SetAspect( int aspect ) { m_Aspect = aspect; this->UpdateLooping(); this->UpdateDirection(); } void QmitkMovieMaker::SetWindow( int window ) { // Set newly selected window / renderer as focused const mitk::RenderWindow::RenderWindowSet rws = mitk::RenderWindow::GetInstances(); int i; mitk::RenderWindow::RenderWindowSet::const_iterator iter; for (iter = rws.begin(), i = 0; iter != rws.end(); ++iter, ++i) { if ( i == window ) { mitk::GlobalInteraction::GetInstance()->GetFocusManager() ->SetFocused( (*iter)->GetRenderer() ); break; } } } void QmitkMovieMaker::UpdateLooping() { this->GetAspectStepper()->SetAutoRepeat( m_Looping ); } void QmitkMovieMaker::UpdateDirection() { mitk::Stepper* stepper = this->GetAspectStepper(); switch ( m_Direction ) { case 0: stepper->InverseDirectionOff(); stepper->PingPongOff(); break; case 1: stepper->InverseDirectionOn(); stepper->PingPongOff(); break; case 2: stepper->PingPongOn(); break; } } mitk::Stepper* QmitkMovieMaker::GetAspectStepper() { if (m_Aspect == 0) { m_Stepper = NULL; return this->GetSpatialController()->GetSlice(); } else if (m_Aspect == 1) { m_Stepper = NULL; return this->GetTemporalController()->GetTime(); } else if (m_Aspect == 2) { if (m_Stepper.IsNull()) { int rel = m_Controls->spatialTimeRelation->value(); int timeRepeat =1 ; int sliceRepeat = 1; if (rel < 0 ) { sliceRepeat = -rel; } else if (rel > 0) { timeRepeat = rel; } m_Stepper = mitk::MultiStepper::New(); m_Stepper->AddStepper(this->GetSpatialController()->GetSlice(),sliceRepeat); m_Stepper->AddStepper(this->GetTemporalController()->GetTime(),timeRepeat); } return m_Stepper.GetPointer(); } else { // should never get here return 0; } } void QmitkMovieMaker::GenerateMovie() { emit StartBlockControls(); // provide the movie generator with the stepper and rotate the camera each step mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New(); if ( movieGenerator.IsNotNull() ) { movieGenerator->SetStepper( this->GetAspectStepper() ); movieGenerator->SetRenderer( mitk::GlobalInteraction::GetInstance()->GetFocus() ); QString movieFileName = QFileDialog::getSaveFileName( QString::null, "Movie (*.avi)", 0, "movie file dialog", "Choose a file name" ); if(movieFileName.isEmpty() == false) { movieGenerator->SetFileName( movieFileName.ascii() ); movieGenerator->WriteMovie(); } } else { std::cerr << "Either mitk::MovieGenerator is not implemented for your"; std::cerr << " platform or an error occurred during"; std::cerr << " mitk::MovieGenerator::New()" << std::endl; } emit EndBlockControls(); } void QmitkMovieMaker::GenerateScreenshot() { emit StartBlockControls(); CommonFunctionality::SaveScreenshot( mitk::GlobalInteraction::GetInstance()->GetFocus()->GetRenderWindow() ); emit EndBlockControls(); } <|endoftext|>
<commit_before>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitCore * File: $Id: RooAcceptReject.cc,v 1.20 2001/11/07 01:56:06 verkerke Exp $ * Authors: * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu * History: * 16-May-2000 DK Created initial version * * Copyright (C) 2001 Stanford University *****************************************************************************/ // -- CLASS DESCRIPTION [AUX] -- // A class description belongs here... //#include "BaBar/BaBar.hh" #include "RooFitCore/RooAcceptReject.hh" #include "RooFitCore/RooAbsReal.hh" #include "RooFitCore/RooCategory.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooDataSet.hh" #include "RooFitCore/RooRandom.hh" #include "TString.h" #include "TIterator.h" #include <assert.h> ClassImp(RooAcceptReject) ; static const char rcsid[] = "$Id: RooAcceptReject.cc,v 1.20 2001/11/07 01:56:06 verkerke Exp $"; RooAcceptReject::RooAcceptReject(const RooAbsReal &func, const RooArgSet &genVars, const RooAbsReal* maxFuncVal, Bool_t verbose) : TNamed(func), _cloneSet(0), _funcClone(0), _verbose(verbose), _funcMaxVal(maxFuncVal) { // Initialize an accept-reject generator for the specified distribution function, // which must be non-negative but does not need to be normalized over the // variables to be generated, genVars. The function and its dependents are // cloned and so will not be disturbed during the generation process. // Clone the function and all nodes that it depends on so that this generator // is independent of any existing objects. RooArgSet nodes(func,func.GetName()); _cloneSet= (RooArgSet*) nodes.snapshot(kTRUE); // Find the clone in the snapshot list _funcClone = (RooAbsReal*)_cloneSet->find(func.GetName()); // Check that each argument is fundamental, and separate them into // sets of categories and reals. Check that the area of the generating // space is finite. _realSampleDim= 0; _catSampleMult= 1; _isValid= kTRUE; TIterator *iterator= genVars.createIterator(); const RooAbsArg *found(0),*arg(0); while(arg= (const RooAbsArg*)iterator->Next()) { if(arg->isDerived()) { cout << fName << "::" << ClassName() << ": cannot generate values for derived \"" << arg->GetName() << "\"" << endl; _isValid= kFALSE; continue; } // look for this argument in the generating function's dependents found= (const RooAbsArg*)_cloneSet->find(arg->GetName()); if(found) { arg= found; const RooAbsCategory * cat = dynamic_cast<const RooAbsCategory*>(found) ; if (cat) { _catSampleMult *= cat->numTypes() ; } else { _realSampleDim++; } } else { // clone any variables we generate that we haven't cloned already arg= _cloneSet->addClone(*arg); } assert(0 != arg); // is this argument a category or a real? const RooCategory *catVar= dynamic_cast<const RooCategory*>(arg); const RooRealVar *realVar= dynamic_cast<const RooRealVar*>(arg); if(0 != catVar) { _catVars.add(*catVar); } else if(0 != realVar) { if(realVar->hasFitMin() && realVar->hasFitMax()) { _realVars.add(*realVar); } else { cout << fName << "::" << ClassName() << ": cannot generate values for \"" << realVar->GetName() << "\" with unbound range" << endl; _isValid= kFALSE; } } else { cout << fName << "::" << ClassName() << ": cannot generate values for \"" << arg->GetName() << "\" with unexpected type" << endl; _isValid= kFALSE; } } delete iterator; if(!_isValid) { cout << fName << "::" << ClassName() << ": constructor failed with errors" << endl; return; } // calculate the minimum number of trials needed to estimate our integral and max value if (!_funcMaxVal) { if(_realSampleDim > _maxSampleDim) { _minTrials= _minTrialsArray[_maxSampleDim]*_catSampleMult; cout << fName << "::" << ClassName() << ": WARNING: generating " << _realSampleDim << " variables with accept-reject may not be accurate" << endl; } else { _minTrials= _minTrialsArray[_realSampleDim]*_catSampleMult; } } else { // No trials needed if we know the maximum a priori _minTrials=0 ; } // print a verbose summary of our configuration, if requested if(_verbose) { cout << fName << "::" << ClassName() << ":" << endl << " Initializing accept-reject generator for" << endl << " "; _funcClone->Print(); if (_funcMaxVal) { cout << " Function maximum provided, no trial sampling performed" << endl ; } else { cout << " Real sampling dimension is " << _realSampleDim << endl; cout << " Category sampling multiplier is " << _catSampleMult << endl ; cout << " Min sampling trials is " << _minTrials << endl; } cout << " Will generate category vars "; TString indent(" "); _catVars.printToStream(cout,Standard,indent); cout << " Will generate real vars "; _realVars.printToStream(cout,Standard,indent); } // create a fundamental type for storing function values _funcValStore= dynamic_cast<RooRealVar*>(_funcClone->createFundamental()); assert(0 != _funcValStore); // create a new dataset to cache trial events and function values RooArgSet cacheArgs(_catVars); cacheArgs.add(_realVars); cacheArgs.add(*_funcValStore); _cache= new RooDataSet("cache","Accept-Reject Event Cache",cacheArgs); assert(0 != _cache); // attach our function clone to the cache dataset const RooArgSet *cacheVars= _cache->get(); assert(0 != cacheVars); _funcClone->recursiveRedirectServers(*cacheVars,kFALSE); // update ours sets of category and real args to refer to the cache dataset const RooArgSet *dataVars= _cache->get(); _catVars.replace(*dataVars); _realVars.replace(*dataVars); // find the function value in the dataset _funcValPtr= (RooRealVar*)dataVars->find(_funcValStore->GetName()); // create iterators for the new sets _nextCatVar= _catVars.createIterator(); _nextRealVar= _realVars.createIterator(); assert(0 != _nextCatVar && 0 != _nextRealVar); // initialize our statistics _maxFuncVal= 0; _funcSum= 0; _totalEvents= 0; _eventsUsed= 0; } RooAcceptReject::~RooAcceptReject() { delete _cache ; delete _nextCatVar; delete _nextRealVar; delete _cloneSet; delete _funcValStore; } void RooAcceptReject::printToStream(ostream &os, PrintOption opt, TString indent) const { oneLinePrint(os,*this); } void RooAcceptReject::attachParameters(const RooArgSet& vars) { // Reattach original parameters to function clone RooArgSet newParams(vars) ; newParams.remove(*_cache->get(),kTRUE,kTRUE) ; _funcClone->recursiveRedirectServers(newParams) ; } const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining) { // Return a pointer to a generated event. The caller does not own the event and it // will be overwritten by a subsequent call. The input parameter 'remaining' should // contain your best guess at the total number of subsequent events you will request. // are we actually generating anything? (the cache always contains at least our function value) const RooArgSet *event= _cache->get(); if(event->getSize() == 1) return event; if (!_funcMaxVal) { // Generation with empirical maximum determination // first generate enough events to get reasonable estimates for the integral and // maximum function value while(_totalEvents < _minTrials) { addEventToCache(); // Limit cache size to 1M events if (_cache->numEntries()>1000000) { cout << "RooAcceptReject::generateEvent: resetting event cache" << endl ; _cache->reset() ; _eventsUsed = 0 ; } } event= 0; while(0 == event) { // Use any cached events first event= nextAcceptedEvent(); if(event) break; // When we have used up the cache, start a new cache and add // some more events to it. _cache->reset(); _eventsUsed= 0; // Calculate how many more events to generate using our best estimate of our efficiency. // Always generate at least one more event so we don't get stuck. if(_totalEvents*_maxFuncVal <= 0) { cout << "RooAcceptReject::generateEvent: cannot estimate efficiency...giving up" << endl; return 0; } Double_t eff= _funcSum/(_totalEvents*_maxFuncVal); Int_t extra= 1 + (Int_t)(1.05*remaining/eff); if(_verbose) { cout << "RooAcceptReject::generateEvent: adding " << extra << " events to the cache" << endl; } Double_t oldMax(_maxFuncVal); while(extra--) addEventToCache(); if(_verbose && (_maxFuncVal > oldMax)) { cout << "RooAcceptReject::generateEvent: estimated function maximum increased from " << oldMax << " to " << _maxFuncVal << endl; } } // Limit cache size to 1M events if (_eventsUsed>1000000) { _cache->reset() ; _eventsUsed = 0 ; } } else { // Generation with a priori maximum knowledge _maxFuncVal = _funcMaxVal->getVal() ; // Generate enough trials to produce a single accepted event event = 0 ; while(0==event) { addEventToCache() ; event = nextAcceptedEvent() ; } } return event; } const RooArgSet *RooAcceptReject::nextAcceptedEvent() { // Scan through events in the cache which have not been used yet, // looking for the first accepted one which is added to the specified // container. Return a pointer to the accepted event, or else zero // if we use up the cache before we accept an event. The caller does // not own the event and it will be overwritten by a subsequent call. const RooArgSet *event(0); while(event= _cache->get(_eventsUsed)) { _eventsUsed++ ; // accept this cached event? Double_t r= RooRandom::uniform(); if(r*_maxFuncVal > _funcValPtr->getVal()) continue; // copy this event into the output container if(_verbose && (_eventsUsed%1000==0)) { cerr << "RooAcceptReject: accepted event (used " << _eventsUsed << " of " << _cache->numEntries() << " so far)" << endl; } break; } return event; } void RooAcceptReject::addEventToCache() { // Add a trial event to our cache and update our estimates // of the function maximum value and integral. // randomize each discrete argument _nextCatVar->Reset(); RooCategory *cat(0); while(cat= (RooCategory*)_nextCatVar->Next()) cat->randomize(); // randomize each real argument _nextRealVar->Reset(); RooRealVar *real(0); while(real= (RooRealVar*)_nextRealVar->Next()) real->randomize(); // calculate and store our function value at this new point Double_t val= _funcClone->getVal(); _funcValPtr->setVal(val); // Update the estimated integral and maximum value. Increase our // maximum estimate slightly to give a safety margin with a // corresponding loss of efficiency. if(val > _maxFuncVal) _maxFuncVal= 1.05*val; _funcSum+= val; // fill a new entry in our cache dataset for this point _cache->fill(); _totalEvents++; if (_verbose &&_totalEvents%10000==0) { cerr << "RooAcceptReject: generated " << _totalEvents << " events so far." << endl ; } } Double_t RooAcceptReject::getFuncMax() { // Generate the minimum required number of samples for a reliable maximum estimate while(_totalEvents < _minTrials) { addEventToCache(); // Limit cache size to 1M events if (_cache->numEntries()>1000000) { cout << "RooAcceptReject::getFuncMax: resetting event cache" << endl ; _cache->reset() ; _eventsUsed = 0 ; } } return _maxFuncVal ; } const int RooAcceptReject::_maxSampleDim= 3, RooAcceptReject::_minTrialsArray[]= { 0,1000,100000,10000000 }; <commit_msg><commit_after>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitCore * File: $Id: RooAcceptReject.cc,v 1.21 2001/11/27 23:19:04 verkerke Exp $ * Authors: * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu * History: * 16-May-2000 DK Created initial version * * Copyright (C) 2001 Stanford University *****************************************************************************/ // -- CLASS DESCRIPTION [AUX] -- // A class description belongs here... //#include "BaBar/BaBar.hh" #include "RooFitCore/RooAcceptReject.hh" #include "RooFitCore/RooAbsReal.hh" #include "RooFitCore/RooCategory.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooDataSet.hh" #include "RooFitCore/RooRandom.hh" #include "TString.h" #include "TIterator.h" #include <assert.h> ClassImp(RooAcceptReject) ; static const char rcsid[] = "$Id: RooAcceptReject.cc,v 1.21 2001/11/27 23:19:04 verkerke Exp $"; RooAcceptReject::RooAcceptReject(const RooAbsReal &func, const RooArgSet &genVars, const RooAbsReal* maxFuncVal, Bool_t verbose) : TNamed(func), _cloneSet(0), _funcClone(0), _verbose(verbose), _funcMaxVal(maxFuncVal) { // Initialize an accept-reject generator for the specified distribution function, // which must be non-negative but does not need to be normalized over the // variables to be generated, genVars. The function and its dependents are // cloned and so will not be disturbed during the generation process. // Clone the function and all nodes that it depends on so that this generator // is independent of any existing objects. RooArgSet nodes(func,func.GetName()); _cloneSet= (RooArgSet*) nodes.snapshot(kTRUE); // Find the clone in the snapshot list _funcClone = (RooAbsReal*)_cloneSet->find(func.GetName()); // Check that each argument is fundamental, and separate them into // sets of categories and reals. Check that the area of the generating // space is finite. _realSampleDim= 0; _catSampleMult= 1; _isValid= kTRUE; TIterator *iterator= genVars.createIterator(); const RooAbsArg *found(0),*arg(0); while(arg= (const RooAbsArg*)iterator->Next()) { if(arg->isDerived()) { cout << fName << "::" << ClassName() << ": cannot generate values for derived \"" << arg->GetName() << "\"" << endl; _isValid= kFALSE; continue; } // look for this argument in the generating function's dependents found= (const RooAbsArg*)_cloneSet->find(arg->GetName()); if(found) { arg= found; const RooAbsCategory * cat = dynamic_cast<const RooAbsCategory*>(found) ; if (cat) { _catSampleMult *= cat->numTypes() ; } else { _realSampleDim++; } } else { // clone any variables we generate that we haven't cloned already arg= _cloneSet->addClone(*arg); } assert(0 != arg); // is this argument a category or a real? const RooCategory *catVar= dynamic_cast<const RooCategory*>(arg); const RooRealVar *realVar= dynamic_cast<const RooRealVar*>(arg); if(0 != catVar) { _catVars.add(*catVar); } else if(0 != realVar) { if(realVar->hasFitMin() && realVar->hasFitMax()) { _realVars.add(*realVar); } else { cout << fName << "::" << ClassName() << ": cannot generate values for \"" << realVar->GetName() << "\" with unbound range" << endl; _isValid= kFALSE; } } else { cout << fName << "::" << ClassName() << ": cannot generate values for \"" << arg->GetName() << "\" with unexpected type" << endl; _isValid= kFALSE; } } delete iterator; if(!_isValid) { cout << fName << "::" << ClassName() << ": constructor failed with errors" << endl; return; } // calculate the minimum number of trials needed to estimate our integral and max value if (!_funcMaxVal) { if(_realSampleDim > _maxSampleDim) { _minTrials= _minTrialsArray[_maxSampleDim]*_catSampleMult; cout << fName << "::" << ClassName() << ": WARNING: generating " << _realSampleDim << " variables with accept-reject may not be accurate" << endl; } else { _minTrials= _minTrialsArray[_realSampleDim]*_catSampleMult; } } else { // No trials needed if we know the maximum a priori _minTrials=0 ; } // print a verbose summary of our configuration, if requested if(_verbose) { cout << fName << "::" << ClassName() << ":" << endl << " Initializing accept-reject generator for" << endl << " "; _funcClone->Print(); if (_funcMaxVal) { cout << " Function maximum provided, no trial sampling performed" << endl ; } else { cout << " Real sampling dimension is " << _realSampleDim << endl; cout << " Category sampling multiplier is " << _catSampleMult << endl ; cout << " Min sampling trials is " << _minTrials << endl; } cout << " Will generate category vars "; TString indent(" "); _catVars.printToStream(cout,Standard,indent); cout << " Will generate real vars "; _realVars.printToStream(cout,Standard,indent); } // create a fundamental type for storing function values _funcValStore= dynamic_cast<RooRealVar*>(_funcClone->createFundamental()); assert(0 != _funcValStore); // create a new dataset to cache trial events and function values RooArgSet cacheArgs(_catVars); cacheArgs.add(_realVars); cacheArgs.add(*_funcValStore); _cache= new RooDataSet("cache","Accept-Reject Event Cache",cacheArgs); assert(0 != _cache); // attach our function clone to the cache dataset const RooArgSet *cacheVars= _cache->get(); assert(0 != cacheVars); _funcClone->recursiveRedirectServers(*cacheVars,kFALSE); // update ours sets of category and real args to refer to the cache dataset const RooArgSet *dataVars= _cache->get(); _catVars.replace(*dataVars); _realVars.replace(*dataVars); // find the function value in the dataset _funcValPtr= (RooRealVar*)dataVars->find(_funcValStore->GetName()); // create iterators for the new sets _nextCatVar= _catVars.createIterator(); _nextRealVar= _realVars.createIterator(); assert(0 != _nextCatVar && 0 != _nextRealVar); // initialize our statistics _maxFuncVal= 0; _funcSum= 0; _totalEvents= 0; _eventsUsed= 0; } RooAcceptReject::~RooAcceptReject() { delete _cache ; delete _nextCatVar; delete _nextRealVar; delete _cloneSet; delete _funcValStore; } void RooAcceptReject::printToStream(ostream &os, PrintOption opt, TString indent) const { oneLinePrint(os,*this); } void RooAcceptReject::attachParameters(const RooArgSet& vars) { // Reattach original parameters to function clone RooArgSet newParams(vars) ; newParams.remove(*_cache->get(),kTRUE,kTRUE) ; _funcClone->recursiveRedirectServers(newParams) ; } const RooArgSet *RooAcceptReject::generateEvent(UInt_t remaining) { // Return a pointer to a generated event. The caller does not own the event and it // will be overwritten by a subsequent call. The input parameter 'remaining' should // contain your best guess at the total number of subsequent events you will request. // are we actually generating anything? (the cache always contains at least our function value) const RooArgSet *event= _cache->get(); if(event->getSize() == 1) return event; if (!_funcMaxVal) { // Generation with empirical maximum determination // first generate enough events to get reasonable estimates for the integral and // maximum function value while(_totalEvents < _minTrials) { addEventToCache(); // Limit cache size to 1M events if (_cache->numEntries()>1000000) { cout << "RooAcceptReject::generateEvent: resetting event cache" << endl ; _cache->reset() ; _eventsUsed = 0 ; } } event= 0; while(0 == event) { // Use any cached events first event= nextAcceptedEvent(); if(event) break; // When we have used up the cache, start a new cache and add // some more events to it. _cache->reset(); _eventsUsed= 0; // Calculate how many more events to generate using our best estimate of our efficiency. // Always generate at least one more event so we don't get stuck. if(_totalEvents*_maxFuncVal <= 0) { cout << "RooAcceptReject::generateEvent: cannot estimate efficiency...giving up" << endl; return 0; } Double_t eff= _funcSum/(_totalEvents*_maxFuncVal); Int_t extra= 1 + (Int_t)(1.05*remaining/eff); if(_verbose) { cout << "RooAcceptReject::generateEvent: adding " << extra << " events to the cache" << endl; } Double_t oldMax(_maxFuncVal); while(extra--) addEventToCache(); if(_verbose && (_maxFuncVal > oldMax)) { cout << "RooAcceptReject::generateEvent: estimated function maximum increased from " << oldMax << " to " << _maxFuncVal << endl; } } // Limit cache size to 1M events if (_eventsUsed>1000000) { _cache->reset() ; _eventsUsed = 0 ; } } else { // Generation with a priori maximum knowledge _maxFuncVal = _funcMaxVal->getVal() ; // Generate enough trials to produce a single accepted event event = 0 ; while(0==event) { addEventToCache() ; event = nextAcceptedEvent() ; } } return event; } const RooArgSet *RooAcceptReject::nextAcceptedEvent() { // Scan through events in the cache which have not been used yet, // looking for the first accepted one which is added to the specified // container. Return a pointer to the accepted event, or else zero // if we use up the cache before we accept an event. The caller does // not own the event and it will be overwritten by a subsequent call. const RooArgSet *event(0); while(event= _cache->get(_eventsUsed)) { _eventsUsed++ ; // accept this cached event? Double_t r= RooRandom::uniform(); if(r*_maxFuncVal > _funcValPtr->getVal()) continue; // copy this event into the output container if(_verbose && (_eventsUsed%1000==0)) { cerr << "RooAcceptReject: accepted event (used " << _eventsUsed << " of " << _cache->numEntries() << " so far)" << endl; } break; } return event; } void RooAcceptReject::addEventToCache() { // Add a trial event to our cache and update our estimates // of the function maximum value and integral. // randomize each discrete argument _nextCatVar->Reset(); RooCategory *cat(0); while(cat= (RooCategory*)_nextCatVar->Next()) cat->randomize(); // randomize each real argument _nextRealVar->Reset(); RooRealVar *real(0); while(real= (RooRealVar*)_nextRealVar->Next()) real->randomize(); // calculate and store our function value at this new point Double_t val= _funcClone->getVal(); _funcValPtr->setVal(val); // Update the estimated integral and maximum value. Increase our // maximum estimate slightly to give a safety margin with a // corresponding loss of efficiency. if(val > _maxFuncVal) _maxFuncVal= 1.05*val; _funcSum+= val; // fill a new entry in our cache dataset for this point _cache->fill(); _totalEvents++; if (_verbose &&_totalEvents%10000==0) { cerr << "RooAcceptReject: generated " << _totalEvents << " events so far." << endl ; } } Double_t RooAcceptReject::getFuncMax() { // Generate the minimum required number of samples for a reliable maximum estimate while(_totalEvents < _minTrials) { addEventToCache(); // Limit cache size to 1M events if (_cache->numEntries()>1000000) { cout << "RooAcceptReject::getFuncMax: resetting event cache" << endl ; _cache->reset() ; _eventsUsed = 0 ; } } return _maxFuncVal ; } const int RooAcceptReject::_maxSampleDim= 3, RooAcceptReject::_minTrialsArray[]= { 100,1000,100000,10000000 }; <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <math.h> #include <stdlib.h> #include <string.h> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/acm_random.h" #include "aom/aom_integer.h" #include "aom_dsp/bitreader.h" #include "aom_dsp/bitwriter.h" using libaom_test::ACMRandom; TEST(AV1, TestAccounting) { const int kBufferSize = 10000; const int kSymbols = 1024; aom_writer bw; uint8_t bw_buffer[kBufferSize]; aom_start_encode(&bw, bw_buffer); for (int i = 0; i < kSymbols; i++) { aom_write(&bw, 0, 32); aom_write(&bw, 0, 32); aom_write(&bw, 0, 32); } aom_stop_encode(&bw); aom_reader br; aom_reader_init(&br, bw_buffer, kBufferSize, NULL, NULL); Accounting accounting; aom_accounting_init(&accounting); br.accounting = &accounting; for (int i = 0; i < kSymbols; i++) { aom_read(&br, 32, "A"); } // Consecutive symbols that are the same are coalesced. GTEST_ASSERT_EQ(accounting.syms.num_syms, 1); GTEST_ASSERT_EQ(accounting.syms.syms[0].samples, (unsigned int)kSymbols); aom_accounting_reset(&accounting); GTEST_ASSERT_EQ(accounting.syms.num_syms, 0); // Should record 2 * kSymbols accounting symbols. aom_reader_init(&br, bw_buffer, kBufferSize, NULL, NULL); br.accounting = &accounting; for (int i = 0; i < kSymbols; i++) { aom_read(&br, 32, "A"); aom_read(&br, 32, "B"); aom_read(&br, 32, "B"); } GTEST_ASSERT_EQ(accounting.syms.num_syms, kSymbols * 2); uint32_t tell_frac = aom_reader_tell_frac(&br); for (int i = 0; i < accounting.syms.num_syms; i++) { tell_frac -= accounting.syms.syms[i].bits; } GTEST_ASSERT_EQ(tell_frac, 0U); GTEST_ASSERT_EQ(aom_accounting_dictionary_lookup(&accounting, "A"), aom_accounting_dictionary_lookup(&accounting, "A")); // Check for collisions. The current aom_accounting_hash function returns // the same hash code for AB and BA. GTEST_ASSERT_NE(aom_accounting_dictionary_lookup(&accounting, "AB"), aom_accounting_dictionary_lookup(&accounting, "BA")); } <commit_msg>accounting_test: fix read of uninitialized data<commit_after>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <math.h> #include <stdlib.h> #include <string.h> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/acm_random.h" #include "aom/aom_integer.h" #include "aom_dsp/bitreader.h" #include "aom_dsp/bitwriter.h" using libaom_test::ACMRandom; TEST(AV1, TestAccounting) { const int kBufferSize = 10000; const int kSymbols = 1024; aom_writer bw; uint8_t bw_buffer[kBufferSize]; aom_start_encode(&bw, bw_buffer); for (int i = 0; i < kSymbols; i++) { aom_write(&bw, 0, 32); aom_write(&bw, 0, 32); aom_write(&bw, 0, 32); } aom_stop_encode(&bw); aom_reader br; aom_reader_init(&br, bw_buffer, bw.pos, NULL, NULL); Accounting accounting; aom_accounting_init(&accounting); br.accounting = &accounting; for (int i = 0; i < kSymbols; i++) { aom_read(&br, 32, "A"); } // Consecutive symbols that are the same are coalesced. GTEST_ASSERT_EQ(accounting.syms.num_syms, 1); GTEST_ASSERT_EQ(accounting.syms.syms[0].samples, (unsigned int)kSymbols); aom_accounting_reset(&accounting); GTEST_ASSERT_EQ(accounting.syms.num_syms, 0); // Should record 2 * kSymbols accounting symbols. aom_reader_init(&br, bw_buffer, bw.pos, NULL, NULL); br.accounting = &accounting; for (int i = 0; i < kSymbols; i++) { aom_read(&br, 32, "A"); aom_read(&br, 32, "B"); aom_read(&br, 32, "B"); } GTEST_ASSERT_EQ(accounting.syms.num_syms, kSymbols * 2); uint32_t tell_frac = aom_reader_tell_frac(&br); for (int i = 0; i < accounting.syms.num_syms; i++) { tell_frac -= accounting.syms.syms[i].bits; } GTEST_ASSERT_EQ(tell_frac, 0U); GTEST_ASSERT_EQ(aom_accounting_dictionary_lookup(&accounting, "A"), aom_accounting_dictionary_lookup(&accounting, "A")); // Check for collisions. The current aom_accounting_hash function returns // the same hash code for AB and BA. GTEST_ASSERT_NE(aom_accounting_dictionary_lookup(&accounting, "AB"), aom_accounting_dictionary_lookup(&accounting, "BA")); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { class AqSegmentTest : public ::libaom_test::EncoderTest, public ::libaom_test::CodecTestWith2Params<libaom_test::TestMode, int> { protected: AqSegmentTest() : EncoderTest(GET_PARAM(0)) {} virtual ~AqSegmentTest() {} virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); aq_mode_ = 0; } virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video, ::libaom_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(AOME_SET_CPUUSED, set_cpu_used_); encoder->Control(AV1E_SET_AQ_MODE, aq_mode_); encoder->Control(AOME_SET_MAX_INTRA_BITRATE_PCT, 100); } } int set_cpu_used_; int aq_mode_; }; // Validate that this AQ segmentation mode (AQ=1, variance_ap) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ1) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 1; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } // Validate that this AQ segmentation mode (AQ=2, complexity_aq) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ2) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 2; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } // Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ3) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 3; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } AV1_INSTANTIATE_TEST_CASE(AqSegmentTest, ::testing::Values(::libaom_test::kRealTime, ::libaom_test::kOnePassGood), ::testing::Range(3, 9)); } // namespace <commit_msg>Add unit test for delta-q (aq-mode=4)<commit_after>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include "./aom_config.h" #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { class AqSegmentTest : public ::libaom_test::EncoderTest, public ::libaom_test::CodecTestWith2Params<libaom_test::TestMode, int> { protected: AqSegmentTest() : EncoderTest(GET_PARAM(0)) {} virtual ~AqSegmentTest() {} virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); aq_mode_ = 0; } virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video, ::libaom_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(AOME_SET_CPUUSED, set_cpu_used_); encoder->Control(AV1E_SET_AQ_MODE, aq_mode_); encoder->Control(AOME_SET_MAX_INTRA_BITRATE_PCT, 100); } } int set_cpu_used_; int aq_mode_; }; // Validate that this AQ segmentation mode (AQ=1, variance_ap) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ1) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 1; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } // Validate that this AQ segmentation mode (AQ=2, complexity_aq) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ2) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 2; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } // Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ3) { cfg_.rc_min_quantizer = 8; cfg_.rc_max_quantizer = 56; cfg_.rc_end_usage = AOM_CBR; cfg_.g_lag_in_frames = 0; cfg_.rc_buf_initial_sz = 500; cfg_.rc_buf_optimal_sz = 500; cfg_.rc_buf_sz = 1000; cfg_.rc_target_bitrate = 300; aq_mode_ = 3; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } #if CONFIG_DELTA_Q // Validate that this AQ mode (AQ=4, delta q) // encodes and decodes without a mismatch. TEST_P(AqSegmentTest, TestNoMisMatchAQ4) { cfg_.rc_end_usage = AOM_CQ; aq_mode_ = 4; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 100); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); } #endif AV1_INSTANTIATE_TEST_CASE(AqSegmentTest, ::testing::Values(::libaom_test::kRealTime, ::libaom_test::kOnePassGood), ::testing::Range(3, 9)); } // namespace <|endoftext|>
<commit_before>#include "Globals.h" #include "App.h" #include "ModuleInput.h" #include "ModuleCamera3D.h" #include "EditorUI.h" #include "Game.h" #include "ModuleWindow.h" #include "Cursor.h" #include "imgui.h" #include "JSONLoader.h" ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled) { SetName("Camera3D"); CalculateViewMatrix(); // Normalized vectors that define the direction of X, Y and Z X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); // Position of the camera X, Y and Z Position = vec3(0.0f, 0.0f, 0.0f); // Reference point in which is rotating from Reference = vec3(0.0f, 0.0f, 0.0f); Focus(vec3(0.0f, 0.0f, 0.0f), 10); } ModuleCamera3D::~ModuleCamera3D() {} bool ModuleCamera3D::Awake() { bool ret = true; LOG_OUTPUT("Loading Camera3D"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { bool ret = true; LOG_OUTPUT("Setting up the camera"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { bool ret = true; LOG_OUTPUT("Cleaning camera"); return ret; } void ModuleCamera3D::OnLoadConfig(JSON_Doc * config) { mouse_sensitivity = config->GetNumber("camera.mouse_sensitivity", 0.25f); wheel_speed = config->GetNumber("camera.wheel_speed", 5.0f); camera_speed = config->GetNumber("camera.camera_speed", 20.0f); } void ModuleCamera3D::OnSaveConfig(JSON_Doc * config) { config->SetNumber("camera.mouse_sensitivity", mouse_sensitivity); config->SetNumber("camera.wheel_speed", wheel_speed); config->SetNumber("camera.camera_speed", camera_speed); } void ModuleCamera3D::SetMouseSensitivity(const float& set) { mouse_sensitivity = set; } void ModuleCamera3D::SetWheelSpeed(const float& set) { wheel_speed = set; } void ModuleCamera3D::SetCameraSpeed(const float& set) { camera_speed = set; } const float ModuleCamera3D::GetMouseSensitivity() const { return mouse_sensitivity; } const float ModuleCamera3D::GetWheelSpeed() const { return wheel_speed; } const float ModuleCamera3D::GetCameraSpeed() const { return camera_speed; } // ----------------------------------------------------------------- bool ModuleCamera3D::Update() { bool ret = true; float speed = camera_speed * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT)) speed = camera_speed/2 * App->GetDT(); if (IsMouseInsideWindow()) { mouse_movement = true; } // Mouse motion ---------------- if (mouse_movement) { if (App->input->GetMouseWheel() == 1) { MoveFront(wheel_speed); } else if (App->input->GetMouseWheel() == -1) { MoveBack(wheel_speed); } else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { App->window->GetCursor()->Hand(); if (App->input->GetKeyRepeat(SDL_SCANCODE_Z)) MoveUp(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_X)) MoveDown(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_W)) MoveFront(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_S)) MoveBack(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_A)) MoveLeft(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_D)) MoveRight(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT)) { Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); App->window->GetCursor()->SizeAll(); } else { Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); } } else { mouse_movement = false; } } if (App->input->GetKeyDown("f")) { Focus(vec3(0, 0, 0), 10); } // Recalculate matrix ------------- CalculateViewMatrix(); return ret; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if (!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt(const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- const float* ModuleCamera3D::GetViewMatrix() const { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); } void ModuleCamera3D::MoveFront(const float& speed) { vec3 newPos(0, 0, 0); newPos -= Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveBack(const float& speed) { vec3 newPos(0, 0, 0); newPos += Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveLeft(const float& speed) { vec3 newPos(0, 0, 0); newPos -= X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveRight(const float& speed) { vec3 newPos(0, 0, 0); newPos += X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveUp(const float& speed) { vec3 newPos(0, 0, 0); newPos.y += speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveDown(const float& speed) { vec3 newPos(0, 0, 0); newPos.y -= speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::Focus(const vec3& focus, const float& distance) { Reference = focus; Position = Reference + Z * distance; } void ModuleCamera3D::Orbit(const vec3& orbit_center, const float& motion_x, const float& motion_y) { Reference = orbit_center; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; // Rotate arround the y axis X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; // Rotate arround the X direction Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } void ModuleCamera3D::Rotate(const float& motion_x, const float& motion_y) { Reference = Position; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } const bool ModuleCamera3D::IsMouseInsideWindow() const { return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect()); } <commit_msg>Now the orbit movement works with left click<commit_after>#include "Globals.h" #include "App.h" #include "ModuleInput.h" #include "ModuleCamera3D.h" #include "EditorUI.h" #include "Game.h" #include "ModuleWindow.h" #include "Cursor.h" #include "imgui.h" #include "JSONLoader.h" ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled) { SetName("Camera3D"); CalculateViewMatrix(); // Normalized vectors that define the direction of X, Y and Z X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); // Position of the camera X, Y and Z Position = vec3(0.0f, 0.0f, 0.0f); // Reference point in which is rotating from Reference = vec3(0.0f, 0.0f, 0.0f); Focus(vec3(0.0f, 0.0f, 0.0f), 10); } ModuleCamera3D::~ModuleCamera3D() {} bool ModuleCamera3D::Awake() { bool ret = true; LOG_OUTPUT("Loading Camera3D"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { bool ret = true; LOG_OUTPUT("Setting up the camera"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { bool ret = true; LOG_OUTPUT("Cleaning camera"); return ret; } void ModuleCamera3D::OnLoadConfig(JSON_Doc * config) { mouse_sensitivity = config->GetNumber("camera.mouse_sensitivity", 0.25f); wheel_speed = config->GetNumber("camera.wheel_speed", 5.0f); camera_speed = config->GetNumber("camera.camera_speed", 20.0f); } void ModuleCamera3D::OnSaveConfig(JSON_Doc * config) { config->SetNumber("camera.mouse_sensitivity", mouse_sensitivity); config->SetNumber("camera.wheel_speed", wheel_speed); config->SetNumber("camera.camera_speed", camera_speed); } void ModuleCamera3D::SetMouseSensitivity(const float& set) { mouse_sensitivity = set; } void ModuleCamera3D::SetWheelSpeed(const float& set) { wheel_speed = set; } void ModuleCamera3D::SetCameraSpeed(const float& set) { camera_speed = set; } const float ModuleCamera3D::GetMouseSensitivity() const { return mouse_sensitivity; } const float ModuleCamera3D::GetWheelSpeed() const { return wheel_speed; } const float ModuleCamera3D::GetCameraSpeed() const { return camera_speed; } // ----------------------------------------------------------------- bool ModuleCamera3D::Update() { bool ret = true; float speed = camera_speed * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT)) speed = camera_speed/2 * App->GetDT(); if (IsMouseInsideWindow()) { mouse_movement = true; } // Mouse motion ---------------- if (mouse_movement) { if (App->input->GetMouseWheel() == 1) { MoveFront(wheel_speed); } else if (App->input->GetMouseWheel() == -1) { MoveBack(wheel_speed); } else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { App->window->GetCursor()->Hand(); if (App->input->GetKeyRepeat(SDL_SCANCODE_Z)) MoveUp(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_X)) MoveDown(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_W)) MoveFront(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_S)) MoveBack(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_A)) MoveLeft(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_D)) MoveRight(speed); else { Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); } } else if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT) { if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT)) { Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); App->window->GetCursor()->SizeAll(); } } else { mouse_movement = false; } } if (App->input->GetKeyDown("f")) { Focus(vec3(0, 0, 0), 10); } // Recalculate matrix ------------- CalculateViewMatrix(); return ret; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if (!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt(const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- const float* ModuleCamera3D::GetViewMatrix() const { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); } void ModuleCamera3D::MoveFront(const float& speed) { vec3 newPos(0, 0, 0); newPos -= Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveBack(const float& speed) { vec3 newPos(0, 0, 0); newPos += Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveLeft(const float& speed) { vec3 newPos(0, 0, 0); newPos -= X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveRight(const float& speed) { vec3 newPos(0, 0, 0); newPos += X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveUp(const float& speed) { vec3 newPos(0, 0, 0); newPos.y += speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveDown(const float& speed) { vec3 newPos(0, 0, 0); newPos.y -= speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::Focus(const vec3& focus, const float& distance) { Reference = focus; Position = Reference + Z * distance; } void ModuleCamera3D::Orbit(const vec3& orbit_center, const float& motion_x, const float& motion_y) { Reference = orbit_center; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; // Rotate arround the y axis X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; // Rotate arround the X direction Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } void ModuleCamera3D::Rotate(const float& motion_x, const float& motion_y) { Reference = Position; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } const bool ModuleCamera3D::IsMouseInsideWindow() const { return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect()); } <|endoftext|>
<commit_before><commit_msg>coverity#1209778 & coverity#1209777 Resource leak<commit_after><|endoftext|>
<commit_before>//Simplified TParticle class #include "AliHBTParticle.h" #include <TParticle.h> ClassImp(AliHBTParticle) //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(): fPdgCode(0), fPx(0), fPy(0),fPz(0),fE(0), fVx(0), fVy(0),fVz(0),fVt(0) {//empty particle } //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(Int_t pdg, Double_t px, Double_t py, Double_t pz, Double_t etot, Double_t vx, Double_t vy, Double_t vz, Double_t time): fPdgCode(pdg), fPx(px), fPy(py),fPz(pz),fE(etot), fVx(vx), fVy(vy),fVz(vz),fVt(time) { //mormal constructor if (GetPDG()) { fCalcMass = GetPDG()->Mass(); } else { Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz; if (a2 >= 0) fCalcMass = TMath::Sqrt(a2); else fCalcMass = -TMath::Sqrt(-a2); } } //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(const TParticle &p): fPdgCode(p.GetPdgCode()),fCalcMass(p.GetCalcMass()), fPx(p.Px()),fPy(p.Py()),fPz(p.Pz()),fE(p.Energy()), fVx(p.Vx()),fVy(p.Vy()),fVz(p.Vz()),fVt(p.T()) { //all copied in the initialization } //______________________________________________________________________________ const Char_t* AliHBTParticle::GetName() const { static char def[4] = "XXX"; const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode); if (ap) return ap->GetName(); else return def; } //______________________________________________________________________________ <commit_msg>Uninitialized value corrected<commit_after>//Simplified TParticle class #include "AliHBTParticle.h" #include <TParticle.h> ClassImp(AliHBTParticle) //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(): fPdgCode(0), fCalcMass(0),fPx(0), fPy(0),fPz(0),fE(0), fVx(0), fVy(0),fVz(0),fVt(0) {//empty particle } //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(Int_t pdg, Double_t px, Double_t py, Double_t pz, Double_t etot, Double_t vx, Double_t vy, Double_t vz, Double_t time): fPdgCode(pdg), fPx(px), fPy(py),fPz(pz),fE(etot), fVx(vx), fVy(vy),fVz(vz),fVt(time) { //mormal constructor if (GetPDG()) { fCalcMass = GetPDG()->Mass(); } else { Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz; if (a2 >= 0) fCalcMass = TMath::Sqrt(a2); else fCalcMass = -TMath::Sqrt(-a2); } } //______________________________________________________________________________ AliHBTParticle::AliHBTParticle(const TParticle &p): fPdgCode(p.GetPdgCode()),fCalcMass(p.GetCalcMass()), fPx(p.Px()),fPy(p.Py()),fPz(p.Pz()),fE(p.Energy()), fVx(p.Vx()),fVy(p.Vy()),fVz(p.Vz()),fVt(p.T()) { //all copied in the initialization } //______________________________________________________________________________ const Char_t* AliHBTParticle::GetName() const { static char def[4] = "XXX"; const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode); if (ap) return ap->GetName(); else return def; } //______________________________________________________________________________ <|endoftext|>
<commit_before>#ifndef NEU_ANY_LAYER_VECTOR_HPP #define NEU_ANY_LAYER_VECTOR_HPP //20150914 #include <vector> #include <neu/basic_type.hpp> #include <neu/range/algorithm.hpp> #include <neu/range/gpu_buffer_range.hpp> #include <neu/layer/traits.hpp> #include <neu/layer/any_layer.hpp> #include <neu/layer/deserialize_fwd.hpp> namespace neu { namespace layer { namespace traits { template<> class input_rank<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::input_rank(alv.front()); } }; template<> class output_rank<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::output_rank(alv.back()); } }; template<> class input_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv, rank_id ri) { return ::neu::layer::input_size(alv.front(), ri); } }; template<> class output_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv, rank_id ri) { return ::neu::layer::output_size(alv.back(), ri); } }; template<> class batch_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::batch_size(alv.front()); } }; template<> class test_forward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call( std::vector<neu::layer::any_layer>& layers, std::size_t batch_size, InputRange const& initial_input, OutputRange& result_output, boost::compute::command_queue& queue) { gpu_vector input(initial_input.begin(), initial_input.end(), queue); gpu_vector output(queue.get_context()); auto output_range = range::to_range(output); for(auto& l : layers) { output.resize(::neu::layer::whole_output_size(l), queue); l.test_forward(batch_size, range::to_range(input), output_range, queue); input.swap(output); } range::copy(input, result_output, queue); } }; template<> class forward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_input, OutputRange& result_output, boost::compute::command_queue& queue) { gpu_vector input(initial_input.begin(), initial_input.end(), queue); gpu_vector output(queue.get_context()); auto output_range = range::to_range(output); for(auto& l : layers) { output.resize(::neu::layer::whole_output_size(l), queue); l.forward(range::to_range(input), output_range, queue); input.swap(output); } range::copy(input, result_output, queue); } }; template<> class backward_top<std::vector<neu::layer::any_layer>> { public: template<typename InputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_delta, boost::compute::command_queue& queue) { gpu_vector delta(initial_delta.begin(), initial_delta.end(), queue); gpu_vector prev_delta(queue.get_context()); auto prev_delta_range = range::to_range(prev_delta); // call backward except the top layer for(int i = layers.size()-1; i >= 1; --i) { auto& l = layers.at(i); prev_delta.resize(::neu::layer::whole_input_size(l), queue); l.backward( range::to_range(delta), prev_delta_range, queue); delta.swap(prev_delta); } // call backward_top on the top layer layers.front().backward_top(range::to_range(delta), queue); } }; template<> class backward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_delta, OutputRange& result_prev_delta, boost::compute::command_queue& queue) { gpu_vector delta(initial_delta.begin(), initial_delta.end(), queue); gpu_vector prev_delta(queue.get_context()); auto prev_delta_range = range::to_range(prev_delta); for(int i = layers.size()-1; i >= 0; --i) { auto& l = layers.at(i); prev_delta.resize(::neu::layer::whole_input_size(l), queue); l.backward( range::to_range(delta), prev_delta_range, queue); delta.swap(prev_delta); } range::copy(delta, result_prev_delta, queue); } }; template<> class update<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, boost::compute::command_queue& queue) { for(auto& l : layers) { l.update(queue); } } }; template<> class serialize<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& layers, YAML::Emitter& emitter, boost::compute::command_queue& queue) { emitter << YAML::BeginMap << YAML::Key << "layer_type" << YAML::Value << "any_layer_vector" << YAML::Key << "input_dim" << YAML::Value << ::neu::layer::input_dim(layers) << YAML::Key << "output_dim" << YAML::Value << ::neu::layer::output_dim(layers) << YAML::Key << "batch_size" << YAML::Value << ::neu::layer::batch_size(layers) << YAML::Key << "layers" << YAML::Value << YAML::BeginSeq; for(auto const& l : layers) { ::neu::layer::serialize(l, emitter, queue); } emitter << YAML::EndSeq << YAML::EndMap; } }; } decltype(auto) deserialize_any_layer_vector(YAML::Node const& node, boost::compute::command_queue& queue) { NEU_ASSERT(node["layer_type"].as<std::string>() == "any_layer_vector"); auto layers_node = node["layers"]; std::vector<neu::layer::any_layer> layers; for(auto const& ln : layers_node) { layers.push_back(::neu::layer::deserialize(ln, queue)); } return layers; } } }// namespace neu #endif //NEU_ANY_LAYER_VECTOR_HPP <commit_msg>fix range resize<commit_after>#ifndef NEU_ANY_LAYER_VECTOR_HPP #define NEU_ANY_LAYER_VECTOR_HPP //20150914 #include <vector> #include <neu/basic_type.hpp> #include <neu/range/algorithm.hpp> #include <neu/range/gpu_buffer_range.hpp> #include <neu/layer/traits.hpp> #include <neu/layer/any_layer.hpp> #include <neu/layer/deserialize_fwd.hpp> namespace neu { namespace layer { namespace traits { template<> class input_rank<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::input_rank(alv.front()); } }; template<> class output_rank<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::output_rank(alv.back()); } }; template<> class input_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv, rank_id ri) { return ::neu::layer::input_size(alv.front(), ri); } }; template<> class output_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv, rank_id ri) { return ::neu::layer::output_size(alv.back(), ri); } }; template<> class batch_size<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& alv) { return ::neu::layer::batch_size(alv.front()); } }; template<> class test_forward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call( std::vector<neu::layer::any_layer>& layers, std::size_t batch_size, InputRange const& initial_input, OutputRange& result_output, boost::compute::command_queue& queue) { gpu_vector input(initial_input.begin(), initial_input.end(), queue); gpu_vector output(queue.get_context()); for(auto& l : layers) { output.resize(::neu::layer::whole_output_size(l), queue); auto output_range = range::to_range(output); l.test_forward(batch_size, range::to_range(input), output_range, queue); input.swap(output); } range::copy(input, result_output, queue); } }; template<> class forward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_input, OutputRange& result_output, boost::compute::command_queue& queue) { gpu_vector input(initial_input.begin(), initial_input.end(), queue); gpu_vector output(queue.get_context()); for(auto& l : layers) { output.resize(::neu::layer::whole_output_size(l), queue); auto output_range = range::to_range(output); l.forward(range::to_range(input), output_range, queue); input.swap(output); } range::copy(input, result_output, queue); } }; template<> class backward_top<std::vector<neu::layer::any_layer>> { public: template<typename InputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_delta, boost::compute::command_queue& queue) { gpu_vector delta(initial_delta.begin(), initial_delta.end(), queue); gpu_vector prev_delta(queue.get_context()); // call backward except the top layer for(int i = layers.size()-1; i >= 1; --i) { auto& l = layers.at(i); prev_delta.resize(::neu::layer::whole_input_size(l), queue); auto prev_delta_range = range::to_range(prev_delta); l.backward( range::to_range(delta), prev_delta_range, queue); delta.swap(prev_delta); } // call backward_top on the top layer layers.front().backward_top(range::to_range(delta), queue); } }; template<> class backward<std::vector<neu::layer::any_layer>> { public: template<typename InputRange, typename OutputRange> static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, InputRange const& initial_delta, OutputRange& result_prev_delta, boost::compute::command_queue& queue) { gpu_vector delta(initial_delta.begin(), initial_delta.end(), queue); gpu_vector prev_delta(queue.get_context()); for(int i = layers.size()-1; i >= 0; --i) { auto& l = layers.at(i); prev_delta.resize(::neu::layer::whole_input_size(l), queue); auto prev_delta_range = range::to_range(prev_delta); l.backward( range::to_range(delta), prev_delta_range, queue); delta.swap(prev_delta); } range::copy(delta, result_prev_delta, queue); } }; template<> class update<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call(std::vector<neu::layer::any_layer>& layers, boost::compute::command_queue& queue) { for(auto& l : layers) { l.update(queue); } } }; template<> class serialize<std::vector<neu::layer::any_layer>> { public: static decltype(auto) call( std::vector<neu::layer::any_layer> const& layers, YAML::Emitter& emitter, boost::compute::command_queue& queue) { emitter << YAML::BeginMap << YAML::Key << "layer_type" << YAML::Value << "any_layer_vector" << YAML::Key << "input_dim" << YAML::Value << ::neu::layer::input_dim(layers) << YAML::Key << "output_dim" << YAML::Value << ::neu::layer::output_dim(layers) << YAML::Key << "batch_size" << YAML::Value << ::neu::layer::batch_size(layers) << YAML::Key << "layers" << YAML::Value << YAML::BeginSeq; for(auto const& l : layers) { ::neu::layer::serialize(l, emitter, queue); } emitter << YAML::EndSeq << YAML::EndMap; } }; } decltype(auto) deserialize_any_layer_vector(YAML::Node const& node, boost::compute::command_queue& queue) { NEU_ASSERT(node["layer_type"].as<std::string>() == "any_layer_vector"); auto layers_node = node["layers"]; std::vector<neu::layer::any_layer> layers; for(auto const& ln : layers_node) { layers.push_back(::neu::layer::deserialize(ln, queue)); } return layers; } } }// namespace neu #endif //NEU_ANY_LAYER_VECTOR_HPP <|endoftext|>
<commit_before>/* Copyright (C) 2004 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "parse_output.h" #include <my_global.h> #include <my_sys.h> #include <m_string.h> #include <stdio.h> #include "parse.h" #include "portability.h" /************************************************************************** Private module implementation. **************************************************************************/ namespace { /* no-indent */ /*************************************************************************/ void trim_space(const char **text, uint *word_len) { const char *start= *text; while (*start != 0 && *start == ' ') start++; *text= start; int len= strlen(start); const char *end= start + len - 1; while (end > start && my_isspace(&my_charset_latin1, *end)) end--; *word_len= (end - start)+1; } /*************************************************************************/ /** @brief A facade to the internal workings of optaining the output from an executed system process. */ class Mysqld_output_parser { public: Mysqld_output_parser() { } virtual ~Mysqld_output_parser() { } public: bool parse(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type); protected: /** @brief Run a process and attach stdout- and stdin-pipes to it. @param command The path to the process to be executed @return Error status. @retval TRUE An error occurred @retval FALSE Operation was a success */ virtual bool run_command(const char *command)= 0; /** @brief Read a sequence of bytes from the executed process' stdout pipe. The sequence is terminated by either '\0', LF or CRLF tokens. The terminating token is excluded from the result. @param line_buffer A pointer to a character buffer @param line_buffer_size The size of the buffer in bytes @return Error status. @retval TRUE An error occured @retval FALSE Operation was a success */ virtual bool read_line(char *line_buffer, uint line_buffer_size)= 0; /** @brief Release any resources needed after a execution and parsing. */ virtual bool cleanup()= 0; }; /*************************************************************************/ bool Mysqld_output_parser::parse(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type) { /* should be enough to store the string from the output */ const int LINE_BUFFER_SIZE= 512; char line_buffer[LINE_BUFFER_SIZE]; if (run_command(command)) return TRUE; while (true) { if (read_line(line_buffer, LINE_BUFFER_SIZE)) { cleanup(); return TRUE; } uint found_word_len= 0; char *linep= line_buffer; line_buffer[sizeof(line_buffer) - 1]= '\0'; /* safety */ /* Find the word(s) we are looking for in the line. */ linep= strstr(linep, option_name_str); if (!linep) continue; linep+= option_name_length; switch (option_type) { case GET_VALUE: trim_space((const char**) &linep, &found_word_len); if (option_value_buf_size <= found_word_len) { cleanup(); return TRUE; } strmake(option_value_buf, linep, found_word_len); break; case GET_LINE: strmake(option_value_buf, linep, option_value_buf_size - 1); break; } cleanup(); return FALSE; } } /************************************************************************** Platform-specific implementation: UNIX. **************************************************************************/ #ifndef __WIN__ class Mysqld_output_parser_unix : public Mysqld_output_parser { public: Mysqld_output_parser_unix() : m_stdout(NULL) { } protected: virtual bool run_command(const char *command); virtual bool read_line(char *line_buffer, uint line_buffer_size); virtual bool cleanup(); private: FILE *m_stdout; }; bool Mysqld_output_parser_unix::run_command(const char *command) { if (!(m_stdout= popen(command, "r"))) return TRUE; /* We want fully buffered stream. We also want system to allocate appropriate buffer. */ setvbuf(m_stdout, NULL, _IOFBF, 0); return FALSE; } bool Mysqld_output_parser_unix::read_line(char *line_buffer, uint line_buffer_size) { char *retbuff = fgets(line_buffer, line_buffer_size, m_stdout); /* Remove any tailing new line charaters */ if (line_buffer[line_buffer_size-1] == LF) line_buffer[line_buffer_size-1]= '\0'; return (retbuff == NULL); } bool Mysqld_output_parser_unix::cleanup() { if (m_stdout) pclose(m_stdout); return FALSE; } #else /* Windows */ /************************************************************************** Platform-specific implementation: Windows. **************************************************************************/ class Mysqld_output_parser_win : public Mysqld_output_parser { public: Mysqld_output_parser_win() : m_internal_buffer(NULL), m_internal_buffer_offset(0), m_internal_buffer_size(0) { } protected: virtual bool run_command(const char *command); virtual bool read_line(char *line_buffer, uint line_buffer_size); virtual bool cleanup(); private: HANDLE m_h_child_stdout_wr; HANDLE m_h_child_stdout_rd; uint m_internal_buffer_offset; uint m_internal_buffer_size; char *m_internal_buffer; }; bool Mysqld_output_parser_win::run_command(const char *command) { BOOL op_status; SECURITY_ATTRIBUTES sa_attr; sa_attr.nLength= sizeof(SECURITY_ATTRIBUTES); sa_attr.bInheritHandle= TRUE; sa_attr.lpSecurityDescriptor= NULL; op_status= CreatePipe(&m_h_child_stdout_rd, &m_h_child_stdout_wr, &sa_attr, 0 /* Use system-default buffer size. */); if (!op_status) return TRUE; SetHandleInformation(m_h_child_stdout_rd, HANDLE_FLAG_INHERIT, 0); STARTUPINFO si_start_info; ZeroMemory(&si_start_info, sizeof(STARTUPINFO)); si_start_info.cb= sizeof(STARTUPINFO); si_start_info.hStdError= m_h_child_stdout_wr; si_start_info.hStdOutput= m_h_child_stdout_wr; si_start_info.dwFlags|= STARTF_USESTDHANDLES; PROCESS_INFORMATION pi_proc_info; op_status= CreateProcess(NULL, /* Application name. */ (char*)command, /* Command line. */ NULL, /* Process security attributes. */ NULL, /* Primary thread security attr.*/ TRUE, /* Handles are inherited. */ 0, /* Creation flags. */ NULL, /* Use parent's environment. */ NULL, /* Use parent's curr. directory. */ &si_start_info, /* STARTUPINFO pointer. */ &pi_proc_info); /* Rec. PROCESS_INFORMATION. */ if (!retval) { CloseHandle(m_h_child_stdout_rd); CloseHandle(m_h_child_stdout_wr); return TRUE; } /* Close unnessary handles. */ CloseHandle(pi_proc_info.hProcess); CloseHandle(pi_proc_info.hThread); return FALSE; } bool Mysqld_output_parser_win::read_line(char *line_buffer, uint line_buffer_size) { DWORD dw_read_count= m_internal_buffer_size; bzero(line_buffer,line_buffer_size); char *buff_ptr= line_buffer; char ch; while (buff_ptr - line_buffer < line_buffer_size) { do { ReadFile(m_h_child_stdout_rd, &ch, 1, &dw_read_count, NULL); } while ((ch == CR || ch == LF) && buff_ptr == line_buffer); if (dw_read_count == 0) return TRUE; if (ch == CR || ch == LF) break; *buff_ptr++ = ch; } return FALSE; } bool Mysqld_output_parser_win::cleanup() { /* Close all handles. */ CloseHandle(m_h_child_stdout_wr); CloseHandle(m_h_child_stdout_rd); return FALSE; } #endif /*************************************************************************/ } /* End of private module implementation. */ /*************************************************************************/ /** @brief Parse output of the given command @param command The command to execute. @param option_name_str Option name. @param option_name_length Length of the option name. @param[out] option_value_buf The buffer to store option value. @param option_value_buf_size Size of the option value buffer. @param option_type Type of the option: - GET_LINE if we want to get all the line after the option name; - GET_VALUE otherwise. Execute the process by running "command". Find the "option name" and return the next word if "option_type" is GET_VALUE. Return the rest of the parsed string otherwise. @note This function has a separate windows implementation. @return The error status. @retval FALSE Ok, the option name has been found. @retval TRUE Error occured or the option name is not found. */ bool parse_output_and_get_value(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type) { #ifndef __WIN__ Mysqld_output_parser_unix parser; #else /* __WIN__ */ Mysqld_output_parser_win parser; #endif return parser.parse(command, option_name_str, option_name_length, option_value_buf, option_value_buf_size, option_type); } <commit_msg>Fix of build errors for windows.<commit_after>/* Copyright (C) 2004 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "parse_output.h" #include <my_global.h> #include <my_sys.h> #include <m_string.h> #include <stdio.h> #include "parse.h" #include "portability.h" /************************************************************************** Private module implementation. **************************************************************************/ namespace { /* no-indent */ /*************************************************************************/ void trim_space(const char **text, uint *word_len) { const char *start= *text; while (*start != 0 && *start == ' ') start++; *text= start; int len= strlen(start); const char *end= start + len - 1; while (end > start && my_isspace(&my_charset_latin1, *end)) end--; *word_len= (end - start)+1; } /*************************************************************************/ /** @brief A facade to the internal workings of optaining the output from an executed system process. */ class Mysqld_output_parser { public: Mysqld_output_parser() { } virtual ~Mysqld_output_parser() { } public: bool parse(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type); protected: /** @brief Run a process and attach stdout- and stdin-pipes to it. @param command The path to the process to be executed @return Error status. @retval TRUE An error occurred @retval FALSE Operation was a success */ virtual bool run_command(const char *command)= 0; /** @brief Read a sequence of bytes from the executed process' stdout pipe. The sequence is terminated by either '\0', LF or CRLF tokens. The terminating token is excluded from the result. @param line_buffer A pointer to a character buffer @param line_buffer_size The size of the buffer in bytes @return Error status. @retval TRUE An error occured @retval FALSE Operation was a success */ virtual bool read_line(char *line_buffer, uint line_buffer_size)= 0; /** @brief Release any resources needed after a execution and parsing. */ virtual bool cleanup()= 0; }; /*************************************************************************/ bool Mysqld_output_parser::parse(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type) { /* should be enough to store the string from the output */ const int LINE_BUFFER_SIZE= 512; char line_buffer[LINE_BUFFER_SIZE]; if (run_command(command)) return TRUE; while (true) { if (read_line(line_buffer, LINE_BUFFER_SIZE)) { cleanup(); return TRUE; } uint found_word_len= 0; char *linep= line_buffer; line_buffer[sizeof(line_buffer) - 1]= '\0'; /* safety */ /* Find the word(s) we are looking for in the line. */ linep= strstr(linep, option_name_str); if (!linep) continue; linep+= option_name_length; switch (option_type) { case GET_VALUE: trim_space((const char**) &linep, &found_word_len); if (option_value_buf_size <= found_word_len) { cleanup(); return TRUE; } strmake(option_value_buf, linep, found_word_len); break; case GET_LINE: strmake(option_value_buf, linep, option_value_buf_size - 1); break; } cleanup(); return FALSE; } } /************************************************************************** Platform-specific implementation: UNIX. **************************************************************************/ #ifndef __WIN__ class Mysqld_output_parser_unix : public Mysqld_output_parser { public: Mysqld_output_parser_unix() : m_stdout(NULL) { } protected: virtual bool run_command(const char *command); virtual bool read_line(char *line_buffer, uint line_buffer_size); virtual bool cleanup(); private: FILE *m_stdout; }; bool Mysqld_output_parser_unix::run_command(const char *command) { if (!(m_stdout= popen(command, "r"))) return TRUE; /* We want fully buffered stream. We also want system to allocate appropriate buffer. */ setvbuf(m_stdout, NULL, _IOFBF, 0); return FALSE; } bool Mysqld_output_parser_unix::read_line(char *line_buffer, uint line_buffer_size) { char *retbuff = fgets(line_buffer, line_buffer_size, m_stdout); /* Remove any tailing new line charaters */ if (line_buffer[line_buffer_size-1] == LF) line_buffer[line_buffer_size-1]= '\0'; return (retbuff == NULL); } bool Mysqld_output_parser_unix::cleanup() { if (m_stdout) pclose(m_stdout); return FALSE; } #else /* Windows */ /************************************************************************** Platform-specific implementation: Windows. **************************************************************************/ class Mysqld_output_parser_win : public Mysqld_output_parser { public: Mysqld_output_parser_win() : m_internal_buffer(NULL), m_internal_buffer_offset(0), m_internal_buffer_size(0) { } protected: virtual bool run_command(const char *command); virtual bool read_line(char *line_buffer, uint line_buffer_size); virtual bool cleanup(); private: HANDLE m_h_child_stdout_wr; HANDLE m_h_child_stdout_rd; uint m_internal_buffer_offset; uint m_internal_buffer_size; char *m_internal_buffer; }; bool Mysqld_output_parser_win::run_command(const char *command) { BOOL op_status; SECURITY_ATTRIBUTES sa_attr; sa_attr.nLength= sizeof(SECURITY_ATTRIBUTES); sa_attr.bInheritHandle= TRUE; sa_attr.lpSecurityDescriptor= NULL; op_status= CreatePipe(&m_h_child_stdout_rd, &m_h_child_stdout_wr, &sa_attr, 0 /* Use system-default buffer size. */); if (!op_status) return TRUE; SetHandleInformation(m_h_child_stdout_rd, HANDLE_FLAG_INHERIT, 0); STARTUPINFO si_start_info; ZeroMemory(&si_start_info, sizeof(STARTUPINFO)); si_start_info.cb= sizeof(STARTUPINFO); si_start_info.hStdError= m_h_child_stdout_wr; si_start_info.hStdOutput= m_h_child_stdout_wr; si_start_info.dwFlags|= STARTF_USESTDHANDLES; PROCESS_INFORMATION pi_proc_info; op_status= CreateProcess(NULL, /* Application name. */ (char*)command, /* Command line. */ NULL, /* Process security attributes. */ NULL, /* Primary thread security attr.*/ TRUE, /* Handles are inherited. */ 0, /* Creation flags. */ NULL, /* Use parent's environment. */ NULL, /* Use parent's curr. directory. */ &si_start_info, /* STARTUPINFO pointer. */ &pi_proc_info); /* Rec. PROCESS_INFORMATION. */ if (!op_status) { CloseHandle(m_h_child_stdout_rd); CloseHandle(m_h_child_stdout_wr); return TRUE; } /* Close unnessary handles. */ CloseHandle(pi_proc_info.hProcess); CloseHandle(pi_proc_info.hThread); return FALSE; } bool Mysqld_output_parser_win::read_line(char *line_buffer, uint line_buffer_size) { DWORD dw_read_count= m_internal_buffer_size; bzero(line_buffer,line_buffer_size); char *buff_ptr= line_buffer; char ch; while ((unsigned)(buff_ptr - line_buffer) < line_buffer_size) { do { ReadFile(m_h_child_stdout_rd, &ch, 1, &dw_read_count, NULL); } while ((ch == CR || ch == LF) && buff_ptr == line_buffer); if (dw_read_count == 0) return TRUE; if (ch == CR || ch == LF) break; *buff_ptr++ = ch; } return FALSE; } bool Mysqld_output_parser_win::cleanup() { /* Close all handles. */ CloseHandle(m_h_child_stdout_wr); CloseHandle(m_h_child_stdout_rd); return FALSE; } #endif /*************************************************************************/ } /* End of private module implementation. */ /*************************************************************************/ /** @brief Parse output of the given command @param command The command to execute. @param option_name_str Option name. @param option_name_length Length of the option name. @param[out] option_value_buf The buffer to store option value. @param option_value_buf_size Size of the option value buffer. @param option_type Type of the option: - GET_LINE if we want to get all the line after the option name; - GET_VALUE otherwise. Execute the process by running "command". Find the "option name" and return the next word if "option_type" is GET_VALUE. Return the rest of the parsed string otherwise. @note This function has a separate windows implementation. @return The error status. @retval FALSE Ok, the option name has been found. @retval TRUE Error occured or the option name is not found. */ bool parse_output_and_get_value(const char *command, const char *option_name_str, uint option_name_length, char *option_value_buf, size_t option_value_buf_size, enum_option_type option_type) { #ifndef __WIN__ Mysqld_output_parser_unix parser; #else /* __WIN__ */ Mysqld_output_parser_win parser; #endif return parser.parse(command, option_name_str, option_name_length, option_value_buf, option_value_buf_size, option_type); } <|endoftext|>
<commit_before>#include <Windows.h> #include <cstdio> #include <cstring> using namespace std; enum DisplaySelection { DS_MONITOR = 1, DS_HDMI = 2, DS_TOGGLE = 3, }; /* This array must match the above enum */ char *DisplaySelectionString[] = { "Monitor", "HDMI", "Toggle", }; #define MAX_PATH_ELEMENTS 128 #define MAX_MODE_ELEMENTS 8 int main(int argc, char *argv[]) { LONG retval; DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS]; DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS]; UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]); UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]); UINT32 hdmi_idx = MAX_PATH_ELEMENTS; UINT32 dvi_idx = MAX_PATH_ELEMENTS; DisplaySelection current_selection = DS_TOGGLE; retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL); if (ERROR_SUCCESS != retval) { printf("Query failure - unable to set new path!!\n"); if (ERROR_INSUFFICIENT_BUFFER == retval) printf("Insufficient buffer failure; increase MAX_PATH_ELEMENTS or MAX_MODE_ELEMENTS and re-compile."); return 2; } /* Find the target paths we care about */ for (unsigned int path = 0; path < numPathElements; path++) { if (pathArray[path].sourceInfo.modeInfoIdx >= 0 && pathArray[path].sourceInfo.modeInfoIdx < numModeElements) { if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { hdmi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_HDMI; } else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { dvi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection = DS_MONITOR; } } } if (current_selection == DS_TOGGLE) { printf("Unable to determine current video output -- exiting\n"); return 3; } /* No argument means toggle output */ unsigned int input = DS_TOGGLE; DISPLAYCONFIG_PATH_INFO desiredSettings; /* Try to get the desired output setting */ if (argc > 1) { input = atoi(argv[1]); } /* input should match the enum above. indexed into the string array as (input - 1) */ if ((input - 1) < (sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]))) { printf("Device to be selected is the %s selection.\n", DisplaySelectionString[input - 1]); if ((DS_MONITOR == input && current_selection == DS_HDMI) || (DS_TOGGLE == input && DS_HDMI == current_selection)) { if (dvi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[dvi_idx]; else { printf("Attempting to switch to DVI, but unable to find config element -- exiting\n"); return 4; } } else if ((DS_HDMI == input && current_selection == DS_MONITOR) || (DS_TOGGLE == input && DS_MONITOR == current_selection)) { if (hdmi_idx < MAX_PATH_ELEMENTS) desiredSettings = pathArray[hdmi_idx]; else { printf("Attempting to switch to HDMI, but unable to find config element -- exiting\n"); return 5; } } else { printf("Output already set to the desired selection.\n"); return 0; } } else { printf("Unknown display selection: %d\n\n", input); printf("Usage:\n"); printf("\tDisplayController_Config.exe [new_output]\n"); for (int i = 0; i < sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]); i++) { printf("\t\t%d: %s\n", i + 1, DisplaySelectionString[i]); } printf("\n\tNo parameter means Toggle\n"); return 1; } /* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */ desiredSettings.flags = DISPLAYCONFIG_PATH_ACTIVE; desiredSettings.targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; desiredSettings.sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES); if (ERROR_SUCCESS != retval) { printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n"); retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES | SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG); if (ERROR_SUCCESS != retval) { printf("Unable to set the new display config!!\n"); return 3; } } return 0; }<commit_msg>Add "Both" option<commit_after>#include <Windows.h> #include <cstdio> #include <cstring> using namespace std; enum DisplaySelection { DS_MONITOR = 1, DS_HDMI = 2, DS_BOTH = 3, DS_CYCLE = 4, }; /* This array must match the above enum */ const char *DisplaySelectionStrings[] = { "Monitor", "HDMI", "Both", "Cycle", }; static const unsigned int MaxSelectionStrings = sizeof(DisplaySelectionStrings) / sizeof(DisplaySelectionStrings[0]); #define DS_SELECT_NONE_FLAG 0 #define DS_SELECT_MONITOR_FLAG 1 #define DS_SELECT_HDMI_FLAG 2 typedef unsigned int DisplaySelectionFlags; /* This array is used to list the order of output combos for the Cycle option. It is also contains the flags for each selection at (DS_* - 1) */ const DisplaySelectionFlags OptionFlags[] = { DS_SELECT_MONITOR_FLAG, /* DVI */ DS_SELECT_HDMI_FLAG, /* HDMI */ DS_SELECT_MONITOR_FLAG | DS_SELECT_HDMI_FLAG, /* Both */ }; static const unsigned int MaxOptions = sizeof(OptionFlags) / sizeof(OptionFlags[0]); static DisplaySelectionFlags GetNextOption(DisplaySelectionFlags current_selection) { unsigned int curr_idx = 0; for (curr_idx = 0; curr_idx < MaxOptions; curr_idx++) { if (OptionFlags[curr_idx] == current_selection) break; } if (curr_idx == MaxOptions) { return OptionFlags[0]; } return OptionFlags[(curr_idx + 1) % MaxOptions]; } #define MAX_PATH_ELEMENTS 128 #define MAX_MODE_ELEMENTS 8 int main(int argc, char *argv[]) { LONG retval; DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS]; DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS]; UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]); UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]); UINT32 hdmi_idx = MAX_PATH_ELEMENTS; UINT32 dvi_idx = MAX_PATH_ELEMENTS; DisplaySelectionFlags current_selection = DS_SELECT_NONE_FLAG; retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL); if (ERROR_SUCCESS != retval) { printf("Query failure - unable to set new path!!\n"); if (ERROR_INSUFFICIENT_BUFFER == retval) printf("Insufficient buffer failure; increase MAX_PATH_ELEMENTS or MAX_MODE_ELEMENTS and re-compile."); return 2; } /* Find the target paths we care about */ for (unsigned int path = 0; path < numPathElements; path++) { if (pathArray[path].sourceInfo.modeInfoIdx >= 0 && pathArray[path].sourceInfo.modeInfoIdx < numModeElements) { if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { hdmi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection |= DS_SELECT_HDMI_FLAG; } else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI) && (pathArray[path].targetInfo.targetAvailable == TRUE)) { dvi_idx = path; if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags) current_selection |= DS_SELECT_MONITOR_FLAG; } } } if (current_selection == DS_SELECT_NONE_FLAG) { printf("Unable to determine current video output -- exiting\n"); return 3; } /* No argument means cycle output */ unsigned int input = DS_CYCLE; DISPLAYCONFIG_PATH_INFO desiredSettings[2]; unsigned int num_desired_settings = 0; /* Try to get the desired output setting */ if (argc > 1) { input = atoi(argv[1]); } /* input should match the enum above. indexed into the string array as (input - 1) */ if ((input - 1) < MaxSelectionStrings) { printf("Device to be selected is the %s selection.\n", DisplaySelectionStrings[input - 1]); DisplaySelectionFlags desired_selection; if (DS_CYCLE == input) desired_selection = GetNextOption(current_selection); else desired_selection = OptionFlags[input - 1]; if (desired_selection != current_selection) { /* HDMI will get priority if multiple outputs being attempted */ if (desired_selection & DS_SELECT_HDMI_FLAG) { if (hdmi_idx < MAX_PATH_ELEMENTS) desiredSettings[num_desired_settings++] = pathArray[hdmi_idx]; else { printf("Attempting to enable HDMI, but unable to find config element -- exiting\n"); return 4; } } if (desired_selection & DS_SELECT_MONITOR_FLAG) { if (dvi_idx < MAX_PATH_ELEMENTS) desiredSettings[num_desired_settings++] = pathArray[dvi_idx]; else { printf("Attempting to enable DVI, but unable to find config element -- exiting\n"); return 5; } } } else { printf("Output already set to the desired selection.\n"); return 0; } } else { printf("Unknown display selection: %d\n\n", input); printf("Usage:\n"); printf("\tDisplayController_Config.exe [new_output]\n"); for (int i = 0; i < MaxSelectionStrings; i++) { printf("\t\t%d: %s\n", i + 1, DisplaySelectionStrings[i]); } printf("\n\tNo parameter means Cycle\n"); return 1; } /* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */ unsigned int setting = 0; for (setting = 0; setting < num_desired_settings; setting++) { desiredSettings[setting].flags = DISPLAYCONFIG_PATH_ACTIVE; desiredSettings[setting].targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; desiredSettings[setting].sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID; } retval = SetDisplayConfig(num_desired_settings, desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES); if (ERROR_SUCCESS != retval) { printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n"); retval = SetDisplayConfig(num_desired_settings, desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES | SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG); if (ERROR_SUCCESS != retval) { printf("Unable to set the new display config!!\n"); return 3; } } return 0; }<|endoftext|>
<commit_before>// Copyright 2020, Intel Corporation #include "mlir/Conversion/GPUToVulkan/ConvertGPUToVulkanPass.h" #include "mlir/Conversion/SCFToGPU/SCFToGPU.h" #include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Conversion/StandardToSPIRV/ConvertStandardToSPIRVPass.h" #include "mlir/Dialect/Affine/Passes.h" #include "mlir/Dialect/GPU/Passes.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/SPIRV/Passes.h" #include "mlir/Dialect/SPIRV/SPIRVDialect.h" #include "mlir/Dialect/SPIRV/SPIRVOps.h" #include "mlir/Dialect/StandardOps/Transforms/Passes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" #include "pmlc/compiler/registry.h" #include "pmlc/conversion/gpu/lowering.h" #include "pmlc/conversion/gpu_to_spirv/passes.h" #include "pmlc/conversion/pxa_to_affine/passes.h" #include "pmlc/conversion/stdx_to_llvm/passes.h" #include "pmlc/conversion/tile_to_pxa/passes.h" #include "pmlc/dialect/pxa/transforms/passes.h" #include "pmlc/dialect/stdx/ir/ops.h" #include "pmlc/dialect/stdx/transforms/passes.h" #include "pmlc/dialect/tile/transforms/passes.h" #include "pmlc/target/intel_gen/pass_detail.h" #include "pmlc/target/intel_gen/passes.h" #include "pmlc/target/x86/passes.h" using namespace mlir; // NOLINT[build/namespaces] namespace pmlc::target::intel_gen { namespace pxa = pmlc::dialect::pxa; namespace { struct LowerPXAToAffinePass : public ConvertPXAToAffineBase<LowerPXAToAffinePass> { void runOnOperation() final { auto &ctx = getContext(); conversion::pxa_to_affine::PXAToAffineConversionTarget target(ctx); OwningRewritePatternList patterns; x86::populatePXAPrngToAffineConversionPatterns(patterns, &ctx); conversion::pxa_to_affine::populatePXAToAffineConversionPatterns(patterns, &ctx); if (failed(applyPartialConversion(getOperation(), target, patterns, nullptr))) { getOperation().emitError("Error lowering pxa -> affine\n"); signalPassFailure(); } } }; struct ConvertStandardToLLVMPass : public ConvertStandardToLLVMBase<ConvertStandardToLLVMPass> { void runOnOperation() override { auto module = getOperation(); auto *context = module.getContext(); LowerToLLVMOptions options = { /*useBarePtrCallConv=*/false, /*emitCWrappers=*/true, /*indexBitwidth=*/kDeriveIndexBitwidthFromDataLayout, /*useAlignedAlloc=*/false, }; LLVMTypeConverter typeConverter(context, options); OwningRewritePatternList patterns; populateExpandTanhPattern(patterns, context); populateStdToLLVMConversionPatterns(typeConverter, patterns); conversion::stdx_to_llvm::populateStdXToLLVMConversionPatterns( typeConverter, patterns); LLVMConversionTarget target(*context); if (failed(applyPartialConversion(module, target, patterns))) { signalPassFailure(); } } }; struct ParallelLoopToGpuPass : public ConvertParallelLoopToGpuBase<ParallelLoopToGpuPass> { void runOnOperation() override { OwningRewritePatternList patterns; populateParallelLoopToGPUPatterns(patterns, &getContext()); ConversionTarget target(getContext()); target.addLegalDialect<StandardOpsDialect>(); target.addLegalDialect<pmlc::dialect::stdx::StdXDialect>(); target.addLegalDialect<AffineDialect>(); target.addLegalDialect<gpu::GPUDialect>(); target.addLegalDialect<scf::SCFDialect>(); target.addIllegalOp<scf::ParallelOp>(); if (failed(applyPartialConversion(getOperation(), target, patterns))) signalPassFailure(); } }; } // namespace std::unique_ptr<Pass> createConvertStandardToLLVM() { return std::make_unique<ConvertStandardToLLVMPass>(); } std::unique_ptr<Pass> createParallelLoopToGpuPass() { return std::make_unique<ParallelLoopToGpuPass>(); } std::unique_ptr<Pass> createLowerPXAToAffinePass() { return std::make_unique<LowerPXAToAffinePass>(); } void pipelineBuilder(OpPassManager &pm) { // Bound + pad initial tile code pm.addPass(dialect::tile::createComputeBoundsPass()); pm.addPass(dialect::tile::createPadRangesPass()); pm.addPass(dialect::tile::createPadConstraintsPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Lower to PXA pm.addPass(conversion::tile_to_pxa::createLowerTileToPXAPass()); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do subgroup or accumulation pm.addPass(pmlc::dialect::pxa::createSubgroupsPass()); // pm.addPass(pmlc::dialect::pxa::createTileAccumulatePass()); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass(/*promote=*/false)); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Assign GPU blocks + threads to outermost loop pm.addPass(pmlc::dialect::pxa::createGPUThreadPass(/*maxThreads=*/64)); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Lower out of PXA memory semantics pm.addPass(createLowerPXAToAffinePass()); // Unroll affine.for loops. pm.addPass(createLoopUnrollPass( /*unrollFactor=*/6, /*unrollUpToFactor=*/true)); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Pack dims pm.addPass(createAffineIndexPackPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do a custom version of lower-affine which also set GPU mappings pm.addPass(createIntelGenLowerAffinePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Fix booleans pm.addPass(dialect::stdx::createI1StorageToI32Pass()); // Devectorize pm.addPass(createSubgroupBroadcastPass()); pm.addPass(createCSEPass()); // Lower mapped scf.parallel's to GPU pm.addPass(createParallelLoopToGpuPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do kernel outlining pm.addPass(conversion::gpu::createGpuKernelOutliningPass()); // GPU to SPIR-V. pm.addPass(createLegalizeStdOpsForSPIRVLoweringPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); pm.addPass(conversion::gpu_to_spirv::createGPUToSPIRVCustomPass()); // SPIR-V passes for lowering attributes. pm.addPass(spirv::createLowerABIAttributesPass()); pm.addPass(spirv::createUpdateVersionCapabilityExtensionPass()); // GPU to Vulkan. pm.addPass(conversion::gpu::createConvertGpuLaunchFuncToVulkanCallsPass()); // Convert Vulkan calls to LLVM code pm.addPass(createConvertStandardToLLVM()); } static PassPipelineRegistration<> passPipelineReg("target-intel_gen", "Target pipeline for Intel GEN iGPUs", pipelineBuilder); static compiler::TargetRegistration targetReg("intel_gen", pipelineBuilder); } // namespace pmlc::target::intel_gen <commit_msg>Adjusted the loop unroll factor (#1446)<commit_after>// Copyright 2020, Intel Corporation #include "mlir/Conversion/GPUToVulkan/ConvertGPUToVulkanPass.h" #include "mlir/Conversion/SCFToGPU/SCFToGPU.h" #include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Conversion/StandardToSPIRV/ConvertStandardToSPIRVPass.h" #include "mlir/Dialect/Affine/Passes.h" #include "mlir/Dialect/GPU/Passes.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/SPIRV/Passes.h" #include "mlir/Dialect/SPIRV/SPIRVDialect.h" #include "mlir/Dialect/SPIRV/SPIRVOps.h" #include "mlir/Dialect/StandardOps/Transforms/Passes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" #include "pmlc/compiler/registry.h" #include "pmlc/conversion/gpu/lowering.h" #include "pmlc/conversion/gpu_to_spirv/passes.h" #include "pmlc/conversion/pxa_to_affine/passes.h" #include "pmlc/conversion/stdx_to_llvm/passes.h" #include "pmlc/conversion/tile_to_pxa/passes.h" #include "pmlc/dialect/pxa/transforms/passes.h" #include "pmlc/dialect/stdx/ir/ops.h" #include "pmlc/dialect/stdx/transforms/passes.h" #include "pmlc/dialect/tile/transforms/passes.h" #include "pmlc/target/intel_gen/pass_detail.h" #include "pmlc/target/intel_gen/passes.h" #include "pmlc/target/x86/passes.h" using namespace mlir; // NOLINT[build/namespaces] namespace pmlc::target::intel_gen { namespace pxa = pmlc::dialect::pxa; namespace { struct LowerPXAToAffinePass : public ConvertPXAToAffineBase<LowerPXAToAffinePass> { void runOnOperation() final { auto &ctx = getContext(); conversion::pxa_to_affine::PXAToAffineConversionTarget target(ctx); OwningRewritePatternList patterns; x86::populatePXAPrngToAffineConversionPatterns(patterns, &ctx); conversion::pxa_to_affine::populatePXAToAffineConversionPatterns(patterns, &ctx); if (failed(applyPartialConversion(getOperation(), target, patterns, nullptr))) { getOperation().emitError("Error lowering pxa -> affine\n"); signalPassFailure(); } } }; struct ConvertStandardToLLVMPass : public ConvertStandardToLLVMBase<ConvertStandardToLLVMPass> { void runOnOperation() override { auto module = getOperation(); auto *context = module.getContext(); LowerToLLVMOptions options = { /*useBarePtrCallConv=*/false, /*emitCWrappers=*/true, /*indexBitwidth=*/kDeriveIndexBitwidthFromDataLayout, /*useAlignedAlloc=*/false, }; LLVMTypeConverter typeConverter(context, options); OwningRewritePatternList patterns; populateExpandTanhPattern(patterns, context); populateStdToLLVMConversionPatterns(typeConverter, patterns); conversion::stdx_to_llvm::populateStdXToLLVMConversionPatterns( typeConverter, patterns); LLVMConversionTarget target(*context); if (failed(applyPartialConversion(module, target, patterns))) { signalPassFailure(); } } }; struct ParallelLoopToGpuPass : public ConvertParallelLoopToGpuBase<ParallelLoopToGpuPass> { void runOnOperation() override { OwningRewritePatternList patterns; populateParallelLoopToGPUPatterns(patterns, &getContext()); ConversionTarget target(getContext()); target.addLegalDialect<StandardOpsDialect>(); target.addLegalDialect<pmlc::dialect::stdx::StdXDialect>(); target.addLegalDialect<AffineDialect>(); target.addLegalDialect<gpu::GPUDialect>(); target.addLegalDialect<scf::SCFDialect>(); target.addIllegalOp<scf::ParallelOp>(); if (failed(applyPartialConversion(getOperation(), target, patterns))) signalPassFailure(); } }; } // namespace std::unique_ptr<Pass> createConvertStandardToLLVM() { return std::make_unique<ConvertStandardToLLVMPass>(); } std::unique_ptr<Pass> createParallelLoopToGpuPass() { return std::make_unique<ParallelLoopToGpuPass>(); } std::unique_ptr<Pass> createLowerPXAToAffinePass() { return std::make_unique<LowerPXAToAffinePass>(); } void pipelineBuilder(OpPassManager &pm) { // Bound + pad initial tile code pm.addPass(dialect::tile::createComputeBoundsPass()); pm.addPass(dialect::tile::createPadRangesPass()); pm.addPass(dialect::tile::createPadConstraintsPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Lower to PXA pm.addPass(conversion::tile_to_pxa::createLowerTileToPXAPass()); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do subgroup or accumulation pm.addPass(pmlc::dialect::pxa::createSubgroupsPass()); // pm.addPass(pmlc::dialect::pxa::createTileAccumulatePass()); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass(/*promote=*/false)); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Assign GPU blocks + threads to outermost loop pm.addPass(pmlc::dialect::pxa::createGPUThreadPass(/*maxThreads=*/64)); pm.addPass(pmlc::dialect::pxa::createAffineNormalizePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Lower out of PXA memory semantics pm.addPass(createLowerPXAToAffinePass()); // Unroll affine.for loops. pm.addPass(createLoopUnrollPass( /*unrollFactor=*/256, /*unrollUpToFactor=*/true)); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Pack dims pm.addPass(createAffineIndexPackPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do a custom version of lower-affine which also set GPU mappings pm.addPass(createIntelGenLowerAffinePass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Fix booleans pm.addPass(dialect::stdx::createI1StorageToI32Pass()); // Devectorize pm.addPass(createSubgroupBroadcastPass()); pm.addPass(createCSEPass()); // Lower mapped scf.parallel's to GPU pm.addPass(createParallelLoopToGpuPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Do kernel outlining pm.addPass(conversion::gpu::createGpuKernelOutliningPass()); // GPU to SPIR-V. pm.addPass(createLegalizeStdOpsForSPIRVLoweringPass()); pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); pm.addPass(conversion::gpu_to_spirv::createGPUToSPIRVCustomPass()); // SPIR-V passes for lowering attributes. pm.addPass(spirv::createLowerABIAttributesPass()); pm.addPass(spirv::createUpdateVersionCapabilityExtensionPass()); // GPU to Vulkan. pm.addPass(conversion::gpu::createConvertGpuLaunchFuncToVulkanCallsPass()); // Convert Vulkan calls to LLVM code pm.addPass(createConvertStandardToLLVM()); } static PassPipelineRegistration<> passPipelineReg("target-intel_gen", "Target pipeline for Intel GEN iGPUs", pipelineBuilder); static compiler::TargetRegistration targetReg("intel_gen", pipelineBuilder); } // namespace pmlc::target::intel_gen <|endoftext|>
<commit_before><commit_msg>throw error if mcnp_to_id is unsuccessful<commit_after><|endoftext|>
<commit_before><commit_msg>New correct fix for memory leaks in AliTPCDigitizer<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "BaseTestBlock.hpp" #include <iterator> #include <boost/math/constants/constants.hpp> #include <nix/hydra/multiArray.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> using namespace nix; using namespace valid; void BaseTestBlock::testValidate() { valid::Result result = validate(block); CPPUNIT_ASSERT(result.getErrors().size() == 0); CPPUNIT_ASSERT(result.getWarnings().size() == 0); } void BaseTestBlock::testId() { CPPUNIT_ASSERT(block.id().size() == 36); } void BaseTestBlock::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); } void BaseTestBlock::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); std::string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void BaseTestBlock::testDefinition() { std::string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); } void BaseTestBlock::testMetadataAccess() { CPPUNIT_ASSERT(!block.metadata()); block.metadata(section); CPPUNIT_ASSERT(block.metadata()); // test none-unsetter block.metadata(none); CPPUNIT_ASSERT(!block.metadata()); // test deleter removing link too block.metadata(section); file.deleteSection(section.id()); CPPUNIT_ASSERT(!block.metadata()); // re-create section section = file.createSection("foo_section", "metadata"); } void BaseTestBlock::testSourceAccess() { std::vector<std::string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" }; Source s; CPPUNIT_ASSERT(!block.hasSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); CPPUNIT_ASSERT(!block.hasSource("invalid_id")); CPPUNIT_ASSERT_THROW(block.getSource(block.sourceCount() + 10), OutOfBounds); std::vector<std::string> ids; for (const auto &name : names) { Source src = block.createSource(name, "channel"); CPPUNIT_ASSERT(src.name() == name); CPPUNIT_ASSERT(block.hasSource(name)); CPPUNIT_ASSERT(block.hasSource(src)); ids.push_back(src.id()); } CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"), DuplicateName); CPPUNIT_ASSERT_THROW(block.createSource("", "test"), nix::EmptyString); CPPUNIT_ASSERT(block.sourceCount() == names.size()); CPPUNIT_ASSERT(block.sources().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getSource(block.sourceCount() + 10), OutOfBounds); for (const auto &id : ids) { Source src = block.getSource(id); CPPUNIT_ASSERT(block.hasSource(id) == true); CPPUNIT_ASSERT(src.id() == id); block.deleteSource(id); } s = block.createSource("test", "test"); CPPUNIT_ASSERT(block.sourceCount() == 1); CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); } void BaseTestBlock::testDataArrayAccess() { std::vector<std::string> names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; DataArray data_array, a; CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); std::vector<std::string> ids; for (const auto &name : names) { data_array = block.createDataArray(name, "channel", DataType::Double, nix::NDSize({ 0 })); CPPUNIT_ASSERT(data_array.name() == name); CPPUNIT_ASSERT(data_array.type() == "channel"); ids.push_back(data_array.id()); } CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })), DuplicateName); CPPUNIT_ASSERT_THROW(block.createDataArray("", "channel", DataType::Double, nix::NDSize({ 0 })), EmptyString); CPPUNIT_ASSERT(block.hasDataArray(data_array)); CPPUNIT_ASSERT(!block.hasDataArray(a)); CPPUNIT_ASSERT(block.dataArrayCount() == names.size()); CPPUNIT_ASSERT(block.dataArrays().size() == names.size()); for (const auto &name : names) { DataArray da_name = block.getDataArray(name); CPPUNIT_ASSERT(da_name); DataArray da_id = block.getDataArray(da_name.id()); CPPUNIT_ASSERT(da_id); CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name()); } std::vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel")); CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size()); filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size()); if (filteredArrays.size() > 0) { boost::optional<std::string> name = filteredArrays[0].name(); CPPUNIT_ASSERT(name && *name == "data_array_c"); } for (auto it = ids.begin(); it != ids.end(); it++) { CPPUNIT_ASSERT(block.hasDataArray(*it)); CPPUNIT_ASSERT(block.getDataArray(*it).id() == *it); block.deleteDataArray(*it); } CPPUNIT_ASSERT(!block.deleteDataArray(a)); CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); } void BaseTestBlock::testTagAccess() { std::vector<std::string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; std::vector<std::string> array_names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; std::vector<DataArray> refs; Tag tag, t; for (const auto &name : array_names) { refs.push_back(block.createDataArray(name, "reference", DataType::Double, nix::NDSize({ 0 }))); } CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); CPPUNIT_ASSERT(!block.hasTag(t)); std::vector<std::string> ids; for (auto it = names.begin(); it != names.end(); ++it) { tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4}); tag.references(refs); CPPUNIT_ASSERT(tag.name() == *it); CPPUNIT_ASSERT(block.hasTag(tag)); ids.push_back(tag.id()); } CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}), DuplicateName); CPPUNIT_ASSERT(block.tagCount() == names.size()); CPPUNIT_ASSERT(block.tags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); ++it) { tag = block.getTag(*it); CPPUNIT_ASSERT(block.hasTag(*it)); CPPUNIT_ASSERT(tag.id() == *it); block.deleteTag(*it); } tag = block.createTag("test", "test", {0.0}); CPPUNIT_ASSERT(block.hasTag(tag)); CPPUNIT_ASSERT(block.deleteTag(tag)); CPPUNIT_ASSERT(!block.deleteTag(t)); CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); } void BaseTestBlock::testMultiTagAccess() { std::vector<std::string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; MultiTag mtag, m; // create a valid positions data array below DataArray positions = block.createDataArray("array_one", "testdata", DataType::Double, nix::NDSize({ 3, 4, 2 })); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); CPPUNIT_ASSERT(!block.hasMultiTag(m)); std::vector<std::string> ids; for (auto it = names.begin(); it != names.end(); it++) { mtag = block.createMultiTag(*it, "segment", positions); CPPUNIT_ASSERT(mtag.name() == *it); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); ids.push_back(mtag.id()); } CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions), DuplicateName); CPPUNIT_ASSERT(block.multiTagCount() == names.size()); CPPUNIT_ASSERT(block.multiTags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); it++) { mtag = block.getMultiTag(*it); CPPUNIT_ASSERT(block.hasMultiTag(*it)); CPPUNIT_ASSERT(mtag.id() == *it); block.deleteMultiTag(*it); } mtag = block.createMultiTag("test", "test", positions); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); CPPUNIT_ASSERT(!block.deleteMultiTag(m)); CPPUNIT_ASSERT(block.deleteMultiTag(mtag)); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); } void BaseTestBlock::testGroupAccess() { std::vector<std::string> names = { "group_a", "group_b", "group_c", "group_d", "group_e" }; Group g; CPPUNIT_ASSERT(!block.hasGroup(g)); CPPUNIT_ASSERT(block.groupCount() == 0); CPPUNIT_ASSERT(block.groups().size() == 0); CPPUNIT_ASSERT(block.getGroup("invalid_id") == false); CPPUNIT_ASSERT(!block.hasGroup("invalid_id")); std::vector<std::string> ids; for (const auto &name : names) { Group gr = block.createGroup(name, "group"); CPPUNIT_ASSERT(gr.name() == name); CPPUNIT_ASSERT(block.hasGroup(name)); CPPUNIT_ASSERT(block.hasGroup(gr)); ids.push_back(gr.id()); } CPPUNIT_ASSERT_THROW(block.createGroup(names[0], "group"), DuplicateName); CPPUNIT_ASSERT(block.groupCount() == names.size()); CPPUNIT_ASSERT(block.groups().size() == names.size()); for (const auto &id : ids) { Group gr = block.getGroup(id); CPPUNIT_ASSERT(block.hasGroup(id)); CPPUNIT_ASSERT(gr.id() == id); block.deleteGroup(id); } g = block.createGroup("test", "test"); CPPUNIT_ASSERT(block.groupCount() == 1); CPPUNIT_ASSERT(block.deleteGroup(g)); CPPUNIT_ASSERT(block.groupCount() == 0); CPPUNIT_ASSERT(block.groups().size() == 0); CPPUNIT_ASSERT(block.getGroup("invalid_id") == false); } void BaseTestBlock::testOperators() { CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); CPPUNIT_ASSERT(block != false); CPPUNIT_ASSERT(block != none); CPPUNIT_ASSERT(block == block); CPPUNIT_ASSERT(block != block_other); block_other = block; CPPUNIT_ASSERT(block == block_other); block_other = none; CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); std::stringstream str; str << block; } void BaseTestBlock::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void BaseTestBlock::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); } void BaseTestBlock::testCompare() { std::string other_name = block_other.name(); std::string block_name = block.name(); CPPUNIT_ASSERT(block.compare(block) == 0); CPPUNIT_ASSERT(block.compare(block_other) == block_name.compare(other_name)); } <commit_msg>[test] Block: add missing OOB access checks<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "BaseTestBlock.hpp" #include <iterator> #include <boost/math/constants/constants.hpp> #include <nix/hydra/multiArray.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TestRunner.h> #include <cppunit/BriefTestProgressListener.h> using namespace nix; using namespace valid; void BaseTestBlock::testValidate() { valid::Result result = validate(block); CPPUNIT_ASSERT(result.getErrors().size() == 0); CPPUNIT_ASSERT(result.getWarnings().size() == 0); } void BaseTestBlock::testId() { CPPUNIT_ASSERT(block.id().size() == 36); } void BaseTestBlock::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); } void BaseTestBlock::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); std::string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void BaseTestBlock::testDefinition() { std::string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); } void BaseTestBlock::testMetadataAccess() { CPPUNIT_ASSERT(!block.metadata()); block.metadata(section); CPPUNIT_ASSERT(block.metadata()); // test none-unsetter block.metadata(none); CPPUNIT_ASSERT(!block.metadata()); // test deleter removing link too block.metadata(section); file.deleteSection(section.id()); CPPUNIT_ASSERT(!block.metadata()); // re-create section section = file.createSection("foo_section", "metadata"); } void BaseTestBlock::testSourceAccess() { std::vector<std::string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" }; Source s; CPPUNIT_ASSERT(!block.hasSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); CPPUNIT_ASSERT(!block.hasSource("invalid_id")); CPPUNIT_ASSERT_THROW(block.getSource(block.sourceCount() + 10), OutOfBounds); std::vector<std::string> ids; for (const auto &name : names) { Source src = block.createSource(name, "channel"); CPPUNIT_ASSERT(src.name() == name); CPPUNIT_ASSERT(block.hasSource(name)); CPPUNIT_ASSERT(block.hasSource(src)); ids.push_back(src.id()); } CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"), DuplicateName); CPPUNIT_ASSERT_THROW(block.createSource("", "test"), nix::EmptyString); CPPUNIT_ASSERT(block.sourceCount() == names.size()); CPPUNIT_ASSERT(block.sources().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getSource(block.sourceCount() + 10), OutOfBounds); for (const auto &id : ids) { Source src = block.getSource(id); CPPUNIT_ASSERT(block.hasSource(id) == true); CPPUNIT_ASSERT(src.id() == id); block.deleteSource(id); } s = block.createSource("test", "test"); CPPUNIT_ASSERT(block.sourceCount() == 1); CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); } void BaseTestBlock::testDataArrayAccess() { std::vector<std::string> names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; DataArray data_array, a; CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); CPPUNIT_ASSERT_THROW(block.getDataArray(block.dataArrayCount() + 10), OutOfBounds); std::vector<std::string> ids; for (const auto &name : names) { data_array = block.createDataArray(name, "channel", DataType::Double, nix::NDSize({ 0 })); CPPUNIT_ASSERT(data_array.name() == name); CPPUNIT_ASSERT(data_array.type() == "channel"); ids.push_back(data_array.id()); } CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })), DuplicateName); CPPUNIT_ASSERT_THROW(block.createDataArray("", "channel", DataType::Double, nix::NDSize({ 0 })), EmptyString); CPPUNIT_ASSERT(block.hasDataArray(data_array)); CPPUNIT_ASSERT(!block.hasDataArray(a)); CPPUNIT_ASSERT(block.dataArrayCount() == names.size()); CPPUNIT_ASSERT(block.dataArrays().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getDataArray(block.dataArrayCount() + 10), OutOfBounds); for (const auto &name : names) { DataArray da_name = block.getDataArray(name); CPPUNIT_ASSERT(da_name); DataArray da_id = block.getDataArray(da_name.id()); CPPUNIT_ASSERT(da_id); CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name()); } std::vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel")); CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size()); filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size()); if (filteredArrays.size() > 0) { boost::optional<std::string> name = filteredArrays[0].name(); CPPUNIT_ASSERT(name && *name == "data_array_c"); } for (auto it = ids.begin(); it != ids.end(); it++) { CPPUNIT_ASSERT(block.hasDataArray(*it)); CPPUNIT_ASSERT(block.getDataArray(*it).id() == *it); block.deleteDataArray(*it); } CPPUNIT_ASSERT(!block.deleteDataArray(a)); CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); } void BaseTestBlock::testTagAccess() { std::vector<std::string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; std::vector<std::string> array_names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; std::vector<DataArray> refs; Tag tag, t; for (const auto &name : array_names) { refs.push_back(block.createDataArray(name, "reference", DataType::Double, nix::NDSize({ 0 }))); } CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); CPPUNIT_ASSERT(!block.hasTag(t)); CPPUNIT_ASSERT_THROW(block.getTag(block.tagCount() + 10), OutOfBounds); std::vector<std::string> ids; for (auto it = names.begin(); it != names.end(); ++it) { tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4}); tag.references(refs); CPPUNIT_ASSERT(tag.name() == *it); CPPUNIT_ASSERT(block.hasTag(tag)); ids.push_back(tag.id()); } CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}), DuplicateName); CPPUNIT_ASSERT(block.tagCount() == names.size()); CPPUNIT_ASSERT(block.tags().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getTag(block.tagCount() + 10), OutOfBounds); for (auto it = ids.begin(); it != ids.end(); ++it) { tag = block.getTag(*it); CPPUNIT_ASSERT(block.hasTag(*it)); CPPUNIT_ASSERT(tag.id() == *it); block.deleteTag(*it); } tag = block.createTag("test", "test", {0.0}); CPPUNIT_ASSERT(block.hasTag(tag)); CPPUNIT_ASSERT(block.deleteTag(tag)); CPPUNIT_ASSERT(!block.deleteTag(t)); CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); } void BaseTestBlock::testMultiTagAccess() { std::vector<std::string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; MultiTag mtag, m; // create a valid positions data array below DataArray positions = block.createDataArray("array_one", "testdata", DataType::Double, nix::NDSize({ 3, 4, 2 })); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); CPPUNIT_ASSERT(!block.hasMultiTag(m)); CPPUNIT_ASSERT_THROW(block.getMultiTag(block.multiTagCount() + 10), OutOfBounds); std::vector<std::string> ids; for (auto it = names.begin(); it != names.end(); it++) { mtag = block.createMultiTag(*it, "segment", positions); CPPUNIT_ASSERT(mtag.name() == *it); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); ids.push_back(mtag.id()); } CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions), DuplicateName); CPPUNIT_ASSERT(block.multiTagCount() == names.size()); CPPUNIT_ASSERT(block.multiTags().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getMultiTag(block.multiTagCount() + 10), OutOfBounds); for (auto it = ids.begin(); it != ids.end(); it++) { mtag = block.getMultiTag(*it); CPPUNIT_ASSERT(block.hasMultiTag(*it)); CPPUNIT_ASSERT(mtag.id() == *it); block.deleteMultiTag(*it); } mtag = block.createMultiTag("test", "test", positions); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); CPPUNIT_ASSERT(!block.deleteMultiTag(m)); CPPUNIT_ASSERT(block.deleteMultiTag(mtag)); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); } void BaseTestBlock::testGroupAccess() { std::vector<std::string> names = { "group_a", "group_b", "group_c", "group_d", "group_e" }; Group g; CPPUNIT_ASSERT(!block.hasGroup(g)); CPPUNIT_ASSERT(block.groupCount() == 0); CPPUNIT_ASSERT(block.groups().size() == 0); CPPUNIT_ASSERT(block.getGroup("invalid_id") == false); CPPUNIT_ASSERT(!block.hasGroup("invalid_id")); CPPUNIT_ASSERT_THROW(block.getGroup(block.groupCount() + 10), OutOfBounds); std::vector<std::string> ids; for (const auto &name : names) { Group gr = block.createGroup(name, "group"); CPPUNIT_ASSERT(gr.name() == name); CPPUNIT_ASSERT(block.hasGroup(name)); CPPUNIT_ASSERT(block.hasGroup(gr)); ids.push_back(gr.id()); } CPPUNIT_ASSERT_THROW(block.createGroup(names[0], "group"), DuplicateName); CPPUNIT_ASSERT(block.groupCount() == names.size()); CPPUNIT_ASSERT(block.groups().size() == names.size()); CPPUNIT_ASSERT_THROW(block.getGroup(block.groupCount() + 10), OutOfBounds); for (const auto &id : ids) { Group gr = block.getGroup(id); CPPUNIT_ASSERT(block.hasGroup(id)); CPPUNIT_ASSERT(gr.id() == id); block.deleteGroup(id); } g = block.createGroup("test", "test"); CPPUNIT_ASSERT(block.groupCount() == 1); CPPUNIT_ASSERT(block.deleteGroup(g)); CPPUNIT_ASSERT(block.groupCount() == 0); CPPUNIT_ASSERT(block.groups().size() == 0); CPPUNIT_ASSERT(block.getGroup("invalid_id") == false); } void BaseTestBlock::testOperators() { CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); CPPUNIT_ASSERT(block != false); CPPUNIT_ASSERT(block != none); CPPUNIT_ASSERT(block == block); CPPUNIT_ASSERT(block != block_other); block_other = block; CPPUNIT_ASSERT(block == block_other); block_other = none; CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); std::stringstream str; str << block; } void BaseTestBlock::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void BaseTestBlock::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); } void BaseTestBlock::testCompare() { std::string other_name = block_other.name(); std::string block_name = block.name(); CPPUNIT_ASSERT(block.compare(block) == 0); CPPUNIT_ASSERT(block.compare(block_other) == block_name.compare(other_name)); } <|endoftext|>
<commit_before>#include "NotificationLoader.h" CNotificationLoader::CNotificationLoader() { m_hNotificationDLL = NULL; lpfn_Notify_FindClose = NULL; lpfn_Notify_FindFirst = NULL; lpfn_Notify_FindNext = NULL; lpfn_Notify_SetCycleInfo = NULL; lpfn_Notify_GetCycleInfo = NULL; lpfn_Notify_SetState = NULL; lpfn_Notify_GetState = NULL; int m_iBeeperIndex = -1; int m_iVibrateIndex = -1; } CNotificationLoader::~CNotificationLoader() { UnloadNotificationDLL(); } // Loading Notification DLL dynamically BOOL CNotificationLoader::LoadNotificationDLL() { m_hNotificationDLL = LoadLibrary(NOTIFY_DLL); if (!m_hNotificationDLL) { return FALSE; } // Map the function pointers to functions exported from the DLL lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindClose"); lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindNext"); lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindFirst"); lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_SetCycleInfo"); lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_GetCycleInfo"); lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_SetState"); lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_GetState"); if (lpfn_Notify_FindClose == NULL || lpfn_Notify_FindNext == NULL || lpfn_Notify_FindFirst == NULL || lpfn_Notify_SetCycleInfo== NULL || lpfn_Notify_GetCycleInfo== NULL || lpfn_Notify_SetState == NULL || lpfn_Notify_GetState == NULL) { m_hNotificationDLL = NULL; return FALSE; } else { // Set the indices of the beeper and vibrate index NOTIFY_FINDINFO notifyObject; HANDLE hFindHandle = NULL; SI_ALLOC_ALL(&notifyObject); notifyObject.StructInfo.dwUsed = 0; if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS) { int iObCount = 0; int m_iBeeperIndexForSoftwareOrHardware = 0; do { if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER) { // Found the Beeper if(m_iBeeperIndexForSoftwareOrHardware == 0) m_iBeeperIndexForSoftwareOrHardware = iObCount; m_iBeeperIndex = m_iBeeperIndexForSoftwareOrHardware; //continue; } else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR) { m_iVibrateIndex = iObCount; } iObCount++; SI_ALLOC_ALL(&notifyObject); notifyObject.StructInfo.dwUsed = 0; } while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS); } lpfn_Notify_FindClose(hFindHandle); return TRUE; } } BOOL CNotificationLoader::UnloadNotificationDLL() { if (m_hNotificationDLL) { FreeLibrary(m_hNotificationDLL); m_hNotificationDLL = NULL; lpfn_Notify_FindClose = NULL; lpfn_Notify_FindNext = NULL; lpfn_Notify_FindFirst = NULL; lpfn_Notify_SetCycleInfo= NULL; lpfn_Notify_GetCycleInfo= NULL; lpfn_Notify_SetState = NULL; lpfn_Notify_GetState = NULL; } return TRUE; } BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration) { if (m_iBeeperIndex < 0) return FALSE; CYCLE_INFO cycleInfo; SI_INIT(&cycleInfo); DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo); if(dwResult != E_NTFY_SUCCESS) return FALSE; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration; dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo); dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE); return TRUE; } BOOL CNotificationLoader::Vibrate(int iDuration) { if (m_iVibrateIndex < 0) return FALSE; CYCLE_INFO cycleInfo; SI_INIT(&cycleInfo); DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo); if(dwResult != E_NTFY_SUCCESS) return FALSE; cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration; dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo); dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE); return dwResult == E_NTFY_SUCCESS; } <commit_msg>Update NotificationLoader.cpp<commit_after>#include "NotificationLoader.h" CNotificationLoader::CNotificationLoader() { m_hNotificationDLL = NULL; lpfn_Notify_FindClose = NULL; lpfn_Notify_FindFirst = NULL; lpfn_Notify_FindNext = NULL; lpfn_Notify_SetCycleInfo = NULL; lpfn_Notify_GetCycleInfo = NULL; lpfn_Notify_SetState = NULL; lpfn_Notify_GetState = NULL; int m_iBeeperIndex = -1; int m_iVibrateIndex = -1; } CNotificationLoader::~CNotificationLoader() { UnloadNotificationDLL(); } // Loading Notification DLL dynamically BOOL CNotificationLoader::LoadNotificationDLL() { m_hNotificationDLL = LoadLibrary(NOTIFY_DLL); if (!m_hNotificationDLL) { return FALSE; } // Map the function pointers to functions exported from the DLL lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindClose"); lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindNext"); lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_FindFirst"); lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_SetCycleInfo"); lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_GetCycleInfo"); lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_SetState"); lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress (m_hNotificationDLL, L"NOTIFY_GetState"); if (lpfn_Notify_FindClose == NULL || lpfn_Notify_FindNext == NULL || lpfn_Notify_FindFirst == NULL || lpfn_Notify_SetCycleInfo== NULL || lpfn_Notify_GetCycleInfo== NULL || lpfn_Notify_SetState == NULL || lpfn_Notify_GetState == NULL) { m_hNotificationDLL = NULL; return FALSE; } else { // Set the indices of the beeper and vibrate index NOTIFY_FINDINFO notifyObject; HANDLE hFindHandle = NULL; SI_ALLOC_ALL(&notifyObject); notifyObject.StructInfo.dwUsed = 0; if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS) { int iObCount = 0; int m_iBeeperIndexForSoftwareOrHardware = 0; do { if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER) { // Found the Beeper if(m_iBeeperIndexForSoftwareOrHardware == 0) { m_iBeeperIndexForSoftwareOrHardware = iObCount; } m_iBeeperIndex = m_iBeeperIndexForSoftwareOrHardware; //continue; } else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR) { m_iVibrateIndex = iObCount; } iObCount++; SI_ALLOC_ALL(&notifyObject); notifyObject.StructInfo.dwUsed = 0; } while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS); } lpfn_Notify_FindClose(hFindHandle); return TRUE; } } BOOL CNotificationLoader::UnloadNotificationDLL() { if (m_hNotificationDLL) { FreeLibrary(m_hNotificationDLL); m_hNotificationDLL = NULL; lpfn_Notify_FindClose = NULL; lpfn_Notify_FindNext = NULL; lpfn_Notify_FindFirst = NULL; lpfn_Notify_SetCycleInfo= NULL; lpfn_Notify_GetCycleInfo= NULL; lpfn_Notify_SetState = NULL; lpfn_Notify_GetState = NULL; } return TRUE; } BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration) { if (m_iBeeperIndex < 0) return FALSE; CYCLE_INFO cycleInfo; SI_INIT(&cycleInfo); DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo); if(dwResult != E_NTFY_SUCCESS) return FALSE; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume; cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration; dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo); dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE); return TRUE; } BOOL CNotificationLoader::Vibrate(int iDuration) { if (m_iVibrateIndex < 0) return FALSE; CYCLE_INFO cycleInfo; SI_INIT(&cycleInfo); DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo); if(dwResult != E_NTFY_SUCCESS) return FALSE; cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration; dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo); dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE); return dwResult == E_NTFY_SUCCESS; } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "primBuilder.h" #include "gfxDevice.h" #include "console/console.h" //***************************************************************************** // Primitive Builder //***************************************************************************** namespace PrimBuild { Vector<GFXVertexPCT> mTempVertBuff; GFXVertexBufferHandle<GFXVertexPCT> mVertBuff; GFXPrimitiveType mType; U32 mCurVertIndex; ColorI mCurColor( 255, 255, 255 ); Point2F mCurTexCoord; const ColorI _colWhite( 255, 255, 255, 255 ); #ifdef TORQUE_DEBUG U32 mMaxVerts; #define INIT_VERTEX_SIZE(x) mMaxVerts = x; #define VERTEX_BOUNDS_CHECK() AssertFatal( mCurVertIndex < mMaxVerts, "PrimBuilder encountered an out of bounds vertex! Break and debug!" ); // This next check shouldn't really be used a lot unless you are tracking down // a specific bug. -pw #define VERTEX_SIZE_CHECK() AssertFatal( mCurVertIndex <= mMaxVerts, "PrimBuilder allocated more verts than you used! Break and debug or rendering artifacts could occur." ); #else #define INIT_VERTEX_SIZE(x) #define VERTEX_BOUNDS_CHECK() #define VERTEX_SIZE_CHECK() #endif //----------------------------------------------------------------------------- // begin //----------------------------------------------------------------------------- void begin( GFXPrimitiveType type, U32 maxVerts ) { AssertFatal( type >= GFXPT_FIRST && type < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); mType = type; mCurVertIndex = 0; INIT_VERTEX_SIZE( maxVerts ); mTempVertBuff.setSize( maxVerts ); } void beginToBuffer( GFXPrimitiveType type, U32 maxVerts ) { AssertFatal( type >= GFXPT_FIRST && type < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); mType = type; mCurVertIndex = 0; INIT_VERTEX_SIZE( maxVerts ); mTempVertBuff.setSize( maxVerts ); } //----------------------------------------------------------------------------- // end //----------------------------------------------------------------------------- GFXVertexBuffer * endToBuffer( U32 &numPrims ) { mVertBuff.set(GFX, mTempVertBuff.size(), GFXBufferTypeVolatile); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, mTempVertBuff.address(), mTempVertBuff.size() * sizeof(GFXVertexPCT) ); mVertBuff.unlock(); VERTEX_SIZE_CHECK(); switch( mType ) { case GFXPointList: { numPrims = mCurVertIndex; break; } case GFXLineList: { numPrims = mCurVertIndex / 2; break; } case GFXLineStrip: { numPrims = mCurVertIndex - 1; break; } case GFXTriangleList: { numPrims = mCurVertIndex / 3; break; } case GFXTriangleStrip: case GFXTriangleFan: { numPrims = mCurVertIndex - 2; break; } case GFXPT_COUNT: // handle warning break; } return mVertBuff; } void end( bool useGenericShaders ) { if ( mCurVertIndex == 0 ) return; VERTEX_SIZE_CHECK(); U32 vertStride = 1; U32 stripStart = 0; AssertFatal( mType >= GFXPT_FIRST && mType < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); switch( mType ) { default: case GFXPointList: { vertStride = 1; break; } case GFXLineList: { vertStride = 2; break; } case GFXTriangleList: { vertStride = 3; break; } case GFXLineStrip: { stripStart = 1; vertStride = 1; break; } case GFXTriangleStrip: case GFXTriangleFan: { stripStart = 2; vertStride = 1; break; } } if ( useGenericShaders ) { GFXStateBlock *currentBlock = GFX->getStateBlock(); if (currentBlock && currentBlock->getDesc().samplersDefined) { if (currentBlock->getDesc().vertexColorEnable) GFX->setupGenericShaders( GFXDevice::GSModColorTexture ); else GFX->setupGenericShaders( GFXDevice::GSTexture ); } else GFX->setupGenericShaders( GFXDevice::GSColor ); } const GFXVertexPCT *srcVerts = mTempVertBuff.address(); U32 numVerts = mCurVertIndex; // Make sure we don't have a dirty prim buffer left. GFX->setPrimitiveBuffer( NULL ); if ( stripStart > 0 ) { // TODO: Fix this to allow > MAX_DYNAMIC_VERTS! U32 copyVerts = getMin( (U32)MAX_DYNAMIC_VERTS, numVerts ); mVertBuff.set( GFX, copyVerts, GFXBufferTypeVolatile ); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, srcVerts, copyVerts * sizeof( GFXVertexPCT ) ); mVertBuff.unlock(); U32 numPrims = ( copyVerts / vertStride ) - stripStart; GFX->setVertexBuffer( mVertBuff ); GFX->drawPrimitive( mType, 0, numPrims ); } else { while ( numVerts > 0 ) { U32 copyVerts = getMin( (U32)MAX_DYNAMIC_VERTS, numVerts ); copyVerts -= copyVerts % vertStride; mVertBuff.set( GFX, copyVerts, GFXBufferTypeVolatile ); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, srcVerts, copyVerts * sizeof( GFXVertexPCT ) ); mVertBuff.unlock(); U32 numPrims = copyVerts / vertStride; GFX->setVertexBuffer( mVertBuff ); GFX->drawPrimitive( mType, 0, numPrims ); srcVerts += copyVerts; numVerts -= copyVerts; } } } //----------------------------------------------------------------------------- // vertex2f //----------------------------------------------------------------------------- void vertex2f( F32 x, F32 y ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.x = x; vert->point.y = y; vert->point.z = 0.0; vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex3f //----------------------------------------------------------------------------- void vertex3f( F32 x, F32 y, F32 z ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.x = x; vert->point.y = y; vert->point.z = z; vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex3fv //----------------------------------------------------------------------------- void vertex3fv( const F32 *data ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.set( data[0], data[1], data[2] ); vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex2fv //----------------------------------------------------------------------------- void vertex2fv( const F32 *data ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.set( data[0], data[1], 0.f ); vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // color //----------------------------------------------------------------------------- void color( const ColorI &inColor ) { mCurColor = inColor; } void color( const ColorF &inColor ) { mCurColor = inColor; } void color3i( U8 red, U8 green, U8 blue ) { mCurColor.set( red, green, blue ); } void color4i( U8 red, U8 green, U8 blue, U8 alpha ) { mCurColor.set( red, green, blue, alpha ); } void color3f( F32 red, F32 green, F32 blue ) { mCurColor.set( U8( red * 255 ), U8( green * 255 ), U8( blue * 255 ) ); } void color4f( F32 red, F32 green, F32 blue, F32 alpha ) { mCurColor.set( U8( red * 255 ), U8( green * 255 ), U8( blue * 255 ), U8( alpha * 255 ) ); } //----------------------------------------------------------------------------- // texCoord //----------------------------------------------------------------------------- void texCoord2f( F32 x, F32 y ) { mCurTexCoord.set( x, y ); } void shutdown() { mVertBuff = NULL; } } // namespace PrimBuild <commit_msg>Fix TAB vs Spaces on Engine/source/gfx/primBuilder.cpp<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "primBuilder.h" #include "gfxDevice.h" #include "console/console.h" //***************************************************************************** // Primitive Builder //***************************************************************************** namespace PrimBuild { Vector<GFXVertexPCT> mTempVertBuff; GFXVertexBufferHandle<GFXVertexPCT> mVertBuff; GFXPrimitiveType mType; U32 mCurVertIndex; ColorI mCurColor( 255, 255, 255 ); Point2F mCurTexCoord; const ColorI _colWhite( 255, 255, 255, 255 ); #ifdef TORQUE_DEBUG U32 mMaxVerts; #define INIT_VERTEX_SIZE(x) mMaxVerts = x; #define VERTEX_BOUNDS_CHECK() AssertFatal( mCurVertIndex < mMaxVerts, "PrimBuilder encountered an out of bounds vertex! Break and debug!" ); // This next check shouldn't really be used a lot unless you are tracking down // a specific bug. -pw #define VERTEX_SIZE_CHECK() AssertFatal( mCurVertIndex <= mMaxVerts, "PrimBuilder allocated more verts than you used! Break and debug or rendering artifacts could occur." ); #else #define INIT_VERTEX_SIZE(x) #define VERTEX_BOUNDS_CHECK() #define VERTEX_SIZE_CHECK() #endif //----------------------------------------------------------------------------- // begin //----------------------------------------------------------------------------- void begin( GFXPrimitiveType type, U32 maxVerts ) { AssertFatal( type >= GFXPT_FIRST && type < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); mType = type; mCurVertIndex = 0; INIT_VERTEX_SIZE( maxVerts ); mTempVertBuff.setSize( maxVerts ); } void beginToBuffer( GFXPrimitiveType type, U32 maxVerts ) { AssertFatal( type >= GFXPT_FIRST && type < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); mType = type; mCurVertIndex = 0; INIT_VERTEX_SIZE( maxVerts ); mTempVertBuff.setSize( maxVerts ); } //----------------------------------------------------------------------------- // end //----------------------------------------------------------------------------- GFXVertexBuffer * endToBuffer( U32 &numPrims ) { mVertBuff.set(GFX, mTempVertBuff.size(), GFXBufferTypeVolatile); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, mTempVertBuff.address(), mTempVertBuff.size() * sizeof(GFXVertexPCT) ); mVertBuff.unlock(); VERTEX_SIZE_CHECK(); switch( mType ) { case GFXPointList: { numPrims = mCurVertIndex; break; } case GFXLineList: { numPrims = mCurVertIndex / 2; break; } case GFXLineStrip: { numPrims = mCurVertIndex - 1; break; } case GFXTriangleList: { numPrims = mCurVertIndex / 3; break; } case GFXTriangleStrip: case GFXTriangleFan: { numPrims = mCurVertIndex - 2; break; } case GFXPT_COUNT: // handle warning break; } return mVertBuff; } void end( bool useGenericShaders ) { if ( mCurVertIndex == 0 ) return; VERTEX_SIZE_CHECK(); U32 vertStride = 1; U32 stripStart = 0; AssertFatal( mType >= GFXPT_FIRST && mType < GFXPT_COUNT, "PrimBuilder::end() - Bad primitive type!" ); switch( mType ) { default: case GFXPointList: { vertStride = 1; break; } case GFXLineList: { vertStride = 2; break; } case GFXTriangleList: { vertStride = 3; break; } case GFXLineStrip: { stripStart = 1; vertStride = 1; break; } case GFXTriangleStrip: case GFXTriangleFan: { stripStart = 2; vertStride = 1; break; } } if ( useGenericShaders ) { GFXStateBlock *currentBlock = GFX->getStateBlock(); if (currentBlock && currentBlock->getDesc().samplersDefined) { if (currentBlock->getDesc().vertexColorEnable) GFX->setupGenericShaders( GFXDevice::GSModColorTexture ); else GFX->setupGenericShaders( GFXDevice::GSTexture ); } else GFX->setupGenericShaders( GFXDevice::GSColor ); } const GFXVertexPCT *srcVerts = mTempVertBuff.address(); U32 numVerts = mCurVertIndex; // Make sure we don't have a dirty prim buffer left. GFX->setPrimitiveBuffer( NULL ); if ( stripStart > 0 ) { // TODO: Fix this to allow > MAX_DYNAMIC_VERTS! U32 copyVerts = getMin( (U32)MAX_DYNAMIC_VERTS, numVerts ); mVertBuff.set( GFX, copyVerts, GFXBufferTypeVolatile ); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, srcVerts, copyVerts * sizeof( GFXVertexPCT ) ); mVertBuff.unlock(); U32 numPrims = ( copyVerts / vertStride ) - stripStart; GFX->setVertexBuffer( mVertBuff ); GFX->drawPrimitive( mType, 0, numPrims ); } else { while ( numVerts > 0 ) { U32 copyVerts = getMin( (U32)MAX_DYNAMIC_VERTS, numVerts ); copyVerts -= copyVerts % vertStride; mVertBuff.set( GFX, copyVerts, GFXBufferTypeVolatile ); GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, srcVerts, copyVerts * sizeof( GFXVertexPCT ) ); mVertBuff.unlock(); U32 numPrims = copyVerts / vertStride; GFX->setVertexBuffer( mVertBuff ); GFX->drawPrimitive( mType, 0, numPrims ); srcVerts += copyVerts; numVerts -= copyVerts; } } } //----------------------------------------------------------------------------- // vertex2f //----------------------------------------------------------------------------- void vertex2f( F32 x, F32 y ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.x = x; vert->point.y = y; vert->point.z = 0.0; vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex3f //----------------------------------------------------------------------------- void vertex3f( F32 x, F32 y, F32 z ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.x = x; vert->point.y = y; vert->point.z = z; vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex3fv //----------------------------------------------------------------------------- void vertex3fv( const F32 *data ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.set( data[0], data[1], data[2] ); vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // vertex2fv //----------------------------------------------------------------------------- void vertex2fv( const F32 *data ) { VERTEX_BOUNDS_CHECK(); GFXVertexPCT *vert = &mTempVertBuff[mCurVertIndex++]; vert->point.set( data[0], data[1], 0.f ); vert->color = mCurColor; vert->texCoord = mCurTexCoord; } //----------------------------------------------------------------------------- // color //----------------------------------------------------------------------------- void color( const ColorI &inColor ) { mCurColor = inColor; } void color( const ColorF &inColor ) { mCurColor = inColor; } void color3i( U8 red, U8 green, U8 blue ) { mCurColor.set( red, green, blue ); } void color4i( U8 red, U8 green, U8 blue, U8 alpha ) { mCurColor.set( red, green, blue, alpha ); } void color3f( F32 red, F32 green, F32 blue ) { mCurColor.set( U8( red * 255 ), U8( green * 255 ), U8( blue * 255 ) ); } void color4f( F32 red, F32 green, F32 blue, F32 alpha ) { mCurColor.set( U8( red * 255 ), U8( green * 255 ), U8( blue * 255 ), U8( alpha * 255 ) ); } //----------------------------------------------------------------------------- // texCoord //----------------------------------------------------------------------------- void texCoord2f( F32 x, F32 y ) { mCurTexCoord.set( x, y ); } void shutdown() { mVertBuff = NULL; } } // namespace PrimBuild <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <iomanip> #include <kvs/StructuredVolumeObject> #include <kvs/StructuredVolumeImporter> #include <kvs/HydrogenVolumeData> #include <kvs/RayCastingRenderer> #include <kvs/Timer> #include <kvs/egl/Screen> int main( int argc, char** argv ) { kvs::StructuredVolumeObject* volume = NULL; if ( argc > 1 ) volume = new kvs::StructuredVolumeImporter( std::string( argv[1] ) ); else volume = new kvs::HydrogenVolumeData( kvs::Vec3u( 64, 64, 64 ) ); kvs::StructuredVolumeObject* object = volume; // kvs::RayCastingRenderer* renderer = new kvs::RayCastingRenderer(); kvs::glsl::RayCastingRenderer* renderer = new kvs::glsl::RayCastingRenderer(); kvs::egl::Screen screen; screen.setGeometry( 0, 0, 512, 512 ); screen.registerObject( object, renderer ); screen.displayInfo(); kvs::Timer timer( kvs::Timer::Start ); for ( size_t i = 0; i < 4; i++ ) { std::stringstream num; num << std::setw(3) << std::setfill('0') << i; std::string filename = "output_" + num.str() + ".bmp"; std::cout << "rendering to ... " << std::flush; object->multiplyXform( kvs::Xform::Rotation( kvs::Mat3::RotationY( 30 ) ) ); screen.draw(); screen.capture().write( filename ); std::cout << filename << std::endl; } timer.stop(); std::cout << "Total rendering time: " << timer.sec() << " [sec]" << std::endl; std::cout << "Average rendering time: " << timer.sec() / 4.0f << " [sec]" << std::endl; return 0; } <commit_msg>Modified.<commit_after>#include <iostream> #include <sstream> #include <iomanip> #include <kvs/StructuredVolumeObject> #include <kvs/StructuredVolumeImporter> #include <kvs/HydrogenVolumeData> #include <kvs/RayCastingRenderer> #include <kvs/Timer> #include <kvs/egl/Screen> int main( int argc, char** argv ) { std::cout << "EGL version: " << kvs::egl::Version() << std::endl; kvs::StructuredVolumeObject* volume = NULL; if ( argc > 1 ) volume = new kvs::StructuredVolumeImporter( std::string( argv[1] ) ); else volume = new kvs::HydrogenVolumeData( kvs::Vec3u( 64, 64, 64 ) ); kvs::StructuredVolumeObject* object = volume; // kvs::RayCastingRenderer* renderer = new kvs::RayCastingRenderer(); kvs::glsl::RayCastingRenderer* renderer = new kvs::glsl::RayCastingRenderer(); kvs::egl::Screen screen; screen.setGeometry( 0, 0, 512, 512 ); screen.registerObject( object, renderer ); screen.displayInfo(); kvs::Timer timer( kvs::Timer::Start ); for ( size_t i = 0; i < 12; i++ ) { std::stringstream num; num << std::setw(3) << std::setfill('0') << i; std::string filename = "output_" + num.str() + ".bmp"; std::cout << "rendering to ... " << std::flush; object->multiplyXform( kvs::Xform::Rotation( kvs::Mat3::RotationY( 30 ) ) ); screen.draw(); screen.capture().write( filename ); std::cout << filename << std::endl; } timer.stop(); std::cout << "Total rendering time: " << timer.sec() << " [sec]" << std::endl; std::cout << "Average rendering time: " << timer.sec() / 4.0f << " [sec]" << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include "gtest/gtest.h" #include <hspp/Managers/GameAgent.hpp> #include <hspp/Tasks/PlayerTasks/BriefTask.hpp> using namespace Hearthstonepp; using namespace PlayerTasks; TEST(BriefTask, GetTaskID) { const BriefTask brief; EXPECT_EQ(brief.GetTaskID(), +TaskID::BRIEF); } TEST(BriefTask, Run) { BriefTask brief; GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1); agent.GetPlayer1().SetID(100); MetaData result = brief.Run(agent.GetPlayer1()); EXPECT_EQ(result, MetaData::BRIEF); TaskMeta meta; result = brief.Run(agent.GetPlayer1(), meta); EXPECT_EQ(result, MetaData::BRIEF); EXPECT_EQ(meta.GetID(), +TaskID::BRIEF); EXPECT_EQ(meta.GetStatus(), MetaData::BRIEF); EXPECT_EQ(meta.GetUserID(), agent.GetPlayer1().GetID()); } <commit_msg>refactor: Replace GameAgent to Game<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include "gtest/gtest.h" #include <hspp/Game/Game.hpp> #include <hspp/Tasks/PlayerTasks/BriefTask.hpp> using namespace Hearthstonepp; using namespace PlayerTasks; TEST(BriefTask, GetTaskID) { const BriefTask brief; EXPECT_EQ(brief.GetTaskID(), +TaskID::BRIEF); } TEST(BriefTask, Run) { BriefTask brief; Game game(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1); game.GetPlayer1().SetID(100); MetaData result = brief.Run(game.GetPlayer1()); EXPECT_EQ(result, MetaData::BRIEF); } <|endoftext|>
<commit_before>// PWHistDlg.cpp : implementation file // #include "stdafx.h" #include "PasswordSafe.h" #include "ThisMfcApp.h" #include "resource.h" #include "PWHistDlg.h" #include "corelib/ItemData.h" #include ".\pwhistdlg.h" // CPWHistDlg dialog IMPLEMENT_DYNAMIC(CPWHistDlg, CDialog) CPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly, CMyString &HistStr, PWHistList &PWHistList, int NumPWHistory, int &MaxPWHistory, BOOL &SavePWHistory) : CDialog(CPWHistDlg::IDD, pParent), m_IsReadOnly(IsReadOnly), m_HistStr(HistStr), m_PWHistList(PWHistList), m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory), m_SavePWHistory(SavePWHistory), m_ClearPWHistory(false), m_iSortedColumn(-1), m_bSortAscending(TRUE) { m_oldMaxPWHistory = m_MaxPWHistory; } CPWHistDlg::~CPWHistDlg() { } void CPWHistDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl); DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory); DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory); DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 25); } BEGIN_MESSAGE_MAP(CPWHistDlg, CDialog) ON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist) ON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) ON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick) ON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll) END_MESSAGE_MAP() BOOL CPWHistDlg::OnInitDialog() { CDialog::OnInitDialog(); GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE); BOOL bpwh_count = (m_PWHistList.GetCount() == 0) ? FALSE : TRUE; GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count); GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count); if (m_IsReadOnly) { GetDlgItem(IDOK)->EnableWindow(FALSE); GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE); GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE); // overrides count } m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_PWHistListCtrl.InsertColumn(0, _T("Set Date/Time")); m_PWHistListCtrl.InsertColumn(1, _T("Password")); int nPos = 0; POSITION itempos; POSITION listpos = m_PWHistList.GetHeadPosition(); while (listpos != NULL) { itempos = listpos; const PWHistEntry pwhentry = m_PWHistList.GetAt(listpos); nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate); m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password); m_PWHistListCtrl.SetItemData(nPos, (DWORD)itempos); m_PWHistList.GetNext(listpos); } m_PWHistListCtrl.SetRedraw(FALSE); for (int i = 0; i < 2; i++) { m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i); m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i); m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_PWHistListCtrl.SetRedraw(TRUE); char buffer[10]; #if _MSC_VER >= 1400 sprintf_s(buffer, 10, "%d", m_NumPWHistory); #else sprintf(buffer, "%d", m_NumPWHistory); #endif CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN); if (m_MaxPWHistory == 0) m_MaxPWHistory = 1; pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY)); pspin->SetRange(1, 25); pspin->SetBase(10); pspin->SetPos(m_MaxPWHistory); return TRUE; } // CPWHistDlg message handlers void CPWHistDlg::OnBnClickedClearPWHist() { m_ClearPWHistory = true; m_PWHistListCtrl.DeleteAllItems(); } void CPWHistDlg::OnOK() { UpdateData(TRUE); /* Handle history header. * Header is in the form fmmnn, where: * f = {0,1} if password history is on/off * mm = 2 digits max size of history list * nn = 2 digits current size of history list * * Special case: history empty and password history off - do nothing */ const CMyString oldHistStr = m_HistStr; if (m_ClearPWHistory == TRUE) { m_PWHistList.RemoveAll(); m_HistStr = m_HistStr.Left(5); } if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) { TCHAR buffer[6]; #if _MSC_VER >= 1400 sprintf_s #else sprintf #endif (buffer, #if _MSC_VER >= 1400 6, #endif "%1x%02x%02x", (m_SavePWHistory == FALSE) ? 0 : 1, m_MaxPWHistory, m_PWHistList.GetCount() ); if (m_HistStr.GetLength() >= 5) { for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]); } else { m_HistStr = buffer; } } CDialog::OnOK(); } void CPWHistDlg::OnCheckedSavePasswordHistory() { m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck(); GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE); } void CPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*) { LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR; ASSERT(lpnmitem != NULL); int item = lpnmitem->iItem; POSITION itempos = POSITION(m_PWHistListCtrl.GetItemData(item)); const PWHistEntry pwhentry = m_PWHistList.GetAt(itempos); app.SetClipboardData(pwhentry.password); } void CPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_PWHistListCtrl.SortItems(CompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CPWHistDlg::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CPWHistDlg *self = (CPWHistDlg*)closure; int nSortColumn = self->m_iSortedColumn; POSITION Lpos = (POSITION)lParam1; POSITION Rpos = (POSITION)lParam2; const PWHistEntry pLHS = self->m_PWHistList.GetAt(Lpos); const PWHistEntry pRHS = self->m_PWHistList.GetAt(Rpos); CMyString password1, changedate1; CMyString password2, changedate2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: t1 = pLHS.changetttdate; t2 = pRHS.changetttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; case 1: password1 = pLHS.password; password2 = pRHS.password; iResult = ((CString)password1).Compare(password2); break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } void CPWHistDlg::OnBnClickedPwhCopyAll() { CMyString HistStr; POSITION pos = m_PWHistList.GetHeadPosition(); while (pos != NULL) { const PWHistEntry &ent = m_PWHistList.GetNext(pos); HistStr += ent.changedate; HistStr += _T("\t"); HistStr += ent.password; HistStr += _T("\r\n"); } app.SetClipboardData(HistStr); } <commit_msg>Fix [1529305] Crash in Password History<commit_after>// PWHistDlg.cpp : implementation file // #include "stdafx.h" #include "PasswordSafe.h" #include "ThisMfcApp.h" #include "resource.h" #include "PWHistDlg.h" #include "corelib/ItemData.h" #include ".\pwhistdlg.h" // CPWHistDlg dialog IMPLEMENT_DYNAMIC(CPWHistDlg, CDialog) CPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly, CMyString &HistStr, PWHistList &PWHistList, int NumPWHistory, int &MaxPWHistory, BOOL &SavePWHistory) : CDialog(CPWHistDlg::IDD, pParent), m_IsReadOnly(IsReadOnly), m_HistStr(HistStr), m_PWHistList(PWHistList), m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory), m_SavePWHistory(SavePWHistory), m_ClearPWHistory(false), m_iSortedColumn(-1), m_bSortAscending(TRUE) { m_oldMaxPWHistory = m_MaxPWHistory; } CPWHistDlg::~CPWHistDlg() { } void CPWHistDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl); DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory); DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory); DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 25); } BEGIN_MESSAGE_MAP(CPWHistDlg, CDialog) ON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist) ON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) ON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick) ON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll) END_MESSAGE_MAP() BOOL CPWHistDlg::OnInitDialog() { CDialog::OnInitDialog(); GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE); BOOL bpwh_count = (m_PWHistList.GetCount() == 0) ? FALSE : TRUE; GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count); GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count); if (m_IsReadOnly) { GetDlgItem(IDOK)->EnableWindow(FALSE); GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE); GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE); // overrides count } m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_PWHistListCtrl.InsertColumn(0, _T("Set Date/Time")); m_PWHistListCtrl.InsertColumn(1, _T("Password")); int nPos = 0; POSITION itempos; POSITION listpos = m_PWHistList.GetHeadPosition(); while (listpos != NULL) { itempos = listpos; const PWHistEntry pwhentry = m_PWHistList.GetAt(listpos); nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate); m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password); m_PWHistListCtrl.SetItemData(nPos, (DWORD)itempos); m_PWHistList.GetNext(listpos); } m_PWHistListCtrl.SetRedraw(FALSE); for (int i = 0; i < 2; i++) { m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i); m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i); m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_PWHistListCtrl.SetRedraw(TRUE); char buffer[10]; #if _MSC_VER >= 1400 sprintf_s(buffer, 10, "%d", m_NumPWHistory); #else sprintf(buffer, "%d", m_NumPWHistory); #endif CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN); if (m_MaxPWHistory == 0) m_MaxPWHistory = 1; pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY)); pspin->SetRange(1, 25); pspin->SetBase(10); pspin->SetPos(m_MaxPWHistory); return TRUE; } // CPWHistDlg message handlers void CPWHistDlg::OnBnClickedClearPWHist() { m_ClearPWHistory = true; m_PWHistListCtrl.DeleteAllItems(); } void CPWHistDlg::OnOK() { UpdateData(TRUE); /* Handle history header. * Header is in the form fmmnn, where: * f = {0,1} if password history is on/off * mm = 2 digits max size of history list * nn = 2 digits current size of history list * * Special case: history empty and password history off - do nothing */ const CMyString oldHistStr = m_HistStr; if (m_ClearPWHistory == TRUE) { m_PWHistList.RemoveAll(); m_HistStr = m_HistStr.Left(5); } if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) { TCHAR buffer[6]; #if _MSC_VER >= 1400 sprintf_s #else sprintf #endif (buffer, #if _MSC_VER >= 1400 6, #endif "%1x%02x%02x", (m_SavePWHistory == FALSE) ? 0 : 1, m_MaxPWHistory, m_PWHistList.GetCount() ); if (m_HistStr.GetLength() >= 5) { for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]); } else { m_HistStr = buffer; } } CDialog::OnOK(); } void CPWHistDlg::OnCheckedSavePasswordHistory() { m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck(); GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE); } void CPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*) { LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR; ASSERT(lpnmitem != NULL); int item = lpnmitem->iItem; if (item == -1) return; POSITION itempos = POSITION(m_PWHistListCtrl.GetItemData(item)); const PWHistEntry pwhentry = m_PWHistList.GetAt(itempos); app.SetClipboardData(pwhentry.password); } void CPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_PWHistListCtrl.SortItems(CompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CPWHistDlg::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CPWHistDlg *self = (CPWHistDlg*)closure; int nSortColumn = self->m_iSortedColumn; POSITION Lpos = (POSITION)lParam1; POSITION Rpos = (POSITION)lParam2; const PWHistEntry pLHS = self->m_PWHistList.GetAt(Lpos); const PWHistEntry pRHS = self->m_PWHistList.GetAt(Rpos); CMyString password1, changedate1; CMyString password2, changedate2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: t1 = pLHS.changetttdate; t2 = pRHS.changetttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; case 1: password1 = pLHS.password; password2 = pRHS.password; iResult = ((CString)password1).Compare(password2); break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } void CPWHistDlg::OnBnClickedPwhCopyAll() { CMyString HistStr; POSITION pos = m_PWHistList.GetHeadPosition(); while (pos != NULL) { const PWHistEntry &ent = m_PWHistList.GetNext(pos); HistStr += ent.changedate; HistStr += _T("\t"); HistStr += ent.password; HistStr += _T("\r\n"); } app.SetClipboardData(HistStr); } <|endoftext|>
<commit_before>#include "websocketbroker.h" #include "logger.h" #include <QJsonDocument> #include <QJsonArray> #include <QVector> #include <QFile> #include <QCoreApplication> #include <QRegularExpression> WebSocketBroker::WebSocketBroker(const QString& vssFile) { loadJson(vssFile); loadTempSignalList(); connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketBroker::onConnected); //connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketBroker::closed); m_webSocket.open(QUrl("ws://localhost:42")); } bool WebSocketBroker::getSignalValue(const QString& path, QJsonArray& values) { // Check if path is single leaf. // Check if path is single branch. // Check if path contains asterisk. // Check if path contains asterisk and leaf. QJsonArray paths = parseGetPath(path); // Check if signal exists. if(checkSignals(paths, true)) { return false; } // Create message to send QJsonObject message; message.insert("get", paths); QJsonDocument jsonDoc(message); // Lock and send message. QMutexLocker locker(&m_mutex); sendMessage(jsonDoc.toJson()); // TODO Need to implement some kind of timer here. while(!m_messageReceivedFromBroker) { //DEBUG("TEST","Waiting for response..."); } jsonDoc = QJsonDocument(m_receivedMessage); // TODO Add check of Success in response. // Could just return false, instead of array, if error? if(jsonDoc.object()["get"].isArray()) { values = jsonDoc.object()["get"].toArray(); return true; } return false; } bool WebSocketBroker::setSignalValue(const QString& path, const QVariant& values) { QJsonArray paths = parseSetPath(path, values.toJsonValue()); // Check if signal exists. if(checkSignals(paths, false)) { return false; } // Create message to send QJsonObject message; message.insert("set", paths); QJsonDocument jsonDoc(message); // Lock and send message. QMutexLocker locker(&m_mutex); sendMessage(jsonDoc.toJson()); // TODO Need to implement some kind of timer here. while(!m_messageReceivedFromBroker) { //DEBUG("TEST","Waiting for response..."); } jsonDoc = QJsonDocument(m_receivedMessage); // Should return false, or 0 if not bool. So should work without checking if bool return jsonDoc.object()["set"].toBool(); } QJsonObject WebSocketBroker::getVSSNode(const QString& path) { // clear old m_vssTreeNode = QJsonObject(); if (m_vssTree.empty()) { DEBUG("Server","Empty VSS tree. Returning empty node."); return m_vssTreeNode; } else if (path == "") { DEBUG("Server","Empty path. Returning full tree."); return m_vssTree; } else { QStringList tokens = path.split('.'); // Make a copy of the full tree QJsonObject tree = m_vssTree; QVector<JsonNode> nodes; getTreeNodes(tree, tokens, nodes); QJsonObject obj; createJsonVssTree(nodes, obj); return m_vssTreeNode; } } QJsonObject WebSocketBroker::getVSSTree(const QString& path) { QString p = path; QJsonObject tree; return tree; } void WebSocketBroker::sendMessage(const QString& message) { m_messageReceivedFromBroker = false; m_webSocket.sendTextMessage(message); m_webSocket.flush(); } void WebSocketBroker::onConnected() { connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketBroker::onTextMessageReceived); } void WebSocketBroker::onTextMessageReceived(QString message) { QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &parseError); if(parseError.error != QJsonParseError::NoError) { m_receivedMessage = doc.object(); // Change to error. m_messageReceivedFromBroker = true; return; } m_receivedMessage = doc.object(); m_messageReceivedFromBroker = true; } void WebSocketBroker::getTreeNodes(QJsonObject& tree, QStringList& path, QVector<JsonNode>& nodes) { if (path.length() > 0) { QString key = path[0]; JsonNode node; node.isBranch = path.length() > 1; node.key = key; if (node.isBranch) { removeAllKeysButOne(tree, key); } tree = tree.value(key).toObject(); QJsonObject treeCopy = tree; if (node.isBranch) { removeOne(treeCopy, "children"); tree = tree.value("children").toObject(); } node.json = treeCopy; nodes.push_front(node); path.removeFirst(); getTreeNodes(tree, path, nodes); } } void WebSocketBroker::createJsonVssTree(QVector<JsonNode>& nodes, QJsonObject& json) { if (nodes.size() > 0) { JsonNode node = nodes.first(); QJsonObject obj; if (node.isBranch) { node.json.insert("children", json); obj.insert(node.key, node.json); } else { obj.insert(node.key, node.json); } nodes.removeFirst(); createJsonVssTree(nodes, obj); } else { m_vssTreeNode = json; } } void WebSocketBroker::removeAllKeysButOne(QJsonObject& json, const QString& filter) { foreach (QString key, json.keys()) { if (filter != key) { json.remove(key); } } } void WebSocketBroker::removeOne(QJsonObject& json, const QString& filter) { foreach (QString key, json.keys()) { if (filter == key) { json.remove(key); } } } void WebSocketBroker::loadJson(const QString &fileName) { QFile jsonFile(fileName); QJsonDocument doc; if (jsonFile.exists()) { jsonFile.open(QFile::ReadOnly); doc = QJsonDocument().fromJson(jsonFile.readAll()); } else { WARNING("Server",QString("VSS File %1 not found!").arg(fileName)); } m_vssTree = doc.object(); } void WebSocketBroker::loadTempSignalList() { QRegularExpression regex(QString("^(\\S+) \\d+")); QFile file(QCoreApplication::applicationDirPath() + "/vss_rel_1.vsi"); file.open(QFile::ReadOnly); if(!file.exists()) { WARNING("Server", "The flattened vsi signal file could not be found for the Signal Broker!"); file.close(); return; } while(!file.atEnd()) { QRegularExpressionMatch match = regex.match(file.readLine()); if(match.hasMatch()) { m_tempSignalList.append(match.captured(1).trimmed()); } } } QJsonArray WebSocketBroker::parseGetPath(const QString& path) { QStringList sl = splitPath(path); QJsonArray values; if(sl.length() == 1) foreach(auto const item, getPath(sl.first())) { QJsonObject value; value.insert(item,""); values.append(value); } else foreach(auto const item, getPath(sl.first(), sl.last())) { QJsonObject value; value.insert(item,""); values.append(value); } return values; } QJsonArray WebSocketBroker::parseSetPath(const QString& path, const QJsonValue &setValues) { QStringList sl = splitPath(path); QJsonArray values; if(setValues.isArray()) { foreach(QJsonValue const val, setValues.toArray()) { QJsonObject value; QJsonObject obj = val.toObject(); QString valuePath = sl.first() + "." + obj.keys().first(); QJsonValue tmp = obj.value(obj.keys().first()); if(tmp.isDouble()) { value.insert(valuePath, tmp.toDouble()); } else if(tmp.isBool()) { value.insert(valuePath, tmp.toBool()); } else { value.insert(valuePath, tmp.toString()); } values.append(value); } } else { QJsonObject value; if(setValues.isDouble()) { value.insert(path, setValues.toDouble()); } else if(setValues.isBool()) { value.insert(path, setValues.toBool()); } else { value.insert(path, setValues.toString()); } values .append(value); } return values; } bool WebSocketBroker::checkSignals(const QJsonArray &paths, bool getOrSet) { foreach (QJsonValue const &value, paths) { QJsonObject signal = getVSSNode(value.toString()); if(signal.isEmpty()) { return false; } if(getOrSet) { // TODO Check if the signal is ok to get } else { // TODO Check if the signal is ok to set } } return true; } QStringList WebSocketBroker::getPath(QString startsWith) { return getPath(startsWith, ""); } QStringList WebSocketBroker::getPath(QString startsWith, QString endsWith) { return m_tempSignalList.filter(QRegularExpression(QString("^%1.*%2$").arg(startsWith, endsWith))); } QStringList WebSocketBroker::splitPath(QString path) { QStringList sl; int i = path.lastIndexOf("*"); if(i == -1) { sl << path; return sl; } foreach(QString item, path.split("*")) { // Trim '.' from items. if(item.startsWith(".")) { item = item.remove(0,1); } if(item.endsWith(".")) { item = item.remove(item.length() -1, 1); } sl << item; } return sl; } <commit_msg>Fixed some bugs in signal broker.<commit_after>#include "websocketbroker.h" #include "logger.h" #include <QJsonDocument> #include <QJsonArray> #include <QVector> #include <QFile> #include <QCoreApplication> #include <QRegularExpression> WebSocketBroker::WebSocketBroker(const QString& vssFile) { loadJson(vssFile); loadTempSignalList(); connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketBroker::onConnected); //connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketBroker::closed); m_webSocket.open(QUrl("ws://localhost:8008")); } bool WebSocketBroker::getSignalValue(const QString& path, QJsonArray& values) { // Check if path is single leaf. // Check if path is single branch. // Check if path contains asterisk. // Check if path contains asterisk and leaf. QJsonArray paths = parseGetPath(path); // Check if signal exists. if(!checkSignals(paths, true)) { return false; } // Create message to send QJsonObject message; message.insert("get", paths); QJsonDocument jsonDoc(message); // Lock and send message. QMutexLocker locker(&m_mutex); sendMessage(jsonDoc.toJson()); // TODO Need to implement some kind of timer here. while(!m_messageReceivedFromBroker) { //DEBUG("TEST","Waiting for response..."); } jsonDoc = QJsonDocument(m_receivedMessage); // TODO Add check of Success in response. // Could just return false, instead of array, if error? if(jsonDoc.object()["get"].isArray()) { values = jsonDoc.object()["get"].toArray(); return true; } return false; } bool WebSocketBroker::setSignalValue(const QString& path, const QVariant& values) { QJsonArray paths = parseSetPath(path, values.toJsonValue()); // Check if signal exists. if(!checkSignals(paths, false)) { return false; } // Create message to send QJsonObject message; message.insert("set", paths); QJsonDocument jsonDoc(message); // Lock and send message. QMutexLocker locker(&m_mutex); sendMessage(jsonDoc.toJson()); // TODO Need to implement some kind of timer here. while(!m_messageReceivedFromBroker) { //DEBUG("TEST","Waiting for response..."); } jsonDoc = QJsonDocument(m_receivedMessage); // Should return false, or 0 if not bool. So should work without checking if bool return jsonDoc.object()["set"].toBool(); } QJsonObject WebSocketBroker::getVSSNode(const QString& path) { // clear old m_vssTreeNode = QJsonObject(); if (m_vssTree.empty()) { DEBUG("Server","Empty VSS tree. Returning empty node."); return m_vssTreeNode; } else if (path == "") { DEBUG("Server","Empty path. Returning full tree."); return m_vssTree; } else { QStringList tokens = path.split('.'); // Make a copy of the full tree QJsonObject tree = m_vssTree; QVector<JsonNode> nodes; getTreeNodes(tree, tokens, nodes); QJsonObject obj; createJsonVssTree(nodes, obj); return m_vssTreeNode; } } QJsonObject WebSocketBroker::getVSSTree(const QString& path) { QString p = path; QJsonObject tree; return tree; } void WebSocketBroker::sendMessage(const QString& message) { m_messageReceivedFromBroker = false; m_webSocket.sendTextMessage(message); m_webSocket.flush(); } void WebSocketBroker::onConnected() { connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketBroker::onTextMessageReceived); } void WebSocketBroker::onTextMessageReceived(QString message) { QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &parseError); if(parseError.error != QJsonParseError::NoError) { m_receivedMessage = doc.object(); // Change to error. m_messageReceivedFromBroker = true; return; } m_receivedMessage = doc.object(); m_messageReceivedFromBroker = true; } void WebSocketBroker::getTreeNodes(QJsonObject& tree, QStringList& path, QVector<JsonNode>& nodes) { if (path.length() > 0) { QString key = path[0]; JsonNode node; node.isBranch = path.length() > 1; node.key = key; if (node.isBranch) { removeAllKeysButOne(tree, key); } tree = tree.value(key).toObject(); QJsonObject treeCopy = tree; if (node.isBranch) { removeOne(treeCopy, "children"); tree = tree.value("children").toObject(); } node.json = treeCopy; nodes.push_front(node); path.removeFirst(); getTreeNodes(tree, path, nodes); } } void WebSocketBroker::createJsonVssTree(QVector<JsonNode>& nodes, QJsonObject& json) { if (nodes.size() > 0) { JsonNode node = nodes.first(); QJsonObject obj; if (node.isBranch) { node.json.insert("children", json); obj.insert(node.key, node.json); } else { obj.insert(node.key, node.json); } nodes.removeFirst(); createJsonVssTree(nodes, obj); } else { m_vssTreeNode = json; } } void WebSocketBroker::removeAllKeysButOne(QJsonObject& json, const QString& filter) { foreach (QString key, json.keys()) { if (filter != key) { json.remove(key); } } } void WebSocketBroker::removeOne(QJsonObject& json, const QString& filter) { foreach (QString key, json.keys()) { if (filter == key) { json.remove(key); } } } void WebSocketBroker::loadJson(const QString &fileName) { QFile jsonFile(fileName); QJsonDocument doc; if (jsonFile.exists()) { jsonFile.open(QFile::ReadOnly); doc = QJsonDocument().fromJson(jsonFile.readAll()); } else { WARNING("Server",QString("VSS File %1 not found!").arg(fileName)); } m_vssTree = doc.object(); } void WebSocketBroker::loadTempSignalList() { QRegularExpression regex(QString("^(\\S+) \\d+")); QFile file(QCoreApplication::applicationDirPath() + "/vss_rel_1.vsi"); file.open(QFile::ReadOnly); if(!file.exists()) { WARNING("Server", "The flattened vsi signal file could not be found for the Signal Broker!"); file.close(); return; } while(!file.atEnd()) { QRegularExpressionMatch match = regex.match(file.readLine()); if(match.hasMatch()) { m_tempSignalList.append(match.captured(1).trimmed()); } } } QJsonArray WebSocketBroker::parseGetPath(const QString& path) { QStringList sl = splitPath(path); QJsonArray values; if(sl.length() == 1) foreach(auto const item, getPath(sl.first())) { QJsonObject value; value.insert(item,""); values.append(value); } else foreach(auto const item, getPath(sl.first(), sl.last())) { QJsonObject value; value.insert(item,""); values.append(value); } return values; } QJsonArray WebSocketBroker::parseSetPath(const QString& path, const QJsonValue &setValues) { QStringList sl = splitPath(path); QJsonArray values; if(setValues.isArray()) { foreach(QJsonValue const val, setValues.toArray()) { QJsonObject value; QJsonObject obj = val.toObject(); QString valuePath = sl.first() + "." + obj.keys().first(); QJsonValue tmp = obj.value(obj.keys().first()); if(tmp.isDouble()) { value.insert(valuePath, tmp.toDouble()); } else if(tmp.isBool()) { value.insert(valuePath, tmp.toBool()); } else { value.insert(valuePath, tmp.toString()); } values.append(value); } } else { QJsonObject value; if(setValues.isDouble()) { value.insert(path, setValues.toDouble()); } else if(setValues.isBool()) { value.insert(path, setValues.toBool()); } else { value.insert(path, setValues.toString()); } values .append(value); } return values; } bool WebSocketBroker::checkSignals(const QJsonArray &paths, bool getOrSet) { foreach (QJsonValue const &obj, paths) { foreach (QJsonValue key, obj.toObject().keys()) { QJsonObject signal = getVSSNode(key.toString()); if(signal.isEmpty()) { return false; } if(getOrSet) { // TODO Check if the signal is ok to get } else { // TODO Check if the signal is ok to set // Check if set is correct type } } } return true; } QStringList WebSocketBroker::getPath(QString startsWith) { return getPath(startsWith, ""); } QStringList WebSocketBroker::getPath(QString startsWith, QString endsWith) { return m_tempSignalList.filter(QRegularExpression(QString("^%1.*%2$").arg(startsWith, endsWith))); } QStringList WebSocketBroker::splitPath(QString path) { QStringList sl; int i = path.lastIndexOf("*"); if(i == -1) { sl << path; return sl; } foreach(QString item, path.split("*")) { // Trim '.' from items. if(item.startsWith(".")) { item = item.remove(0,1); } if(item.endsWith(".")) { item = item.remove(item.length() -1, 1); } sl << item; } return sl; } <|endoftext|>
<commit_before>/* * opencog/atoms/core/Checkers.cc * * Copyright (C) 2017 Linas Vepstas * 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 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 <opencog/atoms/base/Atom.h> #include <opencog/atoms/base/ClassServer.h> using namespace opencog; /// Provide static factory-time type checking. /// This only performs a very simple kind of type checking; /// it does not check deep types, nor does it check arity. /// Check to see if every input atom is of Evaluatable type. bool check_evaluatable(const Handle& bool_atom) { // Make an exception for AndLink, its used in pattern matcher // in an unseemly way. if (bool_atom->get_type() == AND_LINK) return true; for (const Handle& h: bool_atom->getOutgoingSet()) { Type t = h->get_type(); // PutLinks and GetLinks cannot be type-checked statically. // Checking has to be defered until runtime. if (PUT_LINK == t) continue; if (GET_LINK == t) continue; if (VARIABLE_NODE == t) continue; // Fucking quote links. I hate those with a passion. if (QUOTE_LINK == t) continue; if (UNQUOTE_LINK == t) continue; if (not h->is_type(EVALUATABLE_LINK)) return false; } return true; } /// Check to see if every input atom is of Numeric type. bool check_numeric(const Handle& bool_atom) { for (const Handle& h: bool_atom->getOutgoingSet()) { Type t = h->get_type(); // PutLinks and GetLinks cannot be type-checked statically. // Checking has to be defered until runtime. if (PUT_LINK == t) continue; if (GET_LINK == t) continue; if (VARIABLE_NODE == t) continue; if (NUMBER_NODE == t) continue; // Oddly enough, sets of numbers are allowed. if (SET_LINK == t and check_numeric(h)) continue; if (not h->is_type(NUMERIC_OUTPUT_LINK)) return false; } return true; } /* This runs when the shared lib is loaded. */ static __attribute__ ((constructor)) void init(void) { classserver().addValidator(BOOLEAN_LINK, check_evaluatable); classserver().addValidator(NUMERIC_LINK, check_numeric); } <commit_msg>Another allowed type<commit_after>/* * opencog/atoms/core/Checkers.cc * * Copyright (C) 2017 Linas Vepstas * 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 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 <opencog/atoms/base/Atom.h> #include <opencog/atoms/base/ClassServer.h> using namespace opencog; /// Provide static factory-time type checking. /// This only performs a very simple kind of type checking; /// it does not check deep types, nor does it check arity. /// Check to see if every input atom is of Evaluatable type. bool check_evaluatable(const Handle& bool_atom) { // Make an exception for AndLink, its used in pattern matcher // in an unseemly way. if (bool_atom->get_type() == AND_LINK) return true; for (const Handle& h: bool_atom->getOutgoingSet()) { Type t = h->get_type(); // PutLinks and GetLinks cannot be type-checked statically. // Checking has to be defered until runtime. if (PUT_LINK == t) continue; if (GET_LINK == t) continue; if (VARIABLE_NODE == t) continue; if (DEFINED_PREDICATE_NODE == t) continue; // Fucking quote links. I hate those with a passion. if (QUOTE_LINK == t) continue; if (UNQUOTE_LINK == t) continue; if (not h->is_type(EVALUATABLE_LINK)) return false; } return true; } /// Check to see if every input atom is of Numeric type. bool check_numeric(const Handle& bool_atom) { for (const Handle& h: bool_atom->getOutgoingSet()) { Type t = h->get_type(); // PutLinks and GetLinks cannot be type-checked statically. // Checking has to be defered until runtime. if (PUT_LINK == t) continue; if (GET_LINK == t) continue; if (VARIABLE_NODE == t) continue; if (NUMBER_NODE == t) continue; // Oddly enough, sets of numbers are allowed. if (SET_LINK == t and check_numeric(h)) continue; if (not h->is_type(NUMERIC_OUTPUT_LINK)) return false; } return true; } /* This runs when the shared lib is loaded. */ static __attribute__ ((constructor)) void init(void) { classserver().addValidator(BOOLEAN_LINK, check_evaluatable); classserver().addValidator(NUMERIC_LINK, check_numeric); } <|endoftext|>
<commit_before>// Do nothing, if no thread support #ifdef QT_THREAD_SUPPORT #include "threads.h" #include "mainframe.h" #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h> #include <BALL/VIEW/WIDGETS/scene.h> #include <BALL/MOLMEC/AMBER/amber.h> namespace BALL { using namespace VIEW; SimulationThread::SimulationThread() : QThread(), main_frame_(0), dcd_file_(0), composite_(0) { } void SimulationThread::run() { // overloaded in derived classes } void SimulationThread::updateScene_() { Mainframe::UpdateCompositeEvent* se = new Mainframe::UpdateCompositeEvent; se->setComposite(composite_); postEvent(main_frame_, se); /* // old behavior: no rebuilding of surfaces Scene* scene= (Scene*) Scene::getInstance(0); Scene::SceneUpdateEvent* su = new Scene::SceneUpdateEvent; postEvent(scene, su); // Qt will delete it when done */ } void SimulationThread::output_(const String& string) { Mainframe::SimulationOutput* su = new Mainframe::SimulationOutput; su->setMessage(string); postEvent(main_frame_, su); // Qt will delete it when done } void SimulationThread::outputAmberResult_(const AmberFF& amber) { output_( "\nAMBER Energy:\n" " - electrostatic : " + String(amber.getESEnergy()) + " kJ/mol\n" + " - van der Waals : " + String(amber.getVdWEnergy()) + " kJ/mol\n" + " - bond stretch : " + String(amber.getStretchEnergy()) + " kJ/mol\n" + " - angle bend : " + String(amber.getBendEnergy()) + " kJ/mol\n" + " - torsion : " + String(amber.getTorsionEnergy()) + " kJ/mol\n"+ "---------------------------------------\n" + " total energy : " + String(amber.getEnergy()) + " kJ/mol\n" ); } void SimulationThread::finish_() { Mainframe::SimulationThreadFinished* su = new Mainframe::SimulationThreadFinished; postEvent(main_frame_, su); // Qt will delete it when done } void EnergyMinimizerThread::run() { if (minimizer_ == 0 || minimizer_->getForceField() == 0 || minimizer_->getForceField()->getSystem() == 0 || main_frame_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } AmberFF& amber =*(AmberFF*)minimizer_->getForceField(); // iterate until done and refresh the screen every "steps" iterations while (!minimizer_->minimize(steps_between_updates_, true) && minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() && !main_frame_->stopedSimulation()) { updateScene_(); msleep(90); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", minimizer_->getNumberOfIterations(), amber.getEnergy(), amber.getRMSGradient()); output_(message.ascii()); } outputAmberResult_(amber); output_("final RMS gadient : " + String(amber.getRMSGradient()) + " kJ/(mol A) after " + String(minimizer_->getNumberOfIterations()) + " iterations\n"); finish_(); } EnergyMinimizerThread::EnergyMinimizerThread() : SimulationThread(), minimizer_(0) { } EnergyMinimizerThread::~EnergyMinimizerThread() { if (minimizer_ != 0) { delete minimizer_; } } void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) { if (minimizer_ != 0) { delete minimizer_; } minimizer_ = minimizer; } // ===================================================== void MDSimulationThread::run() throw(Exception::NullPointer) { if (md_ == 0 || md_->getForceField() == 0 || md_->getForceField()->getSystem() == 0 || main_frame_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } AmberFF& amber =*(AmberFF*)md_->getForceField(); SnapShotManager manager(amber.getSystem(), &amber, dcd_file_); manager.setFlushToDiskFrequency(10); // iterate until done and refresh the screen every "steps" iterations while (md_->getNumberOfIterations() < steps_ && !main_frame_->stopedSimulation()) { md_->simulateIterations(steps_between_updates_, true); updateScene_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", md_->getNumberOfIterations(), amber.getEnergy(), amber.getRMSGradient()); output_(message.ascii()); msleep(90); if (save_images_) { Scene* scene= (Scene*) Scene::getInstance(0); scene->exportPNG(); } if (dcd_file_) manager.takeSnapShot(); } if (dcd_file_) manager.flushToDisk(); outputAmberResult_(*(AmberFF*)md_->getForceField()); output_("final RMS gadient : " + String(amber.getRMSGradient()) + " kJ/(mol A) after " + String(md_->getNumberOfIterations()) + " iterations\n"); finish_(); } MDSimulationThread::MDSimulationThread() : SimulationThread(), md_(0), save_images_(false) { } MDSimulationThread::~MDSimulationThread() { if (md_ != 0) { delete md_; } } void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md) { if (md_ != 0) { delete md_; } md_ = md; } } #endif //Thread support <commit_msg>fixed postEvent -> qApp->postEvent<commit_after>// Do nothing, if no thread support #ifdef QT_THREAD_SUPPORT #include "threads.h" #include "mainframe.h" #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h> #include <BALL/VIEW/WIDGETS/scene.h> #include <BALL/MOLMEC/AMBER/amber.h> namespace BALL { using namespace VIEW; SimulationThread::SimulationThread() : QThread(), main_frame_(0), dcd_file_(0), composite_(0) { } void SimulationThread::run() { // overloaded in derived classes } void SimulationThread::updateScene_() { Mainframe::UpdateCompositeEvent* se = new Mainframe::UpdateCompositeEvent; se->setComposite(composite_); qApp->postEvent(main_frame_, se); /* // old behavior: no rebuilding of surfaces Scene* scene= (Scene*) Scene::getInstance(0); Scene::SceneUpdateEvent* su = new Scene::SceneUpdateEvent; qApp->postEvent(scene, su); // Qt will delete it when done */ } void SimulationThread::output_(const String& string) { Mainframe::SimulationOutput* su = new Mainframe::SimulationOutput; su->setMessage(string); qApp->postEvent(main_frame_, su); // Qt will delete it when done } void SimulationThread::outputAmberResult_(const AmberFF& amber) { output_( "\nAMBER Energy:\n" " - electrostatic : " + String(amber.getESEnergy()) + " kJ/mol\n" + " - van der Waals : " + String(amber.getVdWEnergy()) + " kJ/mol\n" + " - bond stretch : " + String(amber.getStretchEnergy()) + " kJ/mol\n" + " - angle bend : " + String(amber.getBendEnergy()) + " kJ/mol\n" + " - torsion : " + String(amber.getTorsionEnergy()) + " kJ/mol\n"+ "---------------------------------------\n" + " total energy : " + String(amber.getEnergy()) + " kJ/mol\n" ); } void SimulationThread::finish_() { Mainframe::SimulationThreadFinished* su = new Mainframe::SimulationThreadFinished; qApp->postEvent(main_frame_, su); // Qt will delete it when done } void EnergyMinimizerThread::run() { if (minimizer_ == 0 || minimizer_->getForceField() == 0 || minimizer_->getForceField()->getSystem() == 0 || main_frame_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } AmberFF& amber =*(AmberFF*)minimizer_->getForceField(); // iterate until done and refresh the screen every "steps" iterations while (!minimizer_->minimize(steps_between_updates_, true) && minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() && !main_frame_->stopedSimulation()) { updateScene_(); msleep(90); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", minimizer_->getNumberOfIterations(), amber.getEnergy(), amber.getRMSGradient()); output_(message.ascii()); } outputAmberResult_(amber); output_("final RMS gadient : " + String(amber.getRMSGradient()) + " kJ/(mol A) after " + String(minimizer_->getNumberOfIterations()) + " iterations\n"); finish_(); } EnergyMinimizerThread::EnergyMinimizerThread() : SimulationThread(), minimizer_(0) { } EnergyMinimizerThread::~EnergyMinimizerThread() { if (minimizer_ != 0) { delete minimizer_; } } void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) { if (minimizer_ != 0) { delete minimizer_; } minimizer_ = minimizer; } // ===================================================== void MDSimulationThread::run() throw(Exception::NullPointer) { if (md_ == 0 || md_->getForceField() == 0 || md_->getForceField()->getSystem() == 0 || main_frame_ == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } AmberFF& amber =*(AmberFF*)md_->getForceField(); SnapShotManager manager(amber.getSystem(), &amber, dcd_file_); manager.setFlushToDiskFrequency(10); // iterate until done and refresh the screen every "steps" iterations while (md_->getNumberOfIterations() < steps_ && !main_frame_->stopedSimulation()) { md_->simulateIterations(steps_between_updates_, true); updateScene_(); QString message; message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A", md_->getNumberOfIterations(), amber.getEnergy(), amber.getRMSGradient()); output_(message.ascii()); msleep(90); if (save_images_) { Scene* scene= (Scene*) Scene::getInstance(0); scene->exportPNG(); } if (dcd_file_) manager.takeSnapShot(); } if (dcd_file_) manager.flushToDisk(); outputAmberResult_(*(AmberFF*)md_->getForceField()); output_("final RMS gadient : " + String(amber.getRMSGradient()) + " kJ/(mol A) after " + String(md_->getNumberOfIterations()) + " iterations\n"); finish_(); } MDSimulationThread::MDSimulationThread() : SimulationThread(), md_(0), save_images_(false) { } MDSimulationThread::~MDSimulationThread() { if (md_ != 0) { delete md_; } } void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md) { if (md_ != 0) { delete md_; } md_ = md; } } #endif //Thread support <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // transaction_test.cpp // // Identification: tests/concurrency/transaction_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "concurrency/transaction_tests_util.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Transaction Tests //===--------------------------------------------------------------------===// class TransactionTests : public PelotonTest {}; static std::vector<ConcurrencyType> TEST_TYPES = {CONCURRENCY_TYPE_OCC, CONCURRENCY_TYPE_2PL}; void TransactionTest(concurrency::TransactionManager *txn_manager) { uint64_t thread_id = TestingHarness::GetInstance().GetThreadId(); for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) { txn_manager->BeginTransaction(); if (thread_id % 2 == 0) { std::chrono::microseconds sleep_time(1); std::this_thread::sleep_for(sleep_time); } if (txn_itr % 25 != 0) { txn_manager->CommitTransaction(); } else { txn_manager->AbortTransaction(); } } } TEST_F(TransactionTests, TransactionTest) { for (auto test_type : TEST_TYPES) { concurrency::TransactionManagerFactory::Configure(test_type); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); LaunchParallelTest(8, TransactionTest, &txn_manager); std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n"; } } TEST_F(TransactionTests, AbortTest) { for (auto test_type : TEST_TYPES) { concurrency::TransactionManagerFactory::Configure(test_type); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.Txn(0).Update(0, 100); scheduler.Txn(0).Abort(); scheduler.Txn(1).Read(0); scheduler.Txn(1).Commit(); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); EXPECT_EQ(0, scheduler.schedules[1].results[0]); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // scheduler.AddInsert(0, 100, 0); scheduler.Txn(0).Abort(); scheduler.Txn(1).Read(1); scheduler.Txn(1).Commit(); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); EXPECT_EQ(-1, scheduler.schedules[1].results[0]); } } } } // End test namespace } // End peloton namespace <commit_msg>fix abort test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // transaction_test.cpp // // Identification: tests/concurrency/transaction_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "concurrency/transaction_tests_util.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Transaction Tests //===--------------------------------------------------------------------===// class TransactionTests : public PelotonTest {}; static std::vector<ConcurrencyType> TEST_TYPES = {CONCURRENCY_TYPE_OCC, CONCURRENCY_TYPE_2PL}; void TransactionTest(concurrency::TransactionManager *txn_manager) { uint64_t thread_id = TestingHarness::GetInstance().GetThreadId(); for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) { txn_manager->BeginTransaction(); if (thread_id % 2 == 0) { std::chrono::microseconds sleep_time(1); std::this_thread::sleep_for(sleep_time); } if (txn_itr % 25 != 0) { txn_manager->CommitTransaction(); } else { txn_manager->AbortTransaction(); } } } TEST_F(TransactionTests, TransactionTest) { for (auto test_type : TEST_TYPES) { concurrency::TransactionManagerFactory::Configure(test_type); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); LaunchParallelTest(8, TransactionTest, &txn_manager); std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n"; } } TEST_F(TransactionTests, SingleTransactionTest) { for (auto test_type : TEST_TYPES) { concurrency::TransactionManagerFactory::Configure(test_type); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); // read, read, read, read { TransactionScheduler scheduler(1, table.get(), &txn_manager); scheduler.Txn(0).Read(0); scheduler.Txn(0).Read(0); scheduler.Txn(0).Read(0); scheduler.Txn(0).Read(0); scheduler.Txn(0).Commit(); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(0, scheduler.schedules[0].results[0]); EXPECT_EQ(0, scheduler.schedules[0].results[1]); EXPECT_EQ(0, scheduler.schedules[0].results[2]); EXPECT_EQ(0, scheduler.schedules[0].results[3]); } } } TEST_F(TransactionTests, AbortTest) { for (auto test_type : TEST_TYPES) { concurrency::TransactionManagerFactory::Configure(test_type); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.Txn(0).Update(0, 100); scheduler.Txn(0).Abort(); scheduler.Txn(1).Read(0); scheduler.Txn(1).Commit(); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); EXPECT_EQ(0, scheduler.schedules[1].results[0]); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.Txn(0).Insert(100, 0); scheduler.Txn(0).Abort(); scheduler.Txn(1).Read(100); scheduler.Txn(1).Commit(); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); EXPECT_EQ(-1, scheduler.schedules[1].results[0]); } } } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before>/* * Chrome Token Signing Native Host * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PKCS11Path.h" #include "BinaryUtils.h" #include "Logger.h" #ifdef _WIN32 #undef UNICODE #include <Shlobj.h> #include <Shlwapi.h> #include <Knownfolders.h> #include <winscard.h> #elif defined __APPLE__ #include <PCSC/winscard.h> #include <PCSC/wintypes.h> #include <unistd.h> #else #include <winscard.h> #include <unistd.h> #endif #include <cstring> #include <map> std::vector<std::string> PKCS11Path::atrList() { SCARDCONTEXT hContext = 0; std::vector<std::string> result; LONG err = SCardEstablishContext(SCARD_SCOPE_USER, nullptr, nullptr, &hContext); if (err != SCARD_S_SUCCESS) { _log("SCardEstablishContext ERROR: %x", err); return result; } DWORD size = 0; err = SCardListReaders(hContext, nullptr, nullptr, &size); if (err != SCARD_S_SUCCESS || !size) { _log("SCardListReaders || !size ERROR: %x", err); SCardReleaseContext(hContext); return result; } std::string readers(size, 0); err = SCardListReaders(hContext, nullptr, &readers[0], &size); readers.resize(size); if (err != SCARD_S_SUCCESS) { _log("SCardListReaders ERROR: %x", err); SCardReleaseContext(hContext); return result; } std::vector<SCARD_READERSTATE> list; for (const char *name = readers.c_str(); *name; name += strlen(name) + 1) { _log("found reader: %s", name); list.push_back({ name, nullptr, 0, 0, 0, {} }); } err = SCardGetStatusChange(hContext, 0, list.data(), DWORD(list.size())); if (err != SCARD_S_SUCCESS) _log("SCardGetStatusChange ERROR: %x", err); for(const SCARD_READERSTATE &state: list) { if (state.dwEventState & SCARD_STATE_PRESENT) { std::string atr = BinaryUtils::bin2hex(state.rgbAtr, state.cbAtr); result.push_back(atr); _log("Set ATR = %s for reader %s", atr.c_str(), state.szReader); } } SCardReleaseContext(hContext); return result; } PKCS11Path::Params PKCS11Path::getPkcs11ModulePath() { #ifdef _WIN32 // Use PKCS11 driver on windows to avoid PIN buffering static const std::string litPath = [] { PWSTR programFilesX86 = 0; SHGetKnownFolderPath(FOLDERID_ProgramFilesX86, 0, nullptr, &programFilesX86); std::wstring path = programFilesX86; CoTaskMemFree(programFilesX86); if (PathFileExistsW((path + L"\\PWPW\\pwpw-card-pkcs11.dll").c_str())) path += L"\\PWPW\\pwpw-card-pkcs11.dll"; else path += L"\\CryptoTech\\CryptoCard\\CCPkiP11.dll"; int size = WideCharToMultiByte(CP_UTF8, 0, path.c_str(), DWORD(path.size()), nullptr, 0, nullptr, nullptr); std::string result(size, 0); WideCharToMultiByte(CP_UTF8, 0, path.c_str(), DWORD(path.size()), &result[0], size, nullptr, nullptr); return result; }(); #elif defined __APPLE__ static const std::string openscPath("/Library/OpenSC/lib/opensc-pkcs11.so"); static const std::string estPath = openscPath; static const std::string latPath("/Library/latvia-eid/lib/otlv-pkcs11.so"); static const std::string finPath("/Library/mPolluxDigiSign/libcryptoki.dylib"); static const std::string lit1Path("/Library/Security/tokend/CCSuite.tokend/Contents/Frameworks/libccpkip11.dylib"); static const std::string lit2Path("/Library/PWPW-Card/pwpw-card-pkcs11.so"); static const std::string litPath = access(lit1Path.c_str(), F_OK) == 0 ? lit1Path : lit2Path; static const std::string belPath("/usr/local/lib/beid-pkcs11.bundle/Contents/MacOS/libbeidpkcs11.dylib"); static const std::string eTokenPath("/Library/Frameworks/eToken.framework/Versions/Current/libeToken.dylib"); static const std::string ocsPath("/Library/AWP/lib/libOcsCryptoki.dylib"); #else static const std::string openscPath("opensc-pkcs11.so"); static const std::string estPath = openscPath; static const std::string latPath("otlv-pkcs11.so"); static const std::string finPath("libcryptoki.so"); static const std::string lit1Path("/usr/lib/ccs/libccpkip11.so"); static const std::string lit2Path("pwpw-card-pkcs11.so"); static const std::string litPath = access(lit1Path.c_str(), F_OK) == 0 ? lit1Path : lit2Path; static const std::string belPath("libbeidpkcs11.so.0"); static const std::string eTokenPath("/usr/local/lib/libeTPkcs11.so"); static const std::string ocsPath("/usr/local/AWP/lib/libOcsCryptoki.so"); #endif static const std::map<std::string, Params> m = { #ifdef _WIN32 {"3BFD1800008031FE4553434536302D43443134352D46CD", {"C:\\Windows\\System32\\aetpkss1.dll", "PIN", "PIN"}}, #else {"3BFE1800008031FE454573744549442076657220312E30A8", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_COLD_DEV1_ATR {"3BFE1800008031FE45803180664090A4561B168301900086", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV1_ATR {"3BFE1800008031FE45803180664090A4162A0083019000E1", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV2_ATR {"3BFE1800008031FE45803180664090A4162A00830F9000EF", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV3_ATR {"3BFA1800008031FE45FE654944202F20504B4903", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3.5_COLD_ATR {"3BDD18008131FE45904C41545649412D65494490008C", {latPath, "PIN1", "PIN2"}}, {"3B7B940000806212515646696E454944", {finPath, "PIN1", "PIN2"}}, {"3B7F9600008031B865B0850300EF1200F6829000", {finPath, "PIN1", "PIN2"}}, {"3B9813400AA503010101AD1311", {belPath, "PIN", "PIN"}}, {"3BD5180081313A7D8073C8211030", {eTokenPath, "PIN", "PIN"}}, {"3BD518008131FE7D8073C82110F4", {eTokenPath, "PIN", "PIN"}}, {"3BDB960080B1FE451F830012233F536549440F9000F1", {ocsPath, "PIN1", "PIN2"}}, #endif {"3BF81300008131FE45536D617274417070F8", {litPath, "PIN", "PIN"}}, {"3B7D94000080318065B08311C0A983009000", {litPath, "PIN", "PIN"}}, {"3B7D94000080318065B0831100C883009000", {litPath, "PIN", "PIN"}}, {"3B9F9681B1FE451F070064051EB20031B0739621DB00900050", {litPath, "PIN", "PIN"}}, {"3B9F90801FC30068104405014649534531C800000000", {litPath, "PIN", "PIN"}}, }; const std::vector<std::string> list = atrList(); for (const std::string &atr : list) { auto it = m.find(atr); if (it != m.end()) return it->second; } #ifdef _WIN32 return Params(); #else if (!list.empty()) _log("Unknown ATR '%s' using default module '%s'", list[0].c_str(), openscPath.c_str()); return {openscPath, "PIN", "PIN"}; #endif } <commit_msg>Fix linux module path (#129) (#130)<commit_after>/* * Chrome Token Signing Native Host * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PKCS11Path.h" #include "BinaryUtils.h" #include "Logger.h" #ifdef _WIN32 #undef UNICODE #include <Shlobj.h> #include <Shlwapi.h> #include <Knownfolders.h> #include <winscard.h> #elif defined __APPLE__ #include <PCSC/winscard.h> #include <PCSC/wintypes.h> #include <unistd.h> #else #include <winscard.h> #include <unistd.h> #endif #include <cstring> #include <map> std::vector<std::string> PKCS11Path::atrList() { SCARDCONTEXT hContext = 0; std::vector<std::string> result; LONG err = SCardEstablishContext(SCARD_SCOPE_USER, nullptr, nullptr, &hContext); if (err != SCARD_S_SUCCESS) { _log("SCardEstablishContext ERROR: %x", err); return result; } DWORD size = 0; err = SCardListReaders(hContext, nullptr, nullptr, &size); if (err != SCARD_S_SUCCESS || !size) { _log("SCardListReaders || !size ERROR: %x", err); SCardReleaseContext(hContext); return result; } std::string readers(size, 0); err = SCardListReaders(hContext, nullptr, &readers[0], &size); readers.resize(size); if (err != SCARD_S_SUCCESS) { _log("SCardListReaders ERROR: %x", err); SCardReleaseContext(hContext); return result; } std::vector<SCARD_READERSTATE> list; for (const char *name = readers.c_str(); *name; name += strlen(name) + 1) { _log("found reader: %s", name); list.push_back({ name, nullptr, 0, 0, 0, {} }); } err = SCardGetStatusChange(hContext, 0, list.data(), DWORD(list.size())); if (err != SCARD_S_SUCCESS) _log("SCardGetStatusChange ERROR: %x", err); for(const SCARD_READERSTATE &state: list) { if (state.dwEventState & SCARD_STATE_PRESENT) { std::string atr = BinaryUtils::bin2hex(state.rgbAtr, state.cbAtr); result.push_back(atr); _log("Set ATR = %s for reader %s", atr.c_str(), state.szReader); } } SCardReleaseContext(hContext); return result; } PKCS11Path::Params PKCS11Path::getPkcs11ModulePath() { #ifdef _WIN32 // Use PKCS11 driver on windows to avoid PIN buffering static const std::string litPath = [] { PWSTR programFilesX86 = 0; SHGetKnownFolderPath(FOLDERID_ProgramFilesX86, 0, nullptr, &programFilesX86); std::wstring path = programFilesX86; CoTaskMemFree(programFilesX86); if (PathFileExistsW((path + L"\\PWPW\\pwpw-card-pkcs11.dll").c_str())) path += L"\\PWPW\\pwpw-card-pkcs11.dll"; else path += L"\\CryptoTech\\CryptoCard\\CCPkiP11.dll"; int size = WideCharToMultiByte(CP_UTF8, 0, path.c_str(), DWORD(path.size()), nullptr, 0, nullptr, nullptr); std::string result(size, 0); WideCharToMultiByte(CP_UTF8, 0, path.c_str(), DWORD(path.size()), &result[0], size, nullptr, nullptr); return result; }(); #elif defined __APPLE__ static const std::string openscPath("/Library/OpenSC/lib/opensc-pkcs11.so"); static const std::string estPath = openscPath; static const std::string latPath("/Library/latvia-eid/lib/otlv-pkcs11.so"); static const std::string finPath("/Library/mPolluxDigiSign/libcryptoki.dylib"); static const std::string lit1Path("/Library/Security/tokend/CCSuite.tokend/Contents/Frameworks/libccpkip11.dylib"); static const std::string lit2Path("/Library/PWPW-Card/pwpw-card-pkcs11.so"); static const std::string litPath = access(lit1Path.c_str(), F_OK) == 0 ? lit1Path : lit2Path; static const std::string belPath("/usr/local/lib/beid-pkcs11.bundle/Contents/MacOS/libbeidpkcs11.dylib"); static const std::string eTokenPath("/Library/Frameworks/eToken.framework/Versions/Current/libeToken.dylib"); static const std::string ocsPath("/Library/AWP/lib/libOcsCryptoki.dylib"); #else static const std::string openscPath("opensc-pkcs11.so"); static const std::string estPath = openscPath; static const std::string latPath("otlv-pkcs11.so"); static const std::string finPath("libcryptoki.so"); static const std::string lit1Path("/usr/lib/ccs/libccpkip11.so"); static const std::string lit2Path("pwpw-card-pkcs11.so"); static const std::string litPath = access(lit1Path.c_str(), F_OK) == 0 ? lit1Path : lit2Path; static const std::string belPath("libbeidpkcs11.so.0"); static const std::string eTokenPath("/usr/lib/libeTPkcs11.so"); static const std::string ocsPath("/usr/local/AWP/lib/libOcsCryptoki.so"); #endif static const std::map<std::string, Params> m = { #ifdef _WIN32 {"3BFD1800008031FE4553434536302D43443134352D46CD", {"C:\\Windows\\System32\\aetpkss1.dll", "PIN", "PIN"}}, #else {"3BFE1800008031FE454573744549442076657220312E30A8", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_COLD_DEV1_ATR {"3BFE1800008031FE45803180664090A4561B168301900086", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV1_ATR {"3BFE1800008031FE45803180664090A4162A0083019000E1", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV2_ATR {"3BFE1800008031FE45803180664090A4162A00830F9000EF", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3_WARM_DEV3_ATR {"3BFA1800008031FE45FE654944202F20504B4903", {estPath, "PIN1", "PIN2"}}, //ESTEID_V3.5_COLD_ATR {"3BDD18008131FE45904C41545649412D65494490008C", {latPath, "PIN1", "PIN2"}}, {"3B7B940000806212515646696E454944", {finPath, "PIN1", "PIN2"}}, {"3B7F9600008031B865B0850300EF1200F6829000", {finPath, "PIN1", "PIN2"}}, {"3B9813400AA503010101AD1311", {belPath, "PIN", "PIN"}}, {"3BD5180081313A7D8073C8211030", {eTokenPath, "PIN", "PIN"}}, {"3BD518008131FE7D8073C82110F4", {eTokenPath, "PIN", "PIN"}}, {"3BDB960080B1FE451F830012233F536549440F9000F1", {ocsPath, "PIN1", "PIN2"}}, #endif {"3BF81300008131FE45536D617274417070F8", {litPath, "PIN", "PIN"}}, {"3B7D94000080318065B08311C0A983009000", {litPath, "PIN", "PIN"}}, {"3B7D94000080318065B0831100C883009000", {litPath, "PIN", "PIN"}}, {"3B9F9681B1FE451F070064051EB20031B0739621DB00900050", {litPath, "PIN", "PIN"}}, {"3B9F90801FC30068104405014649534531C800000000", {litPath, "PIN", "PIN"}}, }; const std::vector<std::string> list = atrList(); for (const std::string &atr : list) { auto it = m.find(atr); if (it != m.end()) return it->second; } #ifdef _WIN32 return Params(); #else if (!list.empty()) _log("Unknown ATR '%s' using default module '%s'", list[0].c_str(), openscPath.c_str()); return {openscPath, "PIN", "PIN"}; #endif } <|endoftext|>
<commit_before>#include "stdafx.h" struct Screen { int32_t Width; int32_t Height; int32_t Width43; } Screen; DWORD WINAPI WindowCheck(LPVOID hWnd) { while (true) { Sleep(10); if (*(HWND*)hWnd && !IsWindow(*(HWND*)hWnd)) ExitProcess(0); } return 0; } void Init() { CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); bool bEndProcess = iniReader.ReadInteger("MAIN", "EndProcessOnWindowClose", 0) != 0; if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.Width43 = static_cast<uint32_t>(Screen.Height * (4.0f / 3.0f)); //wndmode crashfix auto pattern = hook::pattern("E8 ? ? ? ? 83 C4 04 B8 01 00 00 00 5D 5F 5E 5B 81 C4 70 05 00 00"); //0x49225B injector::MakeNOP(pattern.get_first(0), 5, true); //Player_a bugfix pattern = hook::pattern("88 1D ? ? ? ? 88 1D ? ? ? ? C6 05 ? ? ? ? 01 88 1D ? ? ? ? C7 05"); //0x42B512 static auto byte_51029C = *pattern.get_first<uint8_t*>(2); struct patch_player_a { void operator()(injector::reg_pack& regs) { *byte_51029C = 0x06; } }; injector::MakeInline<patch_player_a>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("A2 ? ? ? ? E8 ? ? ? ? 8B F0 83"); //0x4274FF injector::MakeInline<patch_player_a>(pattern.get_first(0)); //Res change pattern = hook::pattern("A3 ? ? ? ? A3 ? ? ? ? 8B 83 B4 01 00 00 40"); //0x491E4C static auto nWidth = *pattern.get_first<uint32_t*>(1); static auto dword_787370 = *pattern.get_first<uint32_t*>(6); static auto nHeight = *pattern.get_first<uint32_t*>(20); static auto dword_787388 = *pattern.get_first<uint32_t*>(25); struct SetResHook { void operator()(injector::reg_pack& regs) { *nWidth = Screen.Width; *dword_787370 = Screen.Width; regs.eax = Screen.Height; } }; injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(17)); pattern = hook::pattern("89 B1 ? ? ? ? D1 F8 89 81"); //0x46453B static auto dword_74F168 = *pattern.get_first<uint32_t>(2); struct SetResHook43 { void operator()(injector::reg_pack& regs) { regs.esi = Screen.Width43; *(uint32_t*)(regs.ecx + dword_74F168) = regs.esi; } }; injector::MakeInline<SetResHook43>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 40 02 00 00"); //0x48C1A0 struct SetResHookX { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Width - 1; } }; injector::MakeInline<SetResHookX>(pattern.get_first(0), pattern.get_first(19)); pattern = hook::pattern("A3 ? ? ? ? E8 ? ? ? ? 83 C4 08 40 83"); //0x414FF7 static auto dword_504CC0 = *pattern.get_first<uint32_t*>(1); struct SetResHookX1 { void operator()(injector::reg_pack& regs) { *dword_504CC0 = Screen.Width; } }; injector::MakeInline<SetResHookX1>(pattern.get_first(0)); pattern = hook::pattern("89 15 ? ? ? ? 8B 40 0C A3 ? ? ? ? C3"); //0x43B7CF static auto dword_5C0C00 = *pattern.get_first<uint32_t*>(2); struct SetResHookX2 { void operator()(injector::reg_pack& regs) { *dword_5C0C00 = Screen.Width; } }; injector::MakeInline<SetResHookX2>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 44 02 00 00 8B 91"); //0x48C1C0 struct SetResHookY { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Height - 1; } }; injector::MakeInline<SetResHookY>(pattern.get_first(0), pattern.get_first(19)); //Menu fix pattern = hook::pattern("BB ? ? ? ? 2B 5D 0C D1 E3 89 5D FC"); //0x4898C3 injector::WriteMemory(pattern.get_first(1), Screen.Width, true); //FMV crashfix static int n480 = 480; pattern = hook::pattern("A1 ? ? ? ? 74 56 85 C0 0F"); injector::WriteMemory(pattern.get_first(1), &n480, true); //42D83A pattern = hook::pattern("3B 15 ? ? ? ? 7C B7 5B 5F 5E C3"); injector::WriteMemory(pattern.get_first(2), &n480, true); //42D88B pattern = hook::pattern("3B 15 ? ? ? ? 7C C7 5F 5E C3"); injector::WriteMemory(pattern.get_first(2), &n480, true); //42D8CC if (bEndProcess) { pattern = hook::pattern("3B 05 ? ? ? ? 0F 94 C3 85 DB"); //0x4B4FB8 auto hwnd = *pattern.get_first<HWND*>(2); CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)&WindowCheck, (LPVOID)hwnd, 0, NULL); } } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("83 EC 0C 33 C0 53 57 33 DB")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { if (!IsUALPresent()) { InitializeASI(); } } return TRUE; }<commit_msg>gta1 update<commit_after>#include "stdafx.h" struct Screen { int32_t Width; int32_t Height; int32_t Width43; } Screen; DWORD WINAPI WindowCheck(LPVOID hWnd) { while (true) { Sleep(10); if (*(HWND*)hWnd && !IsWindow(*(HWND*)hWnd)) ExitProcess(0); } return 0; } void InitGtaClassicsSteam() { // Patches: // - GTA1 Rockstar Classics & Steam: SHA256=6A5C313D9C0D87B4EFA527BAAC7097DD4A149B9B2DA5261ABB224083F5CDC1C2 (774144 bytes) CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); bool bEndProcess = iniReader.ReadInteger("MAIN", "EndProcessOnWindowClose", 0) != 0; if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.Width43 = static_cast<uint32_t>(Screen.Height * (4.0f / 3.0f)); //wndmode crashfix (caused by the ASI loader) auto pattern = hook::pattern("E8 ? ? ? ? 83 C4 04 B8 01 00 00 00 5D 5F 5E 5B 81 C4 70 05 00 00"); //0x49225B injector::MakeNOP(pattern.get_first(0), 5, true); //Player_a bugfix (only in the Rockstar Classics / Steam version) //Fix by Daniel Marschall, //see technical details here: https://misc.daniel-marschall.de/spiele/gta1/player_a_bugfix.txt pattern = hook::pattern("3B C2 0F 9D C2 FE CA 83 E2 06"); if (!pattern.empty()) { // This patch is optional; if pattern does not exist, then do nothing. struct patch_player_a_new { void operator()(injector::reg_pack& regs) { // mov al, [ecx] ; ecx is a pointer to the saved resolution (values 0..5) // cmp eax, edx ; <-- Patch: mov edx, eax // setnl dl ; <-- Patch: nop // dec dl ; <-- Patch: nop // and edx, 6 ; <-- Patch: nop (Bug is in this line: Resolution "6" does not exist!) // mov byte ptr byte_00503224, dl ; In byte_00503224, the to-be-applied resolution will be saved regs.edx = regs.eax; } }; injector::MakeInline<patch_player_a_new>(pattern.get_first(0), pattern.get_first(10)); } //Res change pattern = hook::pattern("A3 ? ? ? ? A3 ? ? ? ? 8B 83 B4 01 00 00 40"); //0x491E4C static auto nWidth = *pattern.get_first<uint32_t*>(1); static auto dword_787370 = *pattern.get_first<uint32_t*>(6); //static auto nHeight = *pattern.get_first<uint32_t*>(20); //static auto dword_787388 = *pattern.get_first<uint32_t*>(25); struct SetResHook { void operator()(injector::reg_pack& regs) { *nWidth = Screen.Width; *dword_787370 = Screen.Width; regs.eax = Screen.Height; } }; injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(17)); pattern = hook::pattern("89 B1 ? ? ? ? D1 F8 89 81"); //0x46453B static auto dword_74F168 = *pattern.get_first<uint32_t>(2); struct SetResHook43 { void operator()(injector::reg_pack& regs) { regs.esi = Screen.Width43; *(uint32_t*)(regs.ecx + dword_74F168) = regs.esi; } }; injector::MakeInline<SetResHook43>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 40 02 00 00"); //0x48C1A0 struct SetResHookX { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Width - 1; } }; injector::MakeInline<SetResHookX>(pattern.get_first(0), pattern.get_first(19)); pattern = hook::pattern("A3 ? ? ? ? E8 ? ? ? ? 83 C4 08 40 83"); //0x414FF7 static auto dword_504CC0 = *pattern.get_first<uint32_t*>(1); struct SetResHookX1 { void operator()(injector::reg_pack& regs) { *dword_504CC0 = Screen.Width; } }; injector::MakeInline<SetResHookX1>(pattern.get_first(0)); pattern = hook::pattern("89 15 ? ? ? ? 8B 40 0C A3 ? ? ? ? C3"); //0x43B7CF static auto dword_5C0C00 = *pattern.get_first<uint32_t*>(2); struct SetResHookX2 { void operator()(injector::reg_pack& regs) { *dword_5C0C00 = Screen.Width; } }; injector::MakeInline<SetResHookX2>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 44 02 00 00 8B 91"); //0x48C1C0 struct SetResHookY { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Height - 1; } }; injector::MakeInline<SetResHookY>(pattern.get_first(0), pattern.get_first(19)); //Menu fix pattern = hook::pattern("BB ? ? ? ? 2B 5D 0C D1 E3 89 5D FC"); //0x4898C3 injector::WriteMemory(pattern.get_first(1), Screen.Width, true); //Fix crash in FMV (cut scenes) due to the resolution change static int n480 = 480; // fix dword_785174 pattern = hook::pattern("A1 ? ? ? ? 74 56 85 C0 0F"); injector::WriteMemory(pattern.get_first(1), &n480, true); //42D83A pattern = hook::pattern("3B 15 ? ? ? ? 7C B7 5B 5F 5E C3"); injector::WriteMemory(pattern.get_first(2), &n480, true); //42D88B pattern = hook::pattern("3B 15 ? ? ? ? 7C C7 5F 5E C3"); injector::WriteMemory(pattern.get_first(2), &n480, true); //42D8CC if (bEndProcess) { pattern = hook::pattern("3B 05 ? ? ? ? 0F 94 C3 85 DB"); //0x4B4FB8 auto hwnd = *pattern.get_first<HWND*>(2); CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)&WindowCheck, (LPVOID)hwnd, 0, NULL); } } // TODO: GTA 1 Retail, London 1969 and London 1961: // The game crashes if a cut scene is replayed (space bar), most likely because of a timer issue: // They are heavily accelerated (like the menu). // The cut scenes do work when they are triggered via mission complete. void InitLondonRetail() { // Patches: // - GTA London 1969 Retail (CD): SHA256=1FA3934F330B0097A0CB8160E3968D78E93CB4A808703AD4854BDB1F87BAE39A (1231360 bytes) // - GTA London 1961 (Download): SHA256=549020E49AAD17D1EF26BC5766A8374503C5A5936251B793BF8BE2A1D90700C5 (1235968 bytes) // Note: Variable names in this function (dword_...) are taken from GTA London 1969, not 1961 CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); bool bEndProcess = iniReader.ReadInteger("MAIN", "EndProcessOnWindowClose", 0) != 0; if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.Width43 = static_cast<uint32_t>(Screen.Height * (4.0f / 3.0f)); //wndmode crashfix (caused by the ASI loader) auto pattern = hook::pattern("E8 ? ? ? ? 83 C4 04 B8 01 00 00 00 5D 5F 5E 5B 81 C4 70 05 00 00"); injector::MakeNOP(pattern.get_first(0), 5, true); //Res change pattern = hook::pattern("A3 ? ? ? ? A3 ? ? ? ? 8B 83 B4 01 00 00 40"); static auto nWidth = *pattern.get_first<uint32_t*>(1); static auto dword_854C30 = *pattern.get_first<uint32_t*>(6); //static auto nHeight = *pattern.get_first<uint32_t*>(20); //static auto dword_854C48 = *pattern.get_first<uint32_t*>(25); struct SetResHook { void operator()(injector::reg_pack& regs) { *nWidth = Screen.Width; *dword_854C30 = Screen.Width; regs.eax = Screen.Height; } }; injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(17)); pattern = hook::pattern("8B 81 ? ? ? ? 99 2B C2 D1 F8"); static auto dword_80CF48 = *pattern.get_first<uint32_t>(2); struct SetResHook43 { void operator()(injector::reg_pack& regs) { regs.eax = *(uint32_t*)(regs.ecx + dword_80CF48); regs.esi = Screen.Width43; *(uint32_t*)(regs.ecx + dword_80CF48) = regs.esi; } }; injector::MakeInline<SetResHook43>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 40 02 00 00 8B 91 38 02 00 00 2B"); struct SetResHookX { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Width - 1; } }; injector::MakeInline<SetResHookX>(pattern.get_first(0), pattern.get_first(19)); pattern = hook::pattern("A1 ? ? ? ? 83 C4 08 40 83"); static auto dword_55128C = *pattern.get_first<uint32_t*>(1); struct SetResHookX1 { void operator()(injector::reg_pack& regs) { *dword_55128C = Screen.Width; } }; injector::MakeInline<SetResHookX1>(pattern.get_first(0)); pattern = hook::pattern("89 15 ? ? ? ? 8B 40 0C A3 ? ? ? ? C3"); static auto dword_626638 = *pattern.get_first<uint32_t*>(2); struct SetResHookX2 { void operator()(injector::reg_pack& regs) { *dword_626638 = Screen.Width; } }; injector::MakeInline<SetResHookX2>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 44 02 00 00 8B 91"); struct SetResHookY { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Height - 1; } }; injector::MakeInline<SetResHookY>(pattern.get_first(0), pattern.get_first(19)); //Menu fix pattern = hook::pattern("BB ? ? ? ? 2B 5D 0C D1 E3 89 5D FC"); injector::WriteMemory(pattern.get_first(1), Screen.Width, true); //Fix crash in FMV (cut scenes) due to the resolution change static int n480 = 480; pattern = hook::pattern("A1 ? ? ? ? 33 D2 85 C0 0F ? ? ? ?"); injector::WriteMemory(pattern.get_first(1), &n480, true); pattern = hook::pattern("42 F3 A4 3B 15 ? ? ? ? 7C B7 5F 5E"); injector::WriteMemory(pattern.get_first(5), &n480, true); pattern = hook::pattern("A1 ? ? ? ? 33 D2 85 C0 7E 39 8B FA"); injector::WriteMemory(pattern.get_first(1), &n480, true); pattern = hook::pattern("42 F3 AA 3B 15 ? ? ? ? 7C C7 5F 5E"); injector::WriteMemory(pattern.get_first(5), &n480, true); if (bEndProcess) { pattern = hook::pattern("3B 05 ? ? ? ? 0F 94 C3 85 DB"); auto hwnd = *pattern.get_first<HWND*>(2); CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)&WindowCheck, (LPVOID)hwnd, 0, NULL); } } void InitGtaRetail() { // Patches: // - GTA1 Retail (CD): SHA256=5AF3C1D90A85F694B184F3FC242E5F8F13B01BFE9BC706C655E97B7BC21599C8 (909824 bytes) CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); bool bEndProcess = iniReader.ReadInteger("MAIN", "EndProcessOnWindowClose", 0) != 0; if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.Width43 = static_cast<uint32_t>(Screen.Height * (4.0f / 3.0f)); //wndmode crashfix (caused by the ASI loader) auto pattern = hook::pattern("E8 ? ? ? ? 83 C4 04 B8 01 00 00 00 5D 5F 5E 5B 81 C4 70 05 00 00"); injector::MakeNOP(pattern.get_first(0), 5, true); //Res change pattern = hook::pattern("A3 ? ? ? ? A3 ? ? ? ? 8B 83 B4 01 00 00 40"); static auto nWidth = *pattern.get_first<uint32_t*>(1); static auto dword_77E990 = *pattern.get_first<uint32_t*>(6); //static auto nHeight = *pattern.get_first<uint32_t*>(20); //static auto dword_77E9A8 = *pattern.get_first<uint32_t*>(25); struct SetResHook { void operator()(injector::reg_pack& regs) { *nWidth = Screen.Width; *dword_77E990 = Screen.Width; regs.eax = Screen.Height; } }; injector::MakeInline<SetResHook>(pattern.get_first(0), pattern.get_first(17)); pattern = hook::pattern("8B 86 ? ? ? ? 99 2B C2 D1 F8 8D 0C 49"); static auto dword_6575E8 = *pattern.get_first<uint32_t>(2); struct SetResHook43 { void operator()(injector::reg_pack& regs) { regs.eax = *(uint32_t*)(regs.esi + dword_6575E8); regs.ecx = Screen.Width43; *(uint32_t*)(regs.esi + dword_6575E8) = regs.ecx; } }; injector::MakeInline<SetResHook43>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 40 02 00 00 8B 91 38 02 00 00 2B"); struct SetResHookX { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Width - 1; } }; injector::MakeInline<SetResHookX>(pattern.get_first(0), pattern.get_first(19)); pattern = hook::pattern("A1 ? ? ? ? 40 A3 10"); static auto dword_4BF010 = *pattern.get_first<uint32_t*>(1); struct SetResHookX1 { void operator()(injector::reg_pack& regs) { *dword_4BF010 = Screen.Width; } }; injector::MakeInline<SetResHookX1>(pattern.get_first(0)); pattern = hook::pattern("89 15 ? ? ? ? 8B 40 0C A3 ? ? ? ? C3"); static auto dword_5F18E8 = *pattern.get_first<uint32_t*>(2); struct SetResHookX2 { void operator()(injector::reg_pack& regs) { *dword_5F18E8 = Screen.Width; } }; injector::MakeInline<SetResHookX2>(pattern.get_first(0), pattern.get_first(6)); pattern = hook::pattern("8B 4C 24 04 8B 81 44 02 00 00 8B 91"); struct SetResHookY { void operator()(injector::reg_pack& regs) { regs.eax = Screen.Height - 1; } }; injector::MakeInline<SetResHookY>(pattern.get_first(0), pattern.get_first(19)); //Menu fix pattern = hook::pattern("BB ? ? ? ? 2B 5D 0C D1 E3 89 5D FC"); injector::WriteMemory(pattern.get_first(1), Screen.Width, true); //Fix crash in FMV (cut scenes) due to the resolution change static int n480 = 480; pattern = hook::pattern("A1 ? ? ? ? 89 54 24 10 3B C2 0F 8E 95 00 00 00"); injector::WriteMemory(pattern.get_first(1), &n480, true); pattern = hook::pattern("42 03 F3 F3 A5 3B 15 ? ? ? ? 7C B1"); injector::WriteMemory(pattern.get_first(7), &n480, true); pattern = hook::pattern("33 D2 A1 ? ? ? ? 3B C2 7E 33"); injector::WriteMemory(pattern.get_first(3), &n480, true); pattern = hook::pattern("F3 AB 3B 15 ? ? ? ? 7C CD"); injector::WriteMemory(pattern.get_first(4), &n480, true); if (bEndProcess) { pattern = hook::pattern("3B 05 ? ? ? ? 0F 94 C3 85 DB"); auto hwnd = *pattern.get_first<HWND*>(2); CreateThreadAutoClose(0, 0, (LPTHREAD_START_ROUTINE)&WindowCheck, (LPVOID)hwnd, 0, NULL); } } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(InitGtaClassicsSteam, hook::pattern("83 EC 0C 33 C0 53 57 33 DB")); CallbackHandler::RegisterCallback(InitLondonRetail, hook::pattern("51 53 55 56 68 ? ? ? ? 33 DB")); CallbackHandler::RegisterCallback(InitGtaRetail, hook::pattern("53 56 57 55 33 ED 68 ? ? ? ? E8")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { if (!IsUALPresent()) { InitializeASI(); } } return TRUE; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: surfaceModel.C,v 1.19 2002/12/17 18:39:18 amoll Exp $ #include <BALL/MOLVIEW/FUNCTOR/surfaceModel.h> #include <BALL/KERNEL/system.h> #include <BALL/STRUCTURE/surfaceProcessor.h> #include <BALL/MOLVIEW/FUNCTOR/molecularInformation.h> #include <BALL/KERNEL/system.h> using namespace std; namespace BALL { namespace MOLVIEW { AddSurfaceModel::AddSurfaceModel() throw() : BaseModelProcessor(), get_composite_(true), start_composite_(0) { } AddSurfaceModel::AddSurfaceModel(const AddSurfaceModel& add_surface, bool deep) throw() : BaseModelProcessor(add_surface, deep), get_composite_(true), start_composite_(0) { } AddSurfaceModel::~AddSurfaceModel() throw() { #ifdef BALL_VIEW_DEBUG Log.error() << "Destructing object " << (void *)this << " of class " << RTTI::getName<AddSurfaceModel>() << endl; #endif destroy(); } void AddSurfaceModel::clear() throw() { BaseModelProcessor::clear(); get_composite_ = true; start_composite_ = 0; } void AddSurfaceModel::destroy() throw() { } bool AddSurfaceModel::start() { get_composite_ = true; start_composite_ = 0; return BaseModelProcessor::start(); } bool AddSurfaceModel::finish() { // insert surface only if a composite exist if (start_composite_ == 0 || RTTI::isKindOf<GeometricObject>(*start_composite_)) { return false; } Mesh* mesh = createMesh_(); if (mesh == 0) { throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Mesh)); } // get info from the start composite MolecularInformation molecular_information; start_composite_->host(molecular_information); mesh->PropertyManager::set(*this); SurfaceProcessor sp; try { start_composite_->apply(sp); } catch (Exception::GeneralException e) { Log.error() << "SurfaceModel: caught exception while calculating molecular surface: " << e << endl; } catch (std::exception e) { Log.error() << "SurfaceModel: caught exception while calculating molecular surface: " << e.what() << endl; } catch (...) { Log.error() << "SurfaceModel: caught unknown exception while calculating molecular surface" << endl; } Log.info() << "assigning surface (" << sp.getSurface().vertex.size() << " vertices, " << sp.getSurface().triangle.size() << " triangles)" << endl; *static_cast<Surface*>(mesh) = sp.getSurface(); mesh->setName(String("Surface of ") + molecular_information.getTypeName() + String(" (") + molecular_information.getName() + String(")")); start_composite_->getRoot().appendChild(*mesh); return true; } Processor::Result AddSurfaceModel::operator () (Composite& composite) { // take first composite, surface will be inserted to it later if (get_composite_) { start_composite_ = &composite; get_composite_ = false; } return Processor::CONTINUE; } void AddSurfaceModel::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BaseModelProcessor::dump(s, depth + 1); BALL_DUMP_STREAM_SUFFIX(s); } Mesh* AddSurfaceModel::createMesh_() { return (Mesh *)(new Mesh()); } } // namespace MOLVIEW } // namespace BALL <commit_msg>added support for different detailled surfaces<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: surfaceModel.C,v 1.20 2002/12/18 03:14:02 amoll Exp $ #include <BALL/MOLVIEW/FUNCTOR/surfaceModel.h> #include <BALL/STRUCTURE/surfaceProcessor.h> #include <BALL/MOLVIEW/FUNCTOR/molecularInformation.h> using namespace std; namespace BALL { namespace MOLVIEW { AddSurfaceModel::AddSurfaceModel() throw() : BaseModelProcessor(), get_composite_(true), start_composite_(0) { } AddSurfaceModel::AddSurfaceModel(const AddSurfaceModel& add_surface, bool deep) throw() : BaseModelProcessor(add_surface, deep), get_composite_(true), start_composite_(0) { } AddSurfaceModel::~AddSurfaceModel() throw() { #ifdef BALL_VIEW_DEBUG Log.error() << "Destructing object " << (void *)this << " of class " << RTTI::getName<AddSurfaceModel>() << endl; #endif destroy(); } void AddSurfaceModel::clear() throw() { BaseModelProcessor::clear(); get_composite_ = true; start_composite_ = 0; } void AddSurfaceModel::destroy() throw() { } bool AddSurfaceModel::start() { get_composite_ = true; start_composite_ = 0; return BaseModelProcessor::start(); } bool AddSurfaceModel::finish() { // insert surface only if a composite exist if (start_composite_ == 0 || RTTI::isKindOf<GeometricObject>(*start_composite_)) { return false; } Mesh* mesh = createMesh_(); if (mesh == 0) { throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Mesh)); } // get info from the start composite MolecularInformation molecular_information; start_composite_->host(molecular_information); mesh->PropertyManager::set(*this); SurfaceProcessor sp; if (hasProperty(GeometricObject::PROPERTY__DRAWING_PRECISION_LOW)) { sp.setDensity(2.0); } else if (hasProperty(GeometricObject::PROPERTY__DRAWING_PRECISION_MEDIUM)) { sp.setDensity(4.5); } else if (hasProperty(GeometricObject::PROPERTY__DRAWING_PRECISION_HIGH)) { sp.setDensity(7.0); } else { Log.error() << "Unknown precision in " << __FILE__ << " " << __LINE__ << std::endl; } try { start_composite_->apply(sp); } catch (Exception::GeneralException e) { Log.error() << "SurfaceModel: caught exception while calculating molecular surface: " << e << endl; } catch (std::exception e) { Log.error() << "SurfaceModel: caught exception while calculating molecular surface: " << e.what() << endl; } catch (...) { Log.error() << "SurfaceModel: caught unknown exception while calculating molecular surface" << endl; } Log.info() << "assigning surface (" << sp.getSurface().vertex.size() << " vertices, " << sp.getSurface().triangle.size() << " triangles)" << endl; *static_cast<Surface*>(mesh) = sp.getSurface(); mesh->setName(String("Surface of ") + molecular_information.getTypeName() + String(" (") + molecular_information.getName() + String(")")); start_composite_->getRoot().appendChild(*mesh); return true; } Processor::Result AddSurfaceModel::operator () (Composite& composite) { // take first composite, surface will be inserted to it later if (get_composite_) { start_composite_ = &composite; get_composite_ = false; } return Processor::CONTINUE; } void AddSurfaceModel::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BaseModelProcessor::dump(s, depth + 1); BALL_DUMP_STREAM_SUFFIX(s); } Mesh* AddSurfaceModel::createMesh_() { return (Mesh *)(new Mesh()); } } // namespace MOLVIEW } // namespace BALL <|endoftext|>
<commit_before>#include <reflection/reflection.h> REFLECTABLE(auto, operator!=, member_function); REFLECTABLE(auto, operator%, member_function); REFLECTABLE(auto, operator%=, member_function); REFLECTABLE(auto, operator&, member_function); REFLECTABLE(auto, operator&&, member_function); REFLECTABLE(auto, operator&=, member_function); REFLECTABLE(auto, operator(), member_function); REFLECTABLE(auto, operator*, member_function); REFLECTABLE(auto, operator*=, member_function); REFLECTABLE(auto, operator+, member_function); REFLECTABLE(auto, operator++, member_function); REFLECTABLE(auto, operator+=, member_function); REFLECTABLE(auto, operator-, member_function); REFLECTABLE(auto, operator--, member_function); REFLECTABLE(auto, operator-=, member_function); REFLECTABLE(auto, operator->*, member_function); REFLECTABLE(auto, operator/, member_function); REFLECTABLE(auto, operator/=, member_function); REFLECTABLE(auto, operator<, member_function); REFLECTABLE(auto, operator<<, member_function); REFLECTABLE(auto, operator<<=, member_function); REFLECTABLE(auto, operator<=, member_function); REFLECTABLE(auto, operator=, member_function); REFLECTABLE(auto, operator==, member_function); REFLECTABLE(auto, operator>, member_function); REFLECTABLE(auto, operator>=, member_function); REFLECTABLE(auto, operator>>, member_function); REFLECTABLE(auto, operator>>=, member_function); REFLECTABLE(auto, operator[], member_function); REFLECTABLE(auto, operator|, member_function); REFLECTABLE(auto, operator|=, member_function); REFLECTABLE(auto, operator||, member_function); REFLECTABLE(auto, operator^=, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator!, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator->, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator~, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator^, member_function); // TODO: operator, // #define REFLECTION_OPERATOR_COMMA operator, // REFLECTABLE(auto, REFLECTION_OPERATOR_COMMA, member_function); <commit_msg>Removed superfluous newline<commit_after>#include <reflection/reflection.h> REFLECTABLE(auto, operator!=, member_function); REFLECTABLE(auto, operator%, member_function); REFLECTABLE(auto, operator%=, member_function); REFLECTABLE(auto, operator&, member_function); REFLECTABLE(auto, operator&&, member_function); REFLECTABLE(auto, operator&=, member_function); REFLECTABLE(auto, operator(), member_function); REFLECTABLE(auto, operator*, member_function); REFLECTABLE(auto, operator*=, member_function); REFLECTABLE(auto, operator+, member_function); REFLECTABLE(auto, operator++, member_function); REFLECTABLE(auto, operator+=, member_function); REFLECTABLE(auto, operator-, member_function); REFLECTABLE(auto, operator--, member_function); REFLECTABLE(auto, operator-=, member_function); REFLECTABLE(auto, operator->*, member_function); REFLECTABLE(auto, operator/, member_function); REFLECTABLE(auto, operator/=, member_function); REFLECTABLE(auto, operator<, member_function); REFLECTABLE(auto, operator<<, member_function); REFLECTABLE(auto, operator<<=, member_function); REFLECTABLE(auto, operator<=, member_function); REFLECTABLE(auto, operator=, member_function); REFLECTABLE(auto, operator==, member_function); REFLECTABLE(auto, operator>, member_function); REFLECTABLE(auto, operator>=, member_function); REFLECTABLE(auto, operator>>, member_function); REFLECTABLE(auto, operator>>=, member_function); REFLECTABLE(auto, operator[], member_function); REFLECTABLE(auto, operator|, member_function); REFLECTABLE(auto, operator|=, member_function); REFLECTABLE(auto, operator||, member_function); REFLECTABLE(auto, operator^=, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator!, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator->, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator~, member_function); REFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator^, member_function); // TODO: operator, // #define REFLECTION_OPERATOR_COMMA operator, // REFLECTABLE(auto, REFLECTION_OPERATOR_COMMA, member_function); <|endoftext|>
<commit_before>/* Copyright (c) 2019 -> Present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include"hip/hip_runtime.h" extern "C" __global__ void matmulK(int* A, int* B, int* C, int N) { int ROW = blockIdx.y*blockDim.y+threadIdx.y; int COL = blockIdx.x*blockDim.x+threadIdx.x; int tmpSum = 0; if (ROW < N && COL < N) { // each thread computes one element of the block sub-matrix for (int i = 0; i < N; i++) { tmpSum += A[ROW * N + i] * B[i * N + COL]; } } C[ROW * N + COL] =tmpSum; } extern "C" __global__ void WaitKernel() { unsigned long long int wait_t=32000000000,start=clock64(),cur; do{cur=clock64()-start;} while(cur<wait_t); } <commit_msg>Formatting changes<commit_after>/* Copyright (c) 2019 - present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include"hip/hip_runtime.h" extern "C" __global__ void matmulK(int* A, int* B, int* C, int N) { int ROW = blockIdx.y*blockDim.y+threadIdx.y; int COL = blockIdx.x*blockDim.x+threadIdx.x; int tmpSum = 0; if (ROW < N && COL < N) { // each thread computes one element of the block sub-matrix for (int i = 0; i < N; i++) { tmpSum += A[ROW * N + i] * B[i * N + COL]; } } C[ROW * N + COL] =tmpSum; } extern "C" __global__ void WaitKernel() { unsigned long long int wait_t=32000000000,start=clock64(),cur; do{cur=clock64()-start;} while(cur<wait_t); } <|endoftext|>
<commit_before>/* Jim Viebke Jun 3 2015 */ #include "npc_enemy.h" void Hostile_NPC::update(World & world, map<string, shared_ptr<Character>> & actors) { // every time this is called, the NPC executes one action against the world then returns // any number of internal objectives may be created, updated, or deleted if (i_dont_have(C::AXE_ID) && !im_planning_to_acquire(C::AXE_ID)) { plan_to_get(C::AXE_ID); } if (i_dont_have(C::SWORD_ID) && !im_planning_to_acquire(C::SWORD_ID)) { plan_to_get(C::SWORD_ID); } for (deque<Objective>::iterator objective_iterator = objectives.begin(); objective_iterator != objectives.end();) { if (objective_iterator->verb == C::AI_OBJECTIVE_ACQUIRE) { // if the item is here, take it, remove the current objective, and return if (world.room_at(x, y, z)->contains_item(objective_iterator->noun)) { take(objective_iterator->noun, world); if (objective_iterator->noun == objective_iterator->purpose) { // this item is an end goal erase_objectives_matching_purpose(objective_iterator->purpose); } else { // this item is a means to an end erase_objective(objective_iterator); } return; } // see if the item is reachable for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { if (!R::bounds_check(cx, cy)) { continue; } // skip if out of bounds if (world.room_at(cx, cy, z)->contains_item(objective_iterator->noun)) { if (pathfind(cx, cy, world)) { return; } } } } // a path could not be found to the item, plan to craft it if it is craftable and the NPC isn't planning to already // if i'm not already planning on crafting the item // AND the item is craftable if (!objective_iterator->already_planning_to_craft && one_can_craft(objective_iterator->noun)) { objective_iterator->already_planning_to_craft = true; plan_to_craft(objective_iterator->noun); objective_iterator = objectives.begin(); // obligatory reset continue; // jump to next iteration } } ++objective_iterator; } for (deque<Objective>::iterator objective_iterator = objectives.begin(); objective_iterator != objectives.end(); ++objective_iterator) { // try to craft the item const string craft_attempt = craft(objective_iterator->noun, world); if (craft_attempt.find("You now have") != string::npos) { // if successful, clear completed objectives if (objective_iterator->noun == objective_iterator->purpose) { // this item is an end goal erase_objectives_matching_purpose(objective_iterator->purpose); } else { // this item is a means to an end erase_objective(objective_iterator); } return; } } // the next block: the NPC runs to the first player it finds IF // - it is armed with a sword AND // - it has no other objectives if (i_have(C::SWORD_ID) && objectives.size() == 0) // hardcoding this bit for now { // for each row in view distance for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { // for each room in the row in view distance for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { // skip this room if it is out of bounds if (!R::bounds_check(cx, cy)) { continue; } // for each actor in the room for (const string & actor_ID : world.room_at(cx, cy, z)->get_actor_ids()) { // if the character is the type of character we're looking for if (R::is<PC>(actors.find(actor_ID)->second)) { // cout << endl << actor_ID << " is a player character at " << cx << "," << cy << ". [exterminate! exterminate!]\n"; // [target acquired] pathfind(cx, cy, world); return; } } } } } } <commit_msg>improve item acquisition and crafting AI<commit_after>/* Jim Viebke Jun 3 2015 */ #include "npc_enemy.h" void Hostile_NPC::update(World & world, map<string, shared_ptr<Character>> & actors) { // Every time this is called, the NPC executes one action against the world then returns. // Any number of internal objectives may be created, updated, or deleted. if (i_dont_have(C::AXE_ID) && !im_planning_to_acquire(C::AXE_ID)) { plan_to_get(C::AXE_ID); } if (i_dont_have(C::SWORD_ID) && !im_planning_to_acquire(C::SWORD_ID)) { plan_to_get(C::SWORD_ID); } // in this block: take the item if it's here, move to the item if it is visible and reachable, for (deque<Objective>::iterator objective_iterator = objectives.begin(); objective_iterator != objectives.end();) { if (objective_iterator->verb == C::AI_OBJECTIVE_ACQUIRE) { // if the item is here, take it, remove the current objective, and return if (world.room_at(x, y, z)->contains_item(objective_iterator->noun)) { take(objective_iterator->noun, world); if (objective_iterator->noun == objective_iterator->purpose) { // this item is an end goal erase_objectives_matching_purpose(objective_iterator->purpose); // erasing all objectives } else { // this item is a means to an end erase_objective(objective_iterator); } return; } // see if the item is reachable if (pathfind_to_closest_item(objective_iterator->noun, world)) { return; } // what's the difference between the above and below block? /*for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { if (!R::bounds_check(cx, cy)) { continue; } // skip if out of bounds if (world.room_at(cx, cy, z)->contains_item(objective_iterator->noun)) { if (pathfind(cx, cy, world)) { return; } } } }*/ // a path could not be found to the item, plan to craft it if it is craftable and the NPC isn't planning to already // if i'm not already planning on crafting the item // AND the item is craftable if (!objective_iterator->already_planning_to_craft && one_can_craft(objective_iterator->noun)) { objective_iterator->already_planning_to_craft = true; plan_to_craft(objective_iterator->noun); objective_iterator = objectives.begin(); // obligatory reset continue; // jump to next iteration } } // if I am planning on moving to an instance if (objective_iterator->verb == C::AI_OBJECTIVE_GOTO) { if (one_can_craft(objective_iterator->purpose) && i_have_all_ingredients_to_craft(objective_iterator->purpose)) { if (pathfind_to_closest_item(objective_iterator->noun, world)) { // delete extra objectives here // or maybe not; perhaps the objective should be cleared when the item is taken/crafted return; } } } ++objective_iterator; } // the next block: work through all objectives, see which objectives can be resolved through crafting attemps. for (deque<Objective>::iterator objective_iterator = objectives.begin(); objective_iterator != objectives.end(); ++objective_iterator) { // try to craft the item, using obj->purpose if the (obj->verb == GOTO), else use obj->noun (most cases) const string craft_attempt = craft(((objective_iterator->verb == C::AI_OBJECTIVE_GOTO) ? objective_iterator->purpose : objective_iterator->noun), world); // const string craft_attempt = craft(objective_iterator->noun, world); if (craft_attempt.find("You now have") != string::npos) { // if successful, clear completed objectives if (objective_iterator->verb == C::AI_OBJECTIVE_GOTO) { // the item crafted was from a "goto" objective // save this because our firse erase will invalidate the iterator const string PURPOSE = objective_iterator->purpose; // erase the "goto" erase_goto_objective_matching(PURPOSE); // erase the "aquire" erase_acquire_objective_matching(PURPOSE); } else if (objective_iterator->noun == objective_iterator->purpose) { // this item is an end goal erase_objectives_matching_purpose(objective_iterator->purpose); } else { // this item is only a means to an end erase_objective(objective_iterator); } return; } } // the next block: the NPC runs to the first player it finds IF // - it has completed crafting the sword and the axe and has completed all other objectives if (i_have(C::SWORD_ID) && i_have(C::AXE_ID) && objectives.size() == 0) { // for each row in view distance for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { // for each room in the row in view distance for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { // skip this room if it is out of bounds if (!R::bounds_check(cx, cy)) { continue; } // for each actor in the room for (const string & actor_ID : world.room_at(cx, cy, z)->get_actor_ids()) { // if the character is a player character if (R::is<PC>(actors.find(actor_ID)->second)) { // [target acquired] pathfind(cx, cy, world); return; } } } } } } <|endoftext|>
<commit_before>#include "wiVersion.h" #include <sstream> namespace wiVersion { // main engine core const int major = 0; // minor features, major updates const int minor = 18; // minor bug fixes, alterations, refactors, updates const int revision = 8; long GetVersion() { return major * 1000000 + minor * 1000 + revision; } int GetMajor() { return major; } int GetMinor() { return minor; } int GetRevision() { return revision; } std::string GetVersionString() { std::stringstream ss(""); ss << GetMajor() << "." << GetMinor() << "." << GetRevision(); return ss.str(); } } <commit_msg>changed version number after big graphics device update<commit_after>#include "wiVersion.h" #include <sstream> namespace wiVersion { // main engine core const int major = 0; // minor features, major updates const int minor = 19; // minor bug fixes, alterations, refactors, updates const int revision = 0; long GetVersion() { return major * 1000000 + minor * 1000 + revision; } int GetMajor() { return major; } int GetMinor() { return minor; } int GetRevision() { return revision; } std::string GetVersionString() { std::stringstream ss(""); ss << GetMajor() << "." << GetMinor() << "." << GetRevision(); return ss.str(); } } <|endoftext|>
<commit_before>#include <iostream> int main() { printf("Hello World!\n"); }<commit_msg>Fixed the invalid input section<commit_after>#include <iostream> #include <stdio.h> unsigned long Fabonacci_Lookup[31] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040 }; using namespace std; int main() { unsigned input; while (true) { cout << "\n\nEnter a number between 0 - 30\n"; cout << "Program will give back a Fibonacci answer that corresponds\n"; cout << "to that given number (index): "; // scanf_s("%d", &input); cin >> input; if (!cin) { cout.flush(); cin.clear(); // Clear out all failbit flags cin.ignore(INT_MAX, '\n'); // Ignore all corrupted input until the next Newline cout << "Invalid input.\n"; continue; } if ((input < 0) || (input > 30)) { printf("Enter a number between 0 - 31 only.\n"); continue; } // Search the lookup table printf("The fibonacci number for the given number is: %u\n", Fabonacci_Lookup[input]); printf("Press Ctrl-C to quit.\n"); } }<|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 "Common.h" #include "Statistics.h" #include "BitcoinUtils.h" //////////////////////////////// StatsWindow ///////////////////////////////// TEST(StatsWindow, clear) { int windowSize = 60; for (int j = 0; j < 10; j++) { StatsWindow<int64> sw(windowSize); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); int64 val = 3; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val); sw.clear(); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); } } TEST(StatsWindow, sum01) { int windowSize = 60; StatsWindow<int64> sw(windowSize); int64 val = 5; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize*2; i < windowSize*3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum02) { int windowSize = 60; StatsWindow<int64> sw(windowSize); int64 val = 5; for (int i = windowSize - 1; i >= 0; i--) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize*2; i < windowSize*3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum03) { StatsWindow<int64> sw(5); sw.insert(0, 1); ASSERT_EQ(sw.sum(0, 1), 1); sw.clear(); ASSERT_EQ(sw.sum(0, 1), 0); sw.insert(0, 1); sw.insert(5, 5); ASSERT_EQ(sw.sum(5, 1), 5); ASSERT_EQ(sw.sum(5, 5), 5); sw.clear(); sw.insert(0, 1); sw.insert(1, 2); sw.insert(2, 3); sw.insert(3, 4); sw.insert(4, 5); ASSERT_EQ(sw.sum(4, 1), 5); ASSERT_EQ(sw.sum(4, 2), 9); ASSERT_EQ(sw.sum(4, 3), 12); ASSERT_EQ(sw.sum(4, 4), 14); ASSERT_EQ(sw.sum(4, 5), 15); sw.insert(8, 9); ASSERT_EQ(sw.sum(8, 5), 14); sw.insert(7, 8); ASSERT_EQ(sw.sum(8, 5), 22); sw.insert(6, 7); ASSERT_EQ(sw.sum(8, 5), 29); sw.insert(5, 6); ASSERT_EQ(sw.sum(8, 5), 35); } TEST(StatsWindow, map) { int windowSize = 10; StatsWindow<int64> sw(windowSize); for (int i = 0; i < windowSize; i++) { sw.insert(i, i * 2); } ASSERT_EQ(sw.sum(windowSize-1), sw.sum(windowSize-1, windowSize)); int64 sum = sw.sum(windowSize-1, windowSize); sw.mapDivide(2); int64 sum2 = sw.sum(windowSize-1, windowSize); ASSERT_EQ(sum/2, sum2); sw.mapMultiply(2); int64 sum3 = sw.sum(windowSize-1, windowSize); ASSERT_EQ(sum, sum3); } //////////////////////////////// ShareStatsDay /////////////////////////////// TEST(ShareStatsDay, ShareStatsDay) { // using mainnet SelectParams(CBaseChainParams::MAIN); // 1 { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.height_ = 504031; share.status_ = StratumStatus::ACCEPT; uint64_t shareValue = 1ll; auto reward = GetBlockReward(share.height_, Params().GetConsensus()); // share -> socre = 1 : 1 // https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f share.blkBits_ = 0x1d00ffffu; // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.shareDiff_ = shareValue; stats.processShare(i, share); } // reject share.status_ = StratumStatus::REJECT_NO_REASON; for (uint32_t i = 0; i < 24; i++) { share.shareDiff_ = shareValue; stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); ASSERT_EQ(ss.earn_, 1 * reward); } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); ASSERT_EQ(ss.earn_, 1 * 24 * reward); } // UINT32_MAX { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.height_ = 504031; share.status_ = StratumStatus::ACCEPT; uint64_t shareValue = UINT32_MAX; // share -> socre = UINT32_MAX : 0.0197582875516673 // https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76 share.blkBits_ = 0x18050edcu; // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.shareDiff_ = shareValue; stats.processShare(i, share); // LOG(INFO) << score2Str(share.score()); } // reject share.status_ = StratumStatus::REJECT_NO_REASON; for (uint32_t i = 0; i < 24; i++) { share.shareDiff_ = shareValue; stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 24697859); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 1975828); // satoshi, only for UBTC #endif } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((uint64_t)ss.earn_, 592748626); // satoshi #else ASSERT_EQ((uint64_t)ss.earn_, 47419890); // satoshi, only for UBTC #endif } } <commit_msg>testcase: fix build warning.<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] 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 "Common.h" #include "Statistics.h" #include "BitcoinUtils.h" //////////////////////////////// StatsWindow ///////////////////////////////// TEST(StatsWindow, clear) { int windowSize = 60; for (int j = 0; j < 10; j++) { StatsWindow<int64> sw(windowSize); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); int64 val = 3; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val); sw.clear(); ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0); } } TEST(StatsWindow, sum01) { int windowSize = 60; StatsWindow<int64> sw(windowSize); int64 val = 5; for (int i = 0; i < windowSize; i++) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize*2; i < windowSize*3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum02) { int windowSize = 60; StatsWindow<int64> sw(windowSize); int64 val = 5; for (int i = windowSize - 1; i >= 0; i--) { sw.insert(i, val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(i, 1), val); } for (int i = 0; i < windowSize; i++) { ASSERT_EQ(sw.sum(windowSize - 1, i), i * val); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, 1), 0); } for (int i = windowSize; i < windowSize*2; i++) { ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val); } for (int i = windowSize*2; i < windowSize*3; i++) { ASSERT_EQ(sw.sum(i, windowSize), 0); } } TEST(StatsWindow, sum03) { StatsWindow<int64> sw(5); sw.insert(0, 1); ASSERT_EQ(sw.sum(0, 1), 1); sw.clear(); ASSERT_EQ(sw.sum(0, 1), 0); sw.insert(0, 1); sw.insert(5, 5); ASSERT_EQ(sw.sum(5, 1), 5); ASSERT_EQ(sw.sum(5, 5), 5); sw.clear(); sw.insert(0, 1); sw.insert(1, 2); sw.insert(2, 3); sw.insert(3, 4); sw.insert(4, 5); ASSERT_EQ(sw.sum(4, 1), 5); ASSERT_EQ(sw.sum(4, 2), 9); ASSERT_EQ(sw.sum(4, 3), 12); ASSERT_EQ(sw.sum(4, 4), 14); ASSERT_EQ(sw.sum(4, 5), 15); sw.insert(8, 9); ASSERT_EQ(sw.sum(8, 5), 14); sw.insert(7, 8); ASSERT_EQ(sw.sum(8, 5), 22); sw.insert(6, 7); ASSERT_EQ(sw.sum(8, 5), 29); sw.insert(5, 6); ASSERT_EQ(sw.sum(8, 5), 35); } TEST(StatsWindow, map) { int windowSize = 10; StatsWindow<int64> sw(windowSize); for (int i = 0; i < windowSize; i++) { sw.insert(i, i * 2); } ASSERT_EQ(sw.sum(windowSize-1), sw.sum(windowSize-1, windowSize)); int64 sum = sw.sum(windowSize-1, windowSize); sw.mapDivide(2); int64 sum2 = sw.sum(windowSize-1, windowSize); ASSERT_EQ(sum/2, sum2); sw.mapMultiply(2); int64 sum3 = sw.sum(windowSize-1, windowSize); ASSERT_EQ(sum, sum3); } //////////////////////////////// ShareStatsDay /////////////////////////////// TEST(ShareStatsDay, ShareStatsDay) { // using mainnet SelectParams(CBaseChainParams::MAIN); // 1 { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.height_ = 504031; share.status_ = StratumStatus::ACCEPT; uint64_t shareValue = 1ll; auto reward = GetBlockReward(share.height_, Params().GetConsensus()); // share -> socre = 1 : 1 // https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f share.blkBits_ = 0x1d00ffffu; // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.shareDiff_ = shareValue; stats.processShare(i, share); } // reject share.status_ = StratumStatus::REJECT_NO_REASON; for (uint32_t i = 0; i < 24; i++) { share.shareDiff_ = shareValue; stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); ASSERT_EQ(ss.earn_, 1 * reward); } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); ASSERT_EQ(ss.earn_, 1 * 24 * reward); } // UINT32_MAX { ShareStatsDay<ShareBitcoin> stats; ShareBitcoin share; share.height_ = 504031; share.status_ = StratumStatus::ACCEPT; uint64_t shareValue = UINT32_MAX; // share -> socre = UINT32_MAX : 0.0197582875516673 // https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76 share.blkBits_ = 0x18050edcu; // accept for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23] share.shareDiff_ = shareValue; stats.processShare(i, share); // LOG(INFO) << score2Str(share.score()); } // reject share.status_ = StratumStatus::REJECT_NO_REASON; for (uint32_t i = 0; i < 24; i++) { share.shareDiff_ = shareValue; stats.processShare(i, share); } ShareStats ss; for (uint32_t i = 0; i < 24; i++) { stats.getShareStatsHour(i, &ss); ASSERT_EQ(ss.shareAccept_, shareValue); ASSERT_EQ(ss.shareReject_, shareValue); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((int64_t)ss.earn_, 24697859); // satoshi #else ASSERT_EQ((int64_t)ss.earn_, 1975828); // satoshi, only for UBTC #endif } stats.getShareStatsDay(&ss); ASSERT_EQ(ss.shareAccept_, shareValue * 24); ASSERT_EQ(ss.shareReject_, shareValue * 24); #ifndef CHAIN_TYPE_UBTC ASSERT_EQ((int64_t)ss.earn_, 592748626); // satoshi #else ASSERT_EQ((int64_t)ss.earn_, 47419890); // satoshi, only for UBTC #endif } } <|endoftext|>
<commit_before>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "pockets/Types.h" using namespace ci; using namespace ci::app; using namespace std; using namespace entityx; using pockets::Vertex2d; struct Locus : Component<Locus> { Locus() = default; Locus( const ci::Vec2f &pos, const ci::Vec2f &registration, float rot, shared_ptr<Locus> parent=nullptr ): position( pos ), registration_point( registration ), rotation( rot ), parent( parent ) {} ci::Vec2f position = ci::Vec2f::zero(); ci::Vec2f registration_point = ci::Vec2f::zero(); float rotation = 0.0f; shared_ptr<Locus> parent = nullptr; ci::MatrixAffine2f toMatrix() const{ MatrixAffine2f mat; mat.translate( position + registration_point ); mat.rotate( rotation ); mat.translate( -registration_point ); if( parent ){ mat = parent->toMatrix() * mat; } return mat; } }; struct Mesh : Component<Mesh> { Mesh( int render_layer=0, const ci::Rectf &bounds={ -20.0f, -10.0f, 20.0f, 10.0f } ): render_layer( render_layer ) { vertices.assign( 4, Vertex2d{} ); vertices[0].position = bounds.getUpperRight(); vertices[1].position = bounds.getUpperLeft(); vertices[2].position = bounds.getLowerRight(); vertices[3].position = bounds.getLowerLeft(); } std::vector<Vertex2d> vertices; int render_layer = 0; }; struct Velocity : Component<Velocity> { Velocity( float x = 0.0f, float y = 0.0f ): velocity( x, y ) {} ci::Vec2f velocity; }; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { for( auto entity : es->entities_with_components<Locus>() ) { auto loc = entity.component<Locus>(); loc->rotation = fmodf( loc->rotation + M_PI * 0.01f, M_PI * 2 ); } } }; struct RenderSystem : public System<RenderSystem> { typedef pair<shared_ptr<Locus>, shared_ptr<Mesh>> MeshPair; void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mGeometry.empty() ) { for( auto entity : es->entities_with_components<Locus, Mesh>() ) { mGeometry.emplace_back( entity.component<Locus>(), entity.component<Mesh>() ); } stable_sort( mGeometry.begin(), mGeometry.end(), []( const MeshPair &lhs, const MeshPair &rhs ) -> bool { return lhs.second->render_layer < rhs.second->render_layer; } ); } // assemble all vertices mVertices.clear(); for( auto pair : mGeometry ) { auto loc = pair.first; auto mesh = pair.second; auto mat = loc->toMatrix(); if( !mVertices.empty() ) { // create degenerate triangle between previous and current shape mVertices.emplace_back( mVertices.back() ); auto vert = mesh->vertices.front(); mVertices.emplace_back( Vertex2d{ mat.transformPoint( vert.position ), vert.color, vert.tex_coord } ); } for( auto &vert : mesh->vertices ) { mVertices.emplace_back( Vertex2d{ mat.transformPoint( vert.position ), vert.color, vert.tex_coord } ); } } } void draw() { glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glVertexPointer( 2, GL_FLOAT, sizeof( Vertex2d ), &mVertices[0].position.x ); glTexCoordPointer( 2, GL_FLOAT, sizeof( Vertex2d ), &mVertices[0].tex_coord.x ); glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Vertex2d ), &mVertices[0].color.r ); glDrawArrays( GL_TRIANGLE_STRIP, 0, mVertices.size() ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } private: std::vector<MeshPair> mGeometry; std::vector<Vertex2d> mVertices; }; class PupTentApp : public AppNative { public: void setup(); void mouseDown( MouseEvent event ); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; shared_ptr<MovementSystem> mMovement; double mLastUpdate = 0.0; double mAverageRenderTime = 0; }; void PupTentApp::setup() { mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); mSystemManager->add<RenderSystem>(); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); for( int i = 0; i < 2000; ++i ) { Entity entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; auto mesh = shared_ptr<Mesh>{ new Mesh }; ColorA color{ CM_HSV, r.nextFloat( 1.0f ), 0.9f, 0.9f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); mesh->render_layer = loc->position.distance( center ); entity.assign<Locus>( loc ); entity.assign<Mesh>( mesh ); } } void PupTentApp::mouseDown( MouseEvent event ) { } void PupTentApp::update() { double now = getElapsedSeconds(); double dt = now - mLastUpdate; mLastUpdate = now; // double start = getElapsedSeconds(); mSystemManager->update<MovementSystem>( dt ); // double end = getElapsedSeconds(); // cout << "Update: " << (end - start) * 1000 << endl; } void PupTentApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); double start = getElapsedSeconds(); mSystemManager->update<RenderSystem>( 0.0 ); mSystemManager->system<RenderSystem>()->draw(); double end = getElapsedSeconds(); double ms = (end - start) * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 120 == 0 ) { cout << "Render ms: " << mAverageRenderTime << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl ) <commit_msg>Cacheing update query as well.<commit_after>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "pockets/Types.h" using namespace ci; using namespace ci::app; using namespace std; using namespace entityx; using pockets::Vertex2d; struct Locus : Component<Locus> { Locus() = default; Locus( const ci::Vec2f &pos, const ci::Vec2f &registration, float rot, shared_ptr<Locus> parent=nullptr ): position( pos ), registration_point( registration ), rotation( rot ), parent( parent ) {} ci::Vec2f position = ci::Vec2f::zero(); ci::Vec2f registration_point = ci::Vec2f::zero(); float rotation = 0.0f; shared_ptr<Locus> parent = nullptr; ci::MatrixAffine2f toMatrix() const{ MatrixAffine2f mat; mat.translate( position + registration_point ); mat.rotate( rotation ); mat.translate( -registration_point ); if( parent ){ mat = parent->toMatrix() * mat; } return mat; } }; struct Mesh : Component<Mesh> { Mesh( int render_layer=0, const ci::Rectf &bounds={ -20.0f, -10.0f, 20.0f, 10.0f } ): render_layer( render_layer ) { vertices.assign( 4, Vertex2d{} ); vertices[0].position = bounds.getUpperRight(); vertices[1].position = bounds.getUpperLeft(); vertices[2].position = bounds.getLowerRight(); vertices[3].position = bounds.getLowerLeft(); } std::vector<Vertex2d> vertices; int render_layer = 0; }; struct Velocity : Component<Velocity> { Velocity( float x = 0.0f, float y = 0.0f ): velocity( x, y ) {} ci::Vec2f velocity; }; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mElements.empty() ) { for( auto entity : es->entities_with_components<Locus>() ) { mElements.push_back( entity.component<Locus>() ); } } for( auto& loc : mElements ) { loc->rotation = fmodf( loc->rotation + M_PI * 0.01f, M_PI * 2 ); } } vector<shared_ptr<Locus>> mElements; }; /** Basic layer-sorted rendering system */ struct RenderSystem : public System<RenderSystem>, Receiver<RenderSystem> { typedef pair<shared_ptr<Locus>, shared_ptr<Mesh>> MeshPair; void configure( EventManager &event_manager ) { event_manager.subscribe<EntityDestroyedEvent>( *this ); event_manager.subscribe<ComponentAddedEvent<Mesh>>( *this ); } void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { // build our sorted geometry list from query if the layers/components have changed // need to rebuild if any meshes are removed or added if( mGeometry.empty() ) { for( auto entity : es->entities_with_components<Locus, Mesh>() ) { mGeometry.emplace_back( entity.component<Locus>(), entity.component<Mesh>() ); } stable_sort( mGeometry.begin(), mGeometry.end(), []( const MeshPair &lhs, const MeshPair &rhs ) -> bool { return lhs.second->render_layer < rhs.second->render_layer; } ); } // assemble all vertices mVertices.clear(); for( auto pair : mGeometry ) { auto loc = pair.first; auto mesh = pair.second; auto mat = loc->toMatrix(); if( !mVertices.empty() ) { // create degenerate triangle between previous and current shape mVertices.emplace_back( mVertices.back() ); auto vert = mesh->vertices.front(); mVertices.emplace_back( Vertex2d{ mat.transformPoint( vert.position ), vert.color, vert.tex_coord } ); } for( auto &vert : mesh->vertices ) { mVertices.emplace_back( Vertex2d{ mat.transformPoint( vert.position ), vert.color, vert.tex_coord } ); } } } void receive( const EntityDestroyedEvent &event ) { auto entity = event.entity; if( entity.component<Mesh>() ) { // if a mesh was destroyed, we will update our render list this frame mGeometry.clear(); } } void receive( const ComponentAddedEvent<Mesh> &event ) { // empty our geometry mGeometry.clear(); } void draw() { glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_COLOR_ARRAY ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glVertexPointer( 2, GL_FLOAT, sizeof( Vertex2d ), &mVertices[0].position.x ); glTexCoordPointer( 2, GL_FLOAT, sizeof( Vertex2d ), &mVertices[0].tex_coord.x ); glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Vertex2d ), &mVertices[0].color.r ); glDrawArrays( GL_TRIANGLE_STRIP, 0, mVertices.size() ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } private: std::vector<MeshPair> mGeometry; std::vector<Vertex2d> mVertices; }; class PupTentApp : public AppNative { public: void setup(); void mouseDown( MouseEvent event ); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; shared_ptr<MovementSystem> mMovement; double mLastUpdate = 0.0; double mAverageRenderTime = 0; }; void PupTentApp::setup() { mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); mSystemManager->add<RenderSystem>(); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); for( int i = 0; i < 50000; ++i ) { Entity entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; auto mesh = shared_ptr<Mesh>{ new Mesh }; ColorA color{ CM_HSV, r.nextFloat( 1.0f ), 0.9f, 0.9f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); mesh->render_layer = loc->position.distance( center ); entity.assign<Locus>( loc ); entity.assign<Mesh>( mesh ); } } void PupTentApp::mouseDown( MouseEvent event ) {} void PupTentApp::update() { double now = getElapsedSeconds(); double dt = now - mLastUpdate; mLastUpdate = now; double start = getElapsedSeconds(); mSystemManager->update<MovementSystem>( dt ); double end = getElapsedSeconds(); if( getElapsedFrames() % 120 == 0 ) { cout << "Update: " << (end - start) * 1000 << endl; } } void PupTentApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); double start = getElapsedSeconds(); mSystemManager->update<RenderSystem>( 0.0 ); mSystemManager->system<RenderSystem>()->draw(); double end = getElapsedSeconds(); double ms = (end - start) * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 120 == 0 ) { cout << "Render ms: " << mAverageRenderTime << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl ) <|endoftext|>
<commit_before>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "cinder/Json.h" #include "cinder/ip/Premultiply.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "puptent/BatchRenderSystem2d.h" #include "puptent/PhysicsSystem2d.h" #include "puptent/TextureAtlas.h" #include "puptent/SpriteAnimation.h" /** Sample app used to develop features of PupTent. Learning about component systems and building my own components. While everything is dependent on the underlying component machinery, it is wonderfully decoupled from other systems and components. */ using namespace ci; using namespace ci::app; using namespace std; using namespace puptent; using namespace entityx; using pockets::Vertex2d; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mElements.empty() ) { for( auto entity : es->entities_with_components<Locus>() ) { mElements.push_back( entity.component<Locus>() ); } } time += dt; for( auto& loc : mElements ) { loc->rotation = fmodf( loc->rotation - M_PI * 0.01f, M_PI * 2 ); loc->scale = math<float>::sin( 0.5f * time + M_PI * loc->position.x / 640.0f + M_PI * loc->position.y / 480.0f ); } } double time = 0.0; vector<shared_ptr<Locus>> mElements; }; class PupTentApp : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; double mAverageUpdateTime = 1.0; double mAverageRenderTime = 1.0; Timer mTimer; TextureAtlas mTextureAtlas; }; void PupTentApp::prepareSettings( Settings *settings ) { settings->disableFrameRate(); settings->setWindowSize( 1024, 768 ); // settings->setFullScreen(); } void PupTentApp::setup() { gl::enableVerticalSync(); Surface sprite_surf{ loadImage( loadAsset( "spritesheet.png" ) ) }; if( !sprite_surf.isPremultiplied() ) { ip::premultiply( &sprite_surf ); } TextureAtlasRef atlas = TextureAtlas::create( sprite_surf, JsonTree( loadAsset( "spritesheet.json" ) ) ); JsonTree animations{ loadAsset( "animations.json" ) }; mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); auto physics = mSystemManager->add<PhysicsSystem2d>(); physics->createBoundaryRect( getWindowBounds() ); auto renderer = mSystemManager->add<BatchRenderSystem2d>(); renderer->setTexture( atlas->getTexture() ); shared_ptr<SpriteAnimationSystem> sprite_system{ new SpriteAnimationSystem{ atlas, animations } }; mSystemManager->add( sprite_system ); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); Entity entity; for( int i = 0; i < 8000; ++i ) { entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; // get an animation out of the sprite system auto anim = sprite_system->createSpriteAnimation( "dot" ); loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); loc->registration_point = { 0, 0 }; float dist = loc->position.distance( center ); ColorA color{ CM_HSV, 0.0f, 0.0f, lmap( dist, 0.0f, 0.75f * getWindowWidth(), 0.0f, 1.0f ), 1.0f }; // entity.assign( physics->createBox( loc->position, atlas->get( "d-0001" ).size / 12.0f, loc->rotation ) ); auto mesh = entity.assign<RenderMesh2d>( 4, dist ); for( auto &v : mesh->vertices ) { v.color = color; } entity.assign( anim ); entity.assign( loc ); } getWindow()->getSignalMouseDown().connect( [=]( MouseEvent &event ) mutable { if( entity.valid() ) { if( entity.component<SpriteAnimation>() ) { cout << "Removing Sprite Animation component: " << entity << endl; entity.remove<SpriteAnimation>(); } else { cout << "Adding Mesh component: " << entity << endl; auto mesh = RenderMesh2dRef{ new RenderMesh2d{ 4 } }; // perhaps have a component to hang on to texturing data mesh->setAsTexture( atlas->get( "dl-0001" ) ); mesh->render_layer = 1000; ColorA color{ 1.0f, 1.0f, 1.0f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } entity.assign<RenderMesh2d>( mesh ); } } }); mTimer.start(); } void PupTentApp::update() { double dt = mTimer.getSeconds(); mTimer.start(); Timer up; up.start(); mSystemManager->system<PhysicsSystem2d>()->stepPhysics(); // could parallelize this with sprite animation and some other things... mSystemManager->update<PhysicsSystem2d>( dt ); mSystemManager->update<MovementSystem>( dt ); mSystemManager->update<SpriteAnimationSystem>( dt ); mSystemManager->update<BatchRenderSystem2d>( dt ); double ms = up.getSeconds() * 1000; mAverageUpdateTime = (mAverageUpdateTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 90 == 0 ) { cout << "Update: " << mAverageUpdateTime << ", " << ms << endl; } } void PupTentApp::draw() { gl::clear( Color::black() ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::color( Color::white() ); Timer dr; dr.start(); mSystemManager->system<BatchRenderSystem2d>()->draw(); // mSystemManager->system<PhysicsSystem2d>()->debugDraw(); double ms = dr.getSeconds() * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 90 == 0 ) { cout << "Render ms: " << mAverageRenderTime << ", " << ms << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl( RendererGl::AA_MSAA_8 ) ) <commit_msg>10k entities.<commit_after>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "cinder/Json.h" #include "cinder/ip/Premultiply.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "puptent/BatchRenderSystem2d.h" #include "puptent/PhysicsSystem2d.h" #include "puptent/TextureAtlas.h" #include "puptent/SpriteAnimation.h" /** Sample app used to develop features of PupTent. Learning about component systems and building my own components. While everything is dependent on the underlying component machinery, it is wonderfully decoupled from other systems and components. */ using namespace ci; using namespace ci::app; using namespace std; using namespace puptent; using namespace entityx; using pockets::Vertex2d; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mElements.empty() ) { for( auto entity : es->entities_with_components<Locus>() ) { mElements.push_back( entity.component<Locus>() ); } } time += dt; for( auto& loc : mElements ) { loc->rotation = fmodf( loc->rotation - M_PI * 0.01f, M_PI * 2 ); loc->scale = math<float>::sin( 0.5f * time + M_PI * loc->position.x / 640.0f + M_PI * loc->position.y / 480.0f ); } } double time = 0.0; vector<shared_ptr<Locus>> mElements; }; class PupTentApp : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; double mAverageUpdateTime = 1.0; double mAverageRenderTime = 1.0; Timer mTimer; TextureAtlas mTextureAtlas; }; void PupTentApp::prepareSettings( Settings *settings ) { settings->disableFrameRate(); settings->setWindowSize( 1024, 768 ); // settings->setFullScreen(); } void PupTentApp::setup() { gl::enableVerticalSync(); Surface sprite_surf{ loadImage( loadAsset( "spritesheet.png" ) ) }; if( !sprite_surf.isPremultiplied() ) { ip::premultiply( &sprite_surf ); } TextureAtlasRef atlas = TextureAtlas::create( sprite_surf, JsonTree( loadAsset( "spritesheet.json" ) ) ); JsonTree animations{ loadAsset( "animations.json" ) }; mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); auto physics = mSystemManager->add<PhysicsSystem2d>(); physics->createBoundaryRect( getWindowBounds() ); auto renderer = mSystemManager->add<BatchRenderSystem2d>(); renderer->setTexture( atlas->getTexture() ); shared_ptr<SpriteAnimationSystem> sprite_system{ new SpriteAnimationSystem{ atlas, animations } }; mSystemManager->add( sprite_system ); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); Entity entity; for( int i = 0; i < 10000; ++i ) { entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; // get an animation out of the sprite system auto anim = sprite_system->createSpriteAnimation( "dot" ); loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); loc->registration_point = { 0, 0 }; float dist = loc->position.distance( center ); ColorA color{ CM_HSV, 0.0f, 0.0f, lmap( dist, 0.0f, 0.75f * getWindowWidth(), 0.0f, 1.0f ), 1.0f }; // entity.assign( physics->createBox( loc->position, atlas->get( "d-0001" ).size / 12.0f, loc->rotation ) ); auto mesh = entity.assign<RenderMesh2d>( 4, dist ); for( auto &v : mesh->vertices ) { v.color = color; } entity.assign( anim ); entity.assign( loc ); } getWindow()->getSignalMouseDown().connect( [=]( MouseEvent &event ) mutable { if( entity.valid() ) { if( entity.component<SpriteAnimation>() ) { cout << "Removing Sprite Animation component: " << entity << endl; entity.remove<SpriteAnimation>(); } else { cout << "Adding Mesh component: " << entity << endl; auto mesh = RenderMesh2dRef{ new RenderMesh2d{ 4 } }; // perhaps have a component to hang on to texturing data mesh->setAsTexture( atlas->get( "dl-0001" ) ); mesh->render_layer = 1000; ColorA color{ 1.0f, 1.0f, 1.0f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } entity.assign<RenderMesh2d>( mesh ); } } }); mTimer.start(); } void PupTentApp::update() { double dt = mTimer.getSeconds(); mTimer.start(); Timer up; up.start(); mSystemManager->system<PhysicsSystem2d>()->stepPhysics(); // could parallelize this with sprite animation and some other things... mSystemManager->update<PhysicsSystem2d>( dt ); mSystemManager->update<MovementSystem>( dt ); mSystemManager->update<SpriteAnimationSystem>( dt ); mSystemManager->update<BatchRenderSystem2d>( dt ); double ms = up.getSeconds() * 1000; mAverageUpdateTime = (mAverageUpdateTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 90 == 0 ) { cout << "Update: " << mAverageUpdateTime << ", " << ms << endl; } } void PupTentApp::draw() { gl::clear( Color::black() ); gl::disableDepthRead(); gl::disableDepthWrite(); gl::color( Color::white() ); Timer dr; dr.start(); mSystemManager->system<BatchRenderSystem2d>()->draw(); // mSystemManager->system<PhysicsSystem2d>()->debugDraw(); double ms = dr.getSeconds() * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 90 == 0 ) { cout << "Render ms: " << mAverageRenderTime << ", " << ms << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl( RendererGl::AA_MSAA_8 ) ) <|endoftext|>
<commit_before>/* IMPORTANT! This file is auto-generated each time you save your project - if you alter its contents, your changes may be overwritten! */ #include "AppConfig.h" #include <juce_video/juce_video.cpp> <commit_msg>Delete juce_video.cpp<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drtxtob2.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:54:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------- #include "scitems.hxx" #include <svx/adjitem.hxx> #include <svx/drawitem.hxx> #include <svx/fontwork.hxx> #include <svx/frmdiritem.hxx> #include <svx/outlobj.hxx> #include <svx/svdocapt.hxx> #include <svx/xtextit.hxx> #ifndef _SVX_WRITINGMODEITEM_HXX #include <svx/writingmodeitem.hxx> #endif #include <sfx2/bindings.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/objsh.hxx> #include <sfx2/request.hxx> #include <sot/formats.hxx> #include <svtools/whiter.hxx> #include "sc.hrc" #include "drtxtob.hxx" #include "viewdata.hxx" #include "drawview.hxx" #include "tabvwsh.hxx" #include "impex.hxx" #include "docsh.hxx" #include "transobj.hxx" #include "drwtrans.hxx" //------------------------------------------------------------------------ USHORT ScGetFontWorkId() { return SvxFontWorkChildWindow::GetChildWindowId(); } BOOL ScDrawTextObjectBar::IsNoteEdit() { ScTabView* pTabView = pViewData->GetView(); SdrView* pSdrView = pTabView->GetSdrView(); SdrObject* pObject = pSdrView->GetTextEditObject(); return ( pObject && pObject->GetLayer() == SC_LAYER_INTERN && pObject->ISA( SdrCaptionObj ) ); } // wenn kein Text editiert wird, Funktionen wie in drawsh void __EXPORT ScDrawTextObjectBar::ExecuteGlobal( SfxRequest &rReq ) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pView = pTabView->GetScDrawView(); USHORT nSlot = rReq.GetSlot(); switch ( nSlot ) { case SID_COPY: pView->DoCopy(); break; case SID_CUT: pView->DoCut(); if (!pTabView->IsDrawSelMode()) pViewData->GetViewShell()->SetDrawShell( FALSE ); break; case SID_PASTE: case FID_PASTE_CONTENTS: case SID_CLIPBOARD_FORMAT_ITEMS: case SID_HYPERLINK_SETLINK: { // cell methods are at cell shell, which is not available if // ScDrawTextObjectBar is active //! move paste etc. to view shell? } break; case SID_SELECTALL: pView->MarkAll(); break; case SID_TEXTDIRECTION_LEFT_TO_RIGHT: case SID_TEXTDIRECTION_TOP_TO_BOTTOM: { SfxItemSet aAttr( pView->GetModel()->GetItemPool(), SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, 0 ); aAttr.Put( SvxWritingModeItem( nSlot == SID_TEXTDIRECTION_LEFT_TO_RIGHT ? com::sun::star::text::WritingMode_LR_TB : com::sun::star::text::WritingMode_TB_RL ) ); pView->SetAttributes( aAttr ); pViewData->GetScDrawView()->InvalidateDrawTextAttrs(); // Bidi slots may be disabled rReq.Done( aAttr ); } break; case SID_ENABLE_HYPHENATION: { SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, SID_ENABLE_HYPHENATION, FALSE); if( pItem ) { SfxItemSet aSet( GetPool(), EE_PARA_HYPHENATE, EE_PARA_HYPHENATE ); BOOL bValue = ( (const SfxBoolItem*) pItem)->GetValue(); aSet.Put( SfxBoolItem( EE_PARA_HYPHENATE, bValue ) ); pView->SetAttributes( aSet ); } rReq.Done(); } break; } } void ScDrawTextObjectBar::GetGlobalClipState( SfxItemSet& rSet ) { // cell methods are at cell shell, which is not available if // ScDrawTextObjectBar is active -> disable everything //! move paste etc. to view shell? SfxWhichIter aIter(rSet); USHORT nWhich = aIter.FirstWhich(); while (nWhich) { rSet.DisableItem( nWhich ); nWhich = aIter.NextWhich(); } } void __EXPORT ScDrawTextObjectBar::ExecuteExtra( SfxRequest &rReq ) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pView = pTabView->GetScDrawView(); USHORT nSlot = rReq.GetSlot(); switch ( nSlot ) { case SID_FONTWORK: { USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); if ( rReq.GetArgs() ) pViewFrm->SetChildWindow( nId, ((const SfxBoolItem&) (rReq.GetArgs()->Get(SID_FONTWORK))). GetValue() ); else pViewFrm->ToggleChildWindow( nId ); pViewFrm->GetBindings().Invalidate( SID_FONTWORK ); rReq.Done(); } break; case SID_ATTR_PARA_LEFT_TO_RIGHT: case SID_ATTR_PARA_RIGHT_TO_LEFT: { SfxItemSet aAttr( pView->GetModel()->GetItemPool(), EE_PARA_WRITINGDIR, EE_PARA_WRITINGDIR, EE_PARA_JUST, EE_PARA_JUST, 0 ); BOOL bLeft = ( nSlot == SID_ATTR_PARA_LEFT_TO_RIGHT ); aAttr.Put( SvxFrameDirectionItem( bLeft ? FRMDIR_HORI_LEFT_TOP : FRMDIR_HORI_RIGHT_TOP, EE_PARA_WRITINGDIR ) ); aAttr.Put( SvxAdjustItem( bLeft ? SVX_ADJUST_LEFT : SVX_ADJUST_RIGHT, EE_PARA_JUST ) ); pView->SetAttributes( aAttr ); pViewData->GetScDrawView()->InvalidateDrawTextAttrs(); rReq.Done(); //! Done(aAttr) ? } break; } } void ScDrawTextObjectBar::ExecFormText(SfxRequest& rReq) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pDrView = pTabView->GetScDrawView(); const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList(); if ( rMarkList.GetMarkCount() == 1 && rReq.GetArgs() ) { const SfxItemSet& rSet = *rReq.GetArgs(); const SfxPoolItem* pItem; if ( pDrView->IsTextEdit() ) pDrView->ScEndTextEdit(); if ( SFX_ITEM_SET == rSet.GetItemState(XATTR_FORMTXTSTDFORM, TRUE, &pItem) && XFTFORM_NONE != ((const XFormTextStdFormItem*) pItem)->GetValue() ) { USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); SvxFontWorkDialog* pDlg = (SvxFontWorkDialog*) (pViewFrm-> GetChildWindow(nId)->GetWindow()); pDlg->CreateStdFormObj(*pDrView, *pDrView->GetPageViewPvNum(0), rSet, *rMarkList.GetMark(0)->GetObj(), ((const XFormTextStdFormItem*) pItem)-> GetValue()); } else pDrView->SetAttributes(rSet); } } void ScDrawTextObjectBar::GetFormTextState(SfxItemSet& rSet) { const SdrObject* pObj = NULL; SvxFontWorkDialog* pDlg = NULL; ScDrawView* pDrView = pViewData->GetView()->GetScDrawView(); const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList(); USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); if ( pViewFrm->HasChildWindow(nId) ) pDlg = (SvxFontWorkDialog*)(pViewFrm->GetChildWindow(nId)->GetWindow()); if ( rMarkList.GetMarkCount() == 1 ) pObj = rMarkList.GetMark(0)->GetObj(); if ( pObj == NULL || !pObj->ISA(SdrTextObj) || !((SdrTextObj*) pObj)->HasText() ) { if ( pDlg ) pDlg->SetActive(FALSE); rSet.DisableItem(XATTR_FORMTXTSTYLE); rSet.DisableItem(XATTR_FORMTXTADJUST); rSet.DisableItem(XATTR_FORMTXTDISTANCE); rSet.DisableItem(XATTR_FORMTXTSTART); rSet.DisableItem(XATTR_FORMTXTMIRROR); rSet.DisableItem(XATTR_FORMTXTSTDFORM); rSet.DisableItem(XATTR_FORMTXTHIDEFORM); rSet.DisableItem(XATTR_FORMTXTOUTLINE); rSet.DisableItem(XATTR_FORMTXTSHADOW); rSet.DisableItem(XATTR_FORMTXTSHDWCOLOR); rSet.DisableItem(XATTR_FORMTXTSHDWXVAL); rSet.DisableItem(XATTR_FORMTXTSHDWYVAL); } else { if ( pDlg ) { SfxObjectShell* pDocSh = SfxObjectShell::Current(); if ( pDocSh ) { const SfxPoolItem* pItem = pDocSh->GetItem( ITEMID_COLOR_TABLE ); XColorTable* pColorTable = NULL; if ( pItem ) pColorTable = ((SvxColorTableItem*)pItem)->GetColorTable(); pDlg->SetActive(); if ( pColorTable ) pDlg->SetColorTable( pColorTable ); else { DBG_ERROR( "ColorList not found :-/" ); } } } SfxItemSet aViewAttr(pDrView->GetModel()->GetItemPool()); pDrView->GetAttributes(aViewAttr); rSet.Set(aViewAttr); } } <commit_msg>INTEGRATION: CWS pchfix01 (1.13.212); FILE MERGED 2006/07/12 10:02:37 kaib 1.13.212.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drtxtob2.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2006-07-21 13:48:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------------- #include "scitems.hxx" #include <svx/adjitem.hxx> #include <svx/drawitem.hxx> #include <svx/fontwork.hxx> #include <svx/frmdiritem.hxx> #include <svx/outlobj.hxx> #include <svx/svdocapt.hxx> #include <svx/xtextit.hxx> #ifndef _SVX_WRITINGMODEITEM_HXX #include <svx/writingmodeitem.hxx> #endif #include <sfx2/bindings.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/objsh.hxx> #include <sfx2/request.hxx> #include <sot/formats.hxx> #include <svtools/whiter.hxx> #include "sc.hrc" #include "drtxtob.hxx" #include "viewdata.hxx" #include "drawview.hxx" #include "tabvwsh.hxx" #include "impex.hxx" #include "docsh.hxx" #include "transobj.hxx" #include "drwtrans.hxx" //------------------------------------------------------------------------ USHORT ScGetFontWorkId() { return SvxFontWorkChildWindow::GetChildWindowId(); } BOOL ScDrawTextObjectBar::IsNoteEdit() { ScTabView* pTabView = pViewData->GetView(); SdrView* pSdrView = pTabView->GetSdrView(); SdrObject* pObject = pSdrView->GetTextEditObject(); return ( pObject && pObject->GetLayer() == SC_LAYER_INTERN && pObject->ISA( SdrCaptionObj ) ); } // wenn kein Text editiert wird, Funktionen wie in drawsh void __EXPORT ScDrawTextObjectBar::ExecuteGlobal( SfxRequest &rReq ) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pView = pTabView->GetScDrawView(); USHORT nSlot = rReq.GetSlot(); switch ( nSlot ) { case SID_COPY: pView->DoCopy(); break; case SID_CUT: pView->DoCut(); if (!pTabView->IsDrawSelMode()) pViewData->GetViewShell()->SetDrawShell( FALSE ); break; case SID_PASTE: case FID_PASTE_CONTENTS: case SID_CLIPBOARD_FORMAT_ITEMS: case SID_HYPERLINK_SETLINK: { // cell methods are at cell shell, which is not available if // ScDrawTextObjectBar is active //! move paste etc. to view shell? } break; case SID_SELECTALL: pView->MarkAll(); break; case SID_TEXTDIRECTION_LEFT_TO_RIGHT: case SID_TEXTDIRECTION_TOP_TO_BOTTOM: { SfxItemSet aAttr( pView->GetModel()->GetItemPool(), SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, 0 ); aAttr.Put( SvxWritingModeItem( nSlot == SID_TEXTDIRECTION_LEFT_TO_RIGHT ? com::sun::star::text::WritingMode_LR_TB : com::sun::star::text::WritingMode_TB_RL ) ); pView->SetAttributes( aAttr ); pViewData->GetScDrawView()->InvalidateDrawTextAttrs(); // Bidi slots may be disabled rReq.Done( aAttr ); } break; case SID_ENABLE_HYPHENATION: { SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, SID_ENABLE_HYPHENATION, FALSE); if( pItem ) { SfxItemSet aSet( GetPool(), EE_PARA_HYPHENATE, EE_PARA_HYPHENATE ); BOOL bValue = ( (const SfxBoolItem*) pItem)->GetValue(); aSet.Put( SfxBoolItem( EE_PARA_HYPHENATE, bValue ) ); pView->SetAttributes( aSet ); } rReq.Done(); } break; } } void ScDrawTextObjectBar::GetGlobalClipState( SfxItemSet& rSet ) { // cell methods are at cell shell, which is not available if // ScDrawTextObjectBar is active -> disable everything //! move paste etc. to view shell? SfxWhichIter aIter(rSet); USHORT nWhich = aIter.FirstWhich(); while (nWhich) { rSet.DisableItem( nWhich ); nWhich = aIter.NextWhich(); } } void __EXPORT ScDrawTextObjectBar::ExecuteExtra( SfxRequest &rReq ) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pView = pTabView->GetScDrawView(); USHORT nSlot = rReq.GetSlot(); switch ( nSlot ) { case SID_FONTWORK: { USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); if ( rReq.GetArgs() ) pViewFrm->SetChildWindow( nId, ((const SfxBoolItem&) (rReq.GetArgs()->Get(SID_FONTWORK))). GetValue() ); else pViewFrm->ToggleChildWindow( nId ); pViewFrm->GetBindings().Invalidate( SID_FONTWORK ); rReq.Done(); } break; case SID_ATTR_PARA_LEFT_TO_RIGHT: case SID_ATTR_PARA_RIGHT_TO_LEFT: { SfxItemSet aAttr( pView->GetModel()->GetItemPool(), EE_PARA_WRITINGDIR, EE_PARA_WRITINGDIR, EE_PARA_JUST, EE_PARA_JUST, 0 ); BOOL bLeft = ( nSlot == SID_ATTR_PARA_LEFT_TO_RIGHT ); aAttr.Put( SvxFrameDirectionItem( bLeft ? FRMDIR_HORI_LEFT_TOP : FRMDIR_HORI_RIGHT_TOP, EE_PARA_WRITINGDIR ) ); aAttr.Put( SvxAdjustItem( bLeft ? SVX_ADJUST_LEFT : SVX_ADJUST_RIGHT, EE_PARA_JUST ) ); pView->SetAttributes( aAttr ); pViewData->GetScDrawView()->InvalidateDrawTextAttrs(); rReq.Done(); //! Done(aAttr) ? } break; } } void ScDrawTextObjectBar::ExecFormText(SfxRequest& rReq) { ScTabView* pTabView = pViewData->GetView(); ScDrawView* pDrView = pTabView->GetScDrawView(); const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList(); if ( rMarkList.GetMarkCount() == 1 && rReq.GetArgs() ) { const SfxItemSet& rSet = *rReq.GetArgs(); const SfxPoolItem* pItem; if ( pDrView->IsTextEdit() ) pDrView->ScEndTextEdit(); if ( SFX_ITEM_SET == rSet.GetItemState(XATTR_FORMTXTSTDFORM, TRUE, &pItem) && XFTFORM_NONE != ((const XFormTextStdFormItem*) pItem)->GetValue() ) { USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); SvxFontWorkDialog* pDlg = (SvxFontWorkDialog*) (pViewFrm-> GetChildWindow(nId)->GetWindow()); pDlg->CreateStdFormObj(*pDrView, *pDrView->GetPageViewPvNum(0), rSet, *rMarkList.GetMark(0)->GetObj(), ((const XFormTextStdFormItem*) pItem)-> GetValue()); } else pDrView->SetAttributes(rSet); } } void ScDrawTextObjectBar::GetFormTextState(SfxItemSet& rSet) { const SdrObject* pObj = NULL; SvxFontWorkDialog* pDlg = NULL; ScDrawView* pDrView = pViewData->GetView()->GetScDrawView(); const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList(); USHORT nId = SvxFontWorkChildWindow::GetChildWindowId(); SfxViewFrame* pViewFrm = pViewData->GetViewShell()->GetViewFrame(); if ( pViewFrm->HasChildWindow(nId) ) pDlg = (SvxFontWorkDialog*)(pViewFrm->GetChildWindow(nId)->GetWindow()); if ( rMarkList.GetMarkCount() == 1 ) pObj = rMarkList.GetMark(0)->GetObj(); if ( pObj == NULL || !pObj->ISA(SdrTextObj) || !((SdrTextObj*) pObj)->HasText() ) { if ( pDlg ) pDlg->SetActive(FALSE); rSet.DisableItem(XATTR_FORMTXTSTYLE); rSet.DisableItem(XATTR_FORMTXTADJUST); rSet.DisableItem(XATTR_FORMTXTDISTANCE); rSet.DisableItem(XATTR_FORMTXTSTART); rSet.DisableItem(XATTR_FORMTXTMIRROR); rSet.DisableItem(XATTR_FORMTXTSTDFORM); rSet.DisableItem(XATTR_FORMTXTHIDEFORM); rSet.DisableItem(XATTR_FORMTXTOUTLINE); rSet.DisableItem(XATTR_FORMTXTSHADOW); rSet.DisableItem(XATTR_FORMTXTSHDWCOLOR); rSet.DisableItem(XATTR_FORMTXTSHDWXVAL); rSet.DisableItem(XATTR_FORMTXTSHDWYVAL); } else { if ( pDlg ) { SfxObjectShell* pDocSh = SfxObjectShell::Current(); if ( pDocSh ) { const SfxPoolItem* pItem = pDocSh->GetItem( ITEMID_COLOR_TABLE ); XColorTable* pColorTable = NULL; if ( pItem ) pColorTable = ((SvxColorTableItem*)pItem)->GetColorTable(); pDlg->SetActive(); if ( pColorTable ) pDlg->SetColorTable( pColorTable ); else { DBG_ERROR( "ColorList not found :-/" ); } } } SfxItemSet aViewAttr(pDrView->GetModel()->GetItemPool()); pDrView->GetAttributes(aViewAttr); rSet.Set(aViewAttr); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuconarc.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-11-24 17:26:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #include <svx/svdview.hxx> #include "fuconarc.hxx" #include "sc.hrc" #include "tabvwsh.hxx" // #98185# Create default drawing objects via keyboard #ifndef _SVDOCIRC_HXX #include <svx/svdocirc.hxx> #endif #ifndef _SXCIAITM_HXX #include <svx/sxciaitm.hxx> #endif //------------------------------------------------------------------------ /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuConstArc::FuConstArc( ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq ) : FuConstruct( pViewSh, pWin, pView, pDoc, rReq ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstArc::~FuConstArc() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseButtonDown( const MouseEvent& rMEvt ) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt ); if ( rMEvt.IsLeft() && !pView->IsAction() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pWindow->CaptureMouse(); pView->BegCreateObj( aPnt ); bReturn = TRUE; } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseMove( const MouseEvent& rMEvt ) { return FuConstruct::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseButtonUp( const MouseEvent& rMEvt ) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; if ( pView->IsCreateObj() && rMEvt.IsLeft() ) { // Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj( SDRCREATE_NEXTPOINT ); bReturn = TRUE; } /* else if ( pView->IsCreateObj() && rMEvt.IsRight() ) { // Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj( SDRCREATE_FORCEEND ); bReturn = TRUE; } */ return (FuConstruct::MouseButtonUp(rMEvt) || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstArc::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstArc::Activate() { SdrObjKind aObjKind; switch (aSfxRequest.GetSlot() ) { case SID_DRAW_ARC: aNewPointer = Pointer( POINTER_DRAW_ARC ); aObjKind = OBJ_CARC; break; case SID_DRAW_PIE: aNewPointer = Pointer( POINTER_DRAW_PIE ); aObjKind = OBJ_SECT; break; case SID_DRAW_CIRCLECUT: aNewPointer = Pointer( POINTER_DRAW_CIRCLECUT ); aObjKind = OBJ_CCUT; break; default: aNewPointer = Pointer( POINTER_CROSS ); aObjKind = OBJ_CARC; break; } pView->SetCurrentObj( aObjKind ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); FuDraw::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstArc::Deactivate() { FuDraw::Deactivate(); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) { // case SID_DRAW_ARC: // case SID_DRAW_PIE: // case SID_DRAW_CIRCLECUT: SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if(pObj) { if(pObj->ISA(SdrCircObj)) { Rectangle aRect(rRectangle); if(SID_DRAW_ARC == nID || SID_DRAW_CIRCLECUT == nID) { // force quadratic ImpForceQuadratic(aRect); } pObj->SetLogicRect(aRect); SfxItemSet aAttr(pDrDoc->GetItemPool()); aAttr.Put(SdrCircStartAngleItem(9000)); aAttr.Put(SdrCircEndAngleItem(0)); pObj->SetMergedItemSet(aAttr); } else { DBG_ERROR("Object is NO circle object"); } } return pObj; } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.564); FILE MERGED 2005/09/05 15:04:41 rt 1.5.564.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconarc.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:54:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #include <svx/svdview.hxx> #include "fuconarc.hxx" #include "sc.hrc" #include "tabvwsh.hxx" // #98185# Create default drawing objects via keyboard #ifndef _SVDOCIRC_HXX #include <svx/svdocirc.hxx> #endif #ifndef _SXCIAITM_HXX #include <svx/sxciaitm.hxx> #endif //------------------------------------------------------------------------ /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuConstArc::FuConstArc( ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq ) : FuConstruct( pViewSh, pWin, pView, pDoc, rReq ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstArc::~FuConstArc() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseButtonDown( const MouseEvent& rMEvt ) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt ); if ( rMEvt.IsLeft() && !pView->IsAction() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pWindow->CaptureMouse(); pView->BegCreateObj( aPnt ); bReturn = TRUE; } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseMove( const MouseEvent& rMEvt ) { return FuConstruct::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstArc::MouseButtonUp( const MouseEvent& rMEvt ) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; if ( pView->IsCreateObj() && rMEvt.IsLeft() ) { // Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj( SDRCREATE_NEXTPOINT ); bReturn = TRUE; } /* else if ( pView->IsCreateObj() && rMEvt.IsRight() ) { // Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj( SDRCREATE_FORCEEND ); bReturn = TRUE; } */ return (FuConstruct::MouseButtonUp(rMEvt) || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstArc::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstArc::Activate() { SdrObjKind aObjKind; switch (aSfxRequest.GetSlot() ) { case SID_DRAW_ARC: aNewPointer = Pointer( POINTER_DRAW_ARC ); aObjKind = OBJ_CARC; break; case SID_DRAW_PIE: aNewPointer = Pointer( POINTER_DRAW_PIE ); aObjKind = OBJ_SECT; break; case SID_DRAW_CIRCLECUT: aNewPointer = Pointer( POINTER_DRAW_CIRCLECUT ); aObjKind = OBJ_CCUT; break; default: aNewPointer = Pointer( POINTER_CROSS ); aObjKind = OBJ_CARC; break; } pView->SetCurrentObj( aObjKind ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); FuDraw::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstArc::Deactivate() { FuDraw::Deactivate(); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) { // case SID_DRAW_ARC: // case SID_DRAW_PIE: // case SID_DRAW_CIRCLECUT: SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if(pObj) { if(pObj->ISA(SdrCircObj)) { Rectangle aRect(rRectangle); if(SID_DRAW_ARC == nID || SID_DRAW_CIRCLECUT == nID) { // force quadratic ImpForceQuadratic(aRect); } pObj->SetLogicRect(aRect); SfxItemSet aAttr(pDrDoc->GetItemPool()); aAttr.Put(SdrCircStartAngleItem(9000)); aAttr.Put(SdrCircEndAngleItem(0)); pObj->SetMergedItemSet(aAttr); } else { DBG_ERROR("Object is NO circle object"); } } return pObj; } <|endoftext|>
<commit_before>#include "dlg_status.h" #include "control.h" #include "hardware.h" #include <QtGui> #include <QApplication> StatusDlg::StatusDlg(QWidget *parent, QWidget *controlDlg) : QWidget(parent) , m_controlDlg(controlDlg) { ui.setupUi(this); Qt::WindowFlags flags = windowFlags(); flags |= Qt::FramelessWindowHint; setWindowFlags(flags); } void StatusDlg::on_pbSetNotte_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::on_pbSetGiorno_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::on_pbSetSoffitta_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::updateStatoRisc() { /* if (ui.pbRiscCaldaia->isChecked()) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(255, 64, 64))); ui.pbRiscCaldaia->setText("Caldaia ON"); } else if (control().xCaldaiaInUso) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscCaldaia->setText("Caldaia auto ON"); } else { ui.pbRiscCaldaia->setPalette(QApplication::palette()); ui.pbRiscCaldaia->setText("Caldaia OFF"); } if (ui.pbRiscPompaCalore->isChecked()) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(64, 255, 64))); ui.pbRiscPompaCalore->setText("Pompa di calore ON"); } else if (control().xPompaCaloreInUso) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscPompaCalore->setText("Pompa di calore auto ON"); } else { ui.pbRiscPompaCalore->setPalette(QApplication::palette()); ui.pbRiscPompaCalore->setText("Pompa di calore OFF"); } */ } static void setLabelActive(QLabel *label, QColor color) { QPalette palette = label->palette(); palette.setColor(label->backgroundRole(), color); label->setPalette(palette); label->setFrameShape(QFrame::Box); label->setEnabled(true); } static void setLabelInactive(QLabel *label) { label->setEnabled(false); label->setPalette(QApplication::palette()); label->setFrameShape(QFrame::NoFrame); } void StatusDlg::updateScreen() { char buf[256]; ui.tlData->setText(QDate::currentDate().toString("dd/MM/yyyy")); ui.tlOra->setText(QTime::currentTime().toString("h:mm")); QMutexLocker lock(&control().mFields); sprintf(buf, "%.1f", control().wTemperaturaACS/10.0); ui.tlTempAcquaTop->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaBoiler/10.0); ui.tlTempAcquaBot->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaAccumulo/10.0); ui.tlTempAccumulo->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaPannelli/10.0); ui.tlTempPannelli->setText(buf); sprintf(buf, "%.1f", control().wTempSoffitta/10.0); ui.tlTempSoffitta->setText(buf); sprintf(buf, "%.1f", control().wUmidSoffitta/10.0); ui.tlUmidSoffitta->setText(buf); sprintf(buf, "%i", control().wPotProdotta); ui.tlPotProdotta->setText(buf); sprintf(buf, "%i", control().wPotConsumata); ui.tlPotConsumata->setText(buf); sprintf(buf, "%.3f Wh oggi", control().wEnergProdotta/1000.0); ui.tlEnergiaProdotta->setText(buf); sprintf(buf, "%.3f Wh oggi", control().wEnergConsumata/1000.0); ui.tlEnergiaConsumata->setText(buf); if (control().tTempoAttivo.hour()) { sprintf(buf, "%ih%02i in attivo", control().tTempoAttivo.hour(), control().tTempoAttivo.minute()); ui.tlBilAttivo->setText(buf); } else { sprintf(buf, "%imin in attivo", control().tTempoAttivo.minute()); ui.tlBilAttivo->setText(buf); } sprintf(buf, "%.3f effettivi", control().wEnergPassivo/1000.0); ui.tlEnergPassivo->setText(buf); if (control().xCaldaiaInUso) { setLabelActive(ui.tlStatoCaldaia, QColor(255, 64, 64)); } else { setLabelInactive(ui.tlStatoCaldaia); } if (control().xPompaCaloreInUso) { setLabelActive(ui.tlStatoPompaCalore, QColor(64, 255, 64)); } else { setLabelInactive(ui.tlStatoPompaCalore); } if (control().xResistenzeInUso) { setLabelActive(ui.tlStatoResistenze, QColor(255, 64, 64)); } else { setLabelInactive(ui.tlStatoResistenze); } if (control().xFanCoil) { setLabelActive(ui.tlStatoVentilatore, QColor(128, 128, 255)); } else { setLabelInactive(ui.tlStatoVentilatore); } } <commit_msg>dlg_status: mostra stato riscaldamento<commit_after>#include "dlg_status.h" #include "control.h" #include "hardware.h" #include <QtGui> #include <QApplication> StatusDlg::StatusDlg(QWidget *parent, QWidget *controlDlg) : QWidget(parent) , m_controlDlg(controlDlg) { ui.setupUi(this); Qt::WindowFlags flags = windowFlags(); flags |= Qt::FramelessWindowHint; setWindowFlags(flags); } void StatusDlg::on_pbSetNotte_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::on_pbSetGiorno_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::on_pbSetSoffitta_toggled(bool checked) { m_controlDlg->show(); } void StatusDlg::updateStatoRisc() { /* if (ui.pbRiscCaldaia->isChecked()) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(255, 64, 64))); ui.pbRiscCaldaia->setText("Caldaia ON"); } else if (control().xCaldaiaInUso) { ui.pbRiscCaldaia->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscCaldaia->setText("Caldaia auto ON"); } else { ui.pbRiscCaldaia->setPalette(QApplication::palette()); ui.pbRiscCaldaia->setText("Caldaia OFF"); } if (ui.pbRiscPompaCalore->isChecked()) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(64, 255, 64))); ui.pbRiscPompaCalore->setText("Pompa di calore ON"); } else if (control().xPompaCaloreInUso) { ui.pbRiscPompaCalore->setPalette(QPalette(QColor(220,220,128))); ui.pbRiscPompaCalore->setText("Pompa di calore auto ON"); } else { ui.pbRiscPompaCalore->setPalette(QApplication::palette()); ui.pbRiscPompaCalore->setText("Pompa di calore OFF"); } */ } static void setLabelActive(QLabel *label, QColor color) { QPalette palette = label->palette(); palette.setColor(label->backgroundRole(), color); label->setPalette(palette); label->setFrameShape(QFrame::Box); label->setEnabled(true); } static void setLabelInactive(QLabel *label) { label->setEnabled(false); label->setPalette(QApplication::palette()); label->setFrameShape(QFrame::NoFrame); } void StatusDlg::updateScreen() { char buf[256]; ui.tlData->setText(QDate::currentDate().toString("dd/MM/yyyy")); ui.tlOra->setText(QTime::currentTime().toString("h:mm")); QMutexLocker lock(&control().mFields); sprintf(buf, "%.1f", control().wTemperaturaACS/10.0); ui.tlTempAcquaTop->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaBoiler/10.0); ui.tlTempAcquaBot->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaAccumulo/10.0); ui.tlTempAccumulo->setText(buf); sprintf(buf, "%.1f", control().wTemperaturaPannelli/10.0); ui.tlTempPannelli->setText(buf); sprintf(buf, "%.1f", control().wTempSoffitta/10.0); ui.tlTempSoffitta->setText(buf); sprintf(buf, "%.1f", control().wUmidSoffitta/10.0); ui.tlUmidSoffitta->setText(buf); sprintf(buf, "%i", control().wPotProdotta); ui.tlPotProdotta->setText(buf); sprintf(buf, "%i", control().wPotConsumata); ui.tlPotConsumata->setText(buf); sprintf(buf, "%.3f Wh oggi", control().wEnergProdotta/1000.0); ui.tlEnergiaProdotta->setText(buf); sprintf(buf, "%.3f Wh oggi", control().wEnergConsumata/1000.0); ui.tlEnergiaConsumata->setText(buf); if (control().tTempoAttivo.hour()) { sprintf(buf, "%ih%02i in attivo", control().tTempoAttivo.hour(), control().tTempoAttivo.minute()); ui.tlBilAttivo->setText(buf); } else { sprintf(buf, "%imin in attivo", control().tTempoAttivo.minute()); ui.tlBilAttivo->setText(buf); } sprintf(buf, "%.3f effettivi", control().wEnergPassivo/1000.0); ui.tlEnergPassivo->setText(buf); if (control().xCaldaiaInUso) { setLabelActive(ui.tlStatoCaldaia, QColor(255, 64, 64)); } else { setLabelInactive(ui.tlStatoCaldaia); } if (control().xPompaCaloreInUso) { setLabelActive(ui.tlStatoPompaCalore, QColor(64, 255, 64)); } else { setLabelInactive(ui.tlStatoPompaCalore); } if (control().xResistenzeInUso) { setLabelActive(ui.tlStatoResistenze, QColor(255, 64, 64)); } else { setLabelInactive(ui.tlStatoResistenze); } if (control().xFanCoil) { setLabelActive(ui.tlStatoVentilatore, QColor(128, 128, 255)); } else { setLabelInactive(ui.tlStatoVentilatore); } if (control().xRiscaldaNotte || control().xRiscaldaGiorno || control().xRiscaldaSoffitta) { setLabelActive(ui.tlStatoRadiatori, QColor(255, 128, 128)); } else { setLabelInactive(ui.tlStatoRadiatori); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2020, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #include <stdarg.h> #include <sys/types.h> #include <unistd.h> #include <cuda.h> #include <check.h> #include <map> #include <gdrapi.h> /** * Memory barrier */ #if defined(GDRAPI_X86) #define MB() asm volatile("mfence":::"memory") #elif defined(GDRAPI_POWER) #define MB() asm volatile("sync":::"memory") #else #define MB() asm volatile("":::"memory") #endif /** * Clock used for timing */ //#define MYCLOCK CLOCK_REALTIME //#define MYCLOCK CLOCK_RAW_MONOTONIC #define MYCLOCK CLOCK_MONOTONIC #define EXIT_WAIVED 2 #define BEGIN_GDRCOPY_TEST(__testname) \ START_TEST(__testname) { \ testname = #__testname; \ print_dbg("&&&& RUNNING " # __testname "\n"); \ fflush(stdout); \ fflush(stderr); \ pid_t __pid = fork(); \ if (__pid < 0) { \ print_dbg("Cannot fork\n"); \ print_dbg("&&&& FAILED " # __testname "\n"); \ exit(EXIT_FAILURE); \ } \ if (__pid == 0) { #define END_GDRCOPY_TEST } \ if (__pid) { \ int __child_exit_status = -EINVAL; \ if (waitpid(__pid, &__child_exit_status, 0) == -1) { \ print_dbg("waitpid returned an error\n"); \ print_dbg("&&&& FAILED %s\n", gdrcopy::test::testname); \ exit(EXIT_FAILURE); \ } \ if (__child_exit_status == EXIT_SUCCESS) \ print_dbg("&&&& PASSED %s\n", gdrcopy::test::testname); \ else if (__child_exit_status == EXIT_WAIVED) \ print_dbg("&&&& WAIVED %s\n", gdrcopy::test::testname); \ else { \ print_dbg("&&&& FAILED %s\n", gdrcopy::test::testname); \ ck_abort(); \ } \ } \ } END_TEST #define ASSERT(x) \ do \ { \ if (!(x)) \ { \ fprintf(stderr, "Assertion \"%s\" failed at %s:%d\n", #x, __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } while (0) #define ASSERTDRV(stmt) \ do \ { \ CUresult result = (stmt); \ if (result != CUDA_SUCCESS) { \ const char *_err_name; \ cuGetErrorName(result, &_err_name); \ fprintf(stderr, "CUDA error: %s\n", _err_name); \ } \ ASSERT(CUDA_SUCCESS == result); \ } while (0) #define ASSERT_EQ(P, V) ASSERT((P) == (V)) #define CHECK_EQ(P, V) ASSERT((P) == (V)) #define ASSERT_NEQ(P, V) ASSERT(!((P) == (V))) #define BREAK_IF_NEQ(P, V) if((P) != (V)) break #define BEGIN_CHECK do #define END_CHECK while(0) #define GDR_OPEN_SAFE() ({ \ gdr_t _g = gdr_open(); \ if (!_g) { \ fprintf(stderr, "gdr_open error: Is gdrdrv driver installed and loaded?\n");\ exit(EXIT_FAILURE); \ } \ _g; \ }) namespace gdrcopy { namespace test { extern std::map<CUdeviceptr, CUdeviceptr> _allocations; static inline CUresult gpuMemAlloc(CUdeviceptr *pptr, size_t psize, bool align_to_gpu_page = true, bool set_sync_memops = true) { CUresult ret = CUDA_SUCCESS; CUdeviceptr ptr; size_t size; if (align_to_gpu_page) size = psize + GPU_PAGE_SIZE - 1; else size = psize; ret = cuMemAlloc(&ptr, size); if (ret != CUDA_SUCCESS) return ret; if (set_sync_memops) { unsigned int flag = 1; ret = cuPointerSetAttribute(&flag, CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr); if (ret != CUDA_SUCCESS) { cuMemFree(ptr); return ret; } } if (align_to_gpu_page) *pptr = (ptr + GPU_PAGE_SIZE - 1) & GPU_PAGE_MASK; else *pptr = ptr; // Record the actual pointer for doing gpuMemFree later. _allocations[*pptr] = ptr; return CUDA_SUCCESS; } static inline CUresult gpuMemFree(CUdeviceptr pptr) { CUresult ret = CUDA_SUCCESS; CUdeviceptr ptr; if (_allocations.count(pptr) > 0) { ptr = _allocations[pptr]; ret = cuMemFree(ptr); if (ret == CUDA_SUCCESS) _allocations.erase(ptr); return ret; } else return CUDA_ERROR_INVALID_VALUE; } extern bool print_dbg_msg; void print_dbg(const char* fmt, ...); extern const char *testname; static inline bool operator==(const gdr_mh_t &a, const gdr_mh_t &b) { return a.h == b.h; } static const gdr_mh_t null_mh = {0}; int compare_buf(uint32_t *ref_buf, uint32_t *buf, size_t size); void init_hbuf_walking_bit(uint32_t *h_buf, size_t size); void init_hbuf_linear_ramp(uint32_t *h_buf, size_t size); } } <commit_msg>Replaced exit(EXIT_FAILURE) with ck_abort in BEGIN/END_GDRCOPY_TEST<commit_after>/* * Copyright (c) 2014-2020, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #include <stdarg.h> #include <sys/types.h> #include <unistd.h> #include <cuda.h> #include <check.h> #include <map> #include <gdrapi.h> /** * Memory barrier */ #if defined(GDRAPI_X86) #define MB() asm volatile("mfence":::"memory") #elif defined(GDRAPI_POWER) #define MB() asm volatile("sync":::"memory") #else #define MB() asm volatile("":::"memory") #endif /** * Clock used for timing */ //#define MYCLOCK CLOCK_REALTIME //#define MYCLOCK CLOCK_RAW_MONOTONIC #define MYCLOCK CLOCK_MONOTONIC #define EXIT_WAIVED 2 #define BEGIN_GDRCOPY_TEST(__testname) \ START_TEST(__testname) { \ testname = #__testname; \ print_dbg("&&&& RUNNING " # __testname "\n"); \ fflush(stdout); \ fflush(stderr); \ pid_t __pid = fork(); \ if (__pid < 0) { \ print_dbg("Cannot fork\n"); \ print_dbg("&&&& FAILED " # __testname "\n"); \ ck_abort(); \ } \ if (__pid == 0) { #define END_GDRCOPY_TEST } \ if (__pid > 0) { \ int __child_exit_status = -EINVAL; \ if (waitpid(__pid, &__child_exit_status, 0) == -1) { \ print_dbg("waitpid returned an error\n"); \ print_dbg("&&&& FAILED %s\n", gdrcopy::test::testname); \ ck_abort(); \ } \ if (__child_exit_status == EXIT_SUCCESS) \ print_dbg("&&&& PASSED %s\n", gdrcopy::test::testname); \ else if (__child_exit_status == EXIT_WAIVED) \ print_dbg("&&&& WAIVED %s\n", gdrcopy::test::testname); \ else { \ print_dbg("&&&& FAILED %s\n", gdrcopy::test::testname); \ ck_abort(); \ } \ } \ } END_TEST #define ASSERT(x) \ do \ { \ if (!(x)) \ { \ fprintf(stderr, "Assertion \"%s\" failed at %s:%d\n", #x, __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } while (0) #define ASSERTDRV(stmt) \ do \ { \ CUresult result = (stmt); \ if (result != CUDA_SUCCESS) { \ const char *_err_name; \ cuGetErrorName(result, &_err_name); \ fprintf(stderr, "CUDA error: %s\n", _err_name); \ } \ ASSERT(CUDA_SUCCESS == result); \ } while (0) #define ASSERT_EQ(P, V) ASSERT((P) == (V)) #define CHECK_EQ(P, V) ASSERT((P) == (V)) #define ASSERT_NEQ(P, V) ASSERT(!((P) == (V))) #define BREAK_IF_NEQ(P, V) if((P) != (V)) break #define BEGIN_CHECK do #define END_CHECK while(0) #define GDR_OPEN_SAFE() ({ \ gdr_t _g = gdr_open(); \ if (!_g) { \ fprintf(stderr, "gdr_open error: Is gdrdrv driver installed and loaded?\n");\ exit(EXIT_FAILURE); \ } \ _g; \ }) namespace gdrcopy { namespace test { extern std::map<CUdeviceptr, CUdeviceptr> _allocations; static inline CUresult gpuMemAlloc(CUdeviceptr *pptr, size_t psize, bool align_to_gpu_page = true, bool set_sync_memops = true) { CUresult ret = CUDA_SUCCESS; CUdeviceptr ptr; size_t size; if (align_to_gpu_page) size = psize + GPU_PAGE_SIZE - 1; else size = psize; ret = cuMemAlloc(&ptr, size); if (ret != CUDA_SUCCESS) return ret; if (set_sync_memops) { unsigned int flag = 1; ret = cuPointerSetAttribute(&flag, CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr); if (ret != CUDA_SUCCESS) { cuMemFree(ptr); return ret; } } if (align_to_gpu_page) *pptr = (ptr + GPU_PAGE_SIZE - 1) & GPU_PAGE_MASK; else *pptr = ptr; // Record the actual pointer for doing gpuMemFree later. _allocations[*pptr] = ptr; return CUDA_SUCCESS; } static inline CUresult gpuMemFree(CUdeviceptr pptr) { CUresult ret = CUDA_SUCCESS; CUdeviceptr ptr; if (_allocations.count(pptr) > 0) { ptr = _allocations[pptr]; ret = cuMemFree(ptr); if (ret == CUDA_SUCCESS) _allocations.erase(ptr); return ret; } else return CUDA_ERROR_INVALID_VALUE; } extern bool print_dbg_msg; void print_dbg(const char* fmt, ...); extern const char *testname; static inline bool operator==(const gdr_mh_t &a, const gdr_mh_t &b) { return a.h == b.h; } static const gdr_mh_t null_mh = {0}; int compare_buf(uint32_t *ref_buf, uint32_t *buf, size_t size); void init_hbuf_walking_bit(uint32_t *h_buf, size_t size); void init_hbuf_linear_ramp(uint32_t *h_buf, size_t size); } } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; vector <unsigned> IT(vector <unsigned>& x) { int i; // cout << x[0] <<endl; /* for (i=0;i < x[0].size();i++){ cout << "AAAA"<<" "<<x[0][i]<<endl; } */ x[0]=x[0]+1; x[1]=x[1]+2; return x; } int main(int argc, char **argv) { double prandtl; double rayleigh; unsigned i; if (argc >= 2) prandtl = strtod (argv[1],NULL); if (argc >= 3) rayleigh = strtod (argv[2],NULL); std::vector <unsigned> x[2]; x[0].reserve(3); x[1].reserve(4); x[0].resize(2); x[1].resize(2); for (i=0;i<x[0].size();i++){ x[0][i]=i*2; } x[0].push_back(10); x[0].push_back(11); for (i=0;i<x[0].size();i++){ std::cout << x[0][i] << std::endl; } std::cout <<"111" << std::endl; std::vector <unsigned> y(10); //y[0] = IT(x); cout <<"BBBBB" <<y.size()<<endl; y=IT(x[0]); cout <<"AAAAA" <<y.size()<<endl; for (i=0; i<y.size(); i++){ std::cout << y[i]<< std::endl; } char *stdOutfile = new char [100] ; char *infile = new char [100]; sprintf(stdOutfile, "%s is the most inportant thing","2"); sprintf(infile, "%s is the number %d","2",2); cout << stdOutfile <<" "<< infile << endl; //stdOutfile =&""; printf(stdOutfile, "%s is the most inportant thing","3"); cout << stdOutfile <<" "<< infile << endl; cout << "prandtl=" << prandtl << endl; cout << "rayleigh=" << rayleigh << endl; return 0; } <commit_msg>practice<commit_after>// pointer to functions #include <iostream> using namespace std; double addition (double a, double b) {return (a+b); } double subtraction (double a, double b) {return (a-b);} double operation (double a , double b, double (*func) (double, double)) { double g; g = (*func)(a,b); return g; } int main() { double (*mypoint) (double, double), n, m; mypoint = &subtraction; n = operation(5.0, 10.0, addition); m = operation(19., n, mypoint); cout << n <<" "<< m <<endl; return 0; } /* int addition (int a, int b) { return (a+b); } int subtraction(int a, int b) {return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return (g); } int main () { int m, n; int (*minus)(int, int) = subtraction; m = operation (7, 5, addition); n = operation (20, m, minus); cout <<n; return 0; } // int main(int argc, char **argv) // { // double prandtl; // double rayleigh; // unsigned i; // if (argc >= 2) prandtl = strtod (argv[1],NULL); // if (argc >= 3) rayleigh = strtod (argv[2],NULL); // // std::vector <unsigned> x[2]; // x[0].reserve(3); // x[1].reserve(4); // x[0].resize(2); // x[1].resize(2); // for (i=0;i<x[0].size();i++){ // x[0][i]=i*2; // } // x[0].push_back(10); // x[0].push_back(11); // for (i=0;i<x[0].size();i++){ // std::cout << x[0][i] << std::endl; // } // std::cout <<"111" << std::endl; // // std::vector <unsigned> y(10); // //y[0] = IT(x); // cout <<"BBBBB" <<y.size()<<endl; // y=IT(x[0]); // cout <<"AAAAA" <<y.size()<<endl; // for (i=0; i<y.size(); i++){ // std::cout << y[i]<< std::endl; // } // // char *stdOutfile = new char [100] ; // char *infile = new char [100]; // // sprintf(stdOutfile, "%s is the most inportant thing","2"); // sprintf(infile, "%s is the number %d","2",2); // cout << stdOutfile <<" "<< infile << endl; // // //stdOutfile =&""; // printf(stdOutfile, "%s is the most inportant thing","3"); // cout << stdOutfile <<" "<< infile << endl; // // // cout << "prandtl=" << prandtl << endl; // cout << "rayleigh=" << rayleigh << endl; // return 0; // }*/ <|endoftext|>
<commit_before>#include "stdafx.h" #include "SmartViewTestData.h" #include "resource.h" namespace SmartViewTestData { struct SmartViewTestResource { __ParsingTypeEnum structType; bool parseAll; DWORD hex; DWORD expected; }; // Resource files saved in unicode have a byte order mark of 0xfeff // We load these in and strip the BOM. // Otherwise we load as ansi and convert to unicode wstring loadfile(HMODULE handle, int name) { auto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE)); auto rcData = ::LoadResource(handle, rc); auto cb = ::SizeofResource(handle, rc); auto bytes = ::LockResource(rcData); auto data = static_cast<const BYTE*>(bytes); if (cb >= 2 && data[0] == 0xfe && data[1] == 0xff) { // Skip the byte order mark auto wstr = static_cast<const wchar_t*>(bytes); auto cch = cb / sizeof(wchar_t); return std::wstring(wstr + 1, cch - 1); } auto str = std::string(static_cast<const char*>(bytes), cb); return stringTowstring(str); } vector<SmartViewTestData> getTestData(HMODULE handle) { const bool parseAll = false; auto resources = { SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT }, SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }, }; vector<SmartViewTestData> testData; for (auto resource : resources) { testData.push_back(SmartViewTestData { resource.structType, resource.parseAll, format(L"%d/%d", resource.hex, resource.expected), loadfile(handle, resource.hex), loadfile(handle, resource.expected) }); } return testData; } }<commit_msg>Factor out loadTestData<commit_after>#include "stdafx.h" #include "SmartViewTestData.h" #include "resource.h" namespace SmartViewTestData { struct SmartViewTestResource { __ParsingTypeEnum structType; bool parseAll; DWORD hex; DWORD expected; }; // Resource files saved in unicode have a byte order mark of 0xfeff // We load these in and strip the BOM. // Otherwise we load as ansi and convert to unicode wstring loadfile(HMODULE handle, int name) { auto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE)); auto rcData = ::LoadResource(handle, rc); auto cb = ::SizeofResource(handle, rc); auto bytes = ::LockResource(rcData); auto data = static_cast<const BYTE*>(bytes); if (cb >= 2 && data[0] == 0xfe && data[1] == 0xff) { // Skip the byte order mark auto wstr = static_cast<const wchar_t*>(bytes); auto cch = cb / sizeof(wchar_t); return std::wstring(wstr + 1, cch - 1); } auto str = std::string(static_cast<const char*>(bytes), cb); return stringTowstring(str); } vector<SmartViewTestData> loadTestData(HMODULE handle, std::initializer_list<SmartViewTestResource> resources) { vector<SmartViewTestData> testData; for (auto resource : resources) { testData.push_back(SmartViewTestData { resource.structType, resource.parseAll, format(L"%d/%d", resource.hex, resource.expected), loadfile(handle, resource.hex), loadfile(handle, resource.expected) }); } return testData; } vector<SmartViewTestData> getTestData(HMODULE handle) { const bool parseAll = false; auto resources = { SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT }, SmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT }, SmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT }, SmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT }, SmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }, }; return loadTestData(handle, resources); } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: image.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:12:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #pragma hdrstop #include <svtools/sbx.hxx> #include "sb.hxx" #include <string.h> // memset() etc #include "image.hxx" #include "filefmt.hxx" #include "segmentc.hxx" #pragma SW_SEGMENT_CLASS( SBASIC, SBASIC_CODE ) SbiImage::SbiImage() { rTypes = new SbxArray; pStringOff = NULL; pStrings = NULL; pCode = NULL; nFlags = nStrings = nStringSize= nCodeSize = nDimBase = 0; bInit = bError = FALSE; eCharSet = gsl_getSystemTextEncoding(); } SbiImage::~SbiImage() { Clear(); } void SbiImage::Clear() { delete pStringOff; delete pStrings; delete pCode; pStringOff = NULL; pStrings = NULL; pCode = NULL; nFlags = nStrings = nStringSize= nCodeSize = 0; eCharSet = gsl_getSystemTextEncoding(); nDimBase = 0; bError = FALSE; } /************************************************************************** * * Service-Routinen fuer das Laden und Speichern * **************************************************************************/ BOOL SbiGood( SvStream& r ) { return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK ); } // Oeffnen eines Records ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem ) { ULONG nPos = r.Tell(); r << nSignature << (INT32) 0 << nElem; return nPos; } // Schliessen eines Records void SbiCloseRecord( SvStream& r, ULONG nOff ) { ULONG nPos = r.Tell(); r.Seek( nOff + 2 ); r << (INT32) ( nPos - nOff - 8 ); r.Seek( nPos ); } /************************************************************************** * * Laden und Speichern * **************************************************************************/ // Falls die Versionsnummer nicht passt, werden die binaeren Teile // nicht geladen, wohl aber Source, Kommentar und Name. BOOL SbiImage::Load( SvStream& r ) { UINT16 nSign, nCount; UINT32 nLen, nOff; Clear(); ULONG nStart = r.Tell(); // Master-Record einlesen r >> nSign >> nLen >> nCount; ULONG nLast = r.Tell() + nLen; UINT32 nVersion = 0; // Versionsnummer UINT32 nCharSet; // System-Zeichensatz UINT32 lDimBase; UINT16 nReserved1; UINT32 nReserved2; UINT32 nReserved3; BOOL bBadVer = FALSE; if( nSign == B_MODULE ) { r >> nVersion >> nCharSet >> lDimBase >> nFlags >> nReserved1 >> nReserved2 >> nReserved3; eCharSet = (CharSet) nCharSet; bBadVer = BOOL( nVersion != B_CURVERSION ); nDimBase = (USHORT) lDimBase; } ULONG nNext; while( ( nNext = r.Tell() ) < nLast ) { short i; r >> nSign >> nLen >> nCount; nNext += nLen + 8; if( r.GetError() == SVSTREAM_OK ) switch( nSign ) { case B_NAME: r.ReadByteString( aName, eCharSet ); //r >> aName; break; case B_COMMENT: r.ReadByteString( aComment, eCharSet ); //r >> aComment; break; case B_SOURCE: r.ReadByteString( aSource, eCharSet ); //r >> aSource; break; case B_PCODE: if( bBadVer ) break; pCode = new char[ nLen ]; nCodeSize = (USHORT) nLen; r.Read( pCode, nCodeSize ); break; case B_PUBLICS: case B_POOLDIR: case B_SYMPOOL: case B_LINERANGES: break; case B_STRINGPOOL: if( bBadVer ) break; MakeStrings( nCount ); for( i = 0; i < nStrings && SbiGood( r ); i++ ) { r >> nOff; pStringOff[ i ] = (USHORT) nOff; } r >> nLen; if( SbiGood( r ) ) { delete pStrings; pStrings = new sal_Unicode[ nLen ]; nStringSize = (USHORT) nLen; char* pByteStrings = new char[ nLen ]; r.Read( pByteStrings, nStringSize ); for( short i = 0; i < nStrings; i++ ) { USHORT nOff = pStringOff[ i ]; String aStr( pByteStrings + nOff, eCharSet ); memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) ); } delete pByteStrings; } break; case B_MODEND: goto done; default: break; } else break; r.Seek( nNext ); } done: r.Seek( nLast ); //if( eCharSet != ::GetSystemCharSet() ) //ConvertStrings(); if( !SbiGood( r ) ) bError = TRUE; return BOOL( !bError ); } BOOL SbiImage::Save( SvStream& r ) { // Erst mal der Header: ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 ); ULONG nPos; r << (INT32) B_CURVERSION << (INT32) eCharSet << (INT32) nDimBase << (INT16) nFlags << (INT16) 0 << (INT32) 0 << (INT32) 0; // Name? if( aName.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_NAME, 1 ); r.WriteByteString( aName, eCharSet ); //r << aName; SbiCloseRecord( r, nPos ); } // Kommentar? if( aComment.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_COMMENT, 1 ); r.WriteByteString( aComment, eCharSet ); //r << aComment; SbiCloseRecord( r, nPos ); } // Source? if( aSource.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_SOURCE, 1 ); r.WriteByteString( aSource, eCharSet ); //r << aSource; SbiCloseRecord( r, nPos ); } // Binaere Daten? if( pCode && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_PCODE, 1 ); r.Write( pCode, nCodeSize ); SbiCloseRecord( r, nPos ); } // String-Pool? if( nStrings ) { nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings ); // Fuer jeden String: // UINT32 Offset des Strings im Stringblock for( short i = 0; i < nStrings && SbiGood( r ); i++ ) r << (UINT32) pStringOff[ i ]; // Danach der String-Block char* pByteStrings = new char[ nStringSize ]; for( i = 0; i < nStrings; i++ ) { USHORT nOff = pStringOff[ i ]; ByteString aStr( pStrings + nOff, eCharSet ); memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) ); } r << (UINT32) nStringSize; r.Write( pByteStrings, nStringSize ); delete pByteStrings; SbiCloseRecord( r, nPos ); } // Und die Gesamtlaenge setzen SbiCloseRecord( r, nStart ); if( !SbiGood( r ) ) bError = TRUE; return BOOL( !bError ); } /************************************************************************** * * Routinen, die auch vom Compiler gerufen werden * **************************************************************************/ void SbiImage::MakeStrings( short nSize ) { nStrings = nStringIdx = nStringOff = 0; nStringSize = 1024; pStrings = new sal_Unicode[ nStringSize ]; pStringOff = new UINT16[ nSize ]; if( pStrings && pStringOff ) { nStrings = nSize; memset( pStringOff, 0, nSize * sizeof( UINT16 ) ); memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) ); } else bError = TRUE; } // Hinzufuegen eines Strings an den StringPool. Der String-Puffer // waechst dynamisch in 1K-Schritten // AB 12.5.2000 Aus Zeitgruenden vorerst weiter auf char-Basis // TODO: Auch hier auf Unicode umstellen, d.h. sal_Unicode-Array void SbiImage::AddString( const String& r ) { if( nStringIdx >= nStrings ) bError = TRUE; if( !bError ) { UINT16 len = r.Len() + 1; long needed = (long) nStringOff + len; if( needed > 0xFF00L ) bError = TRUE; // out of mem! else if( (USHORT) needed > nStringSize ) { sal_Unicode* p = new sal_Unicode[ nStringSize + 1024 ]; if( p ) { memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) ); delete pStrings; pStrings = p; nStringSize += 1024; } else bError = TRUE; } if( !bError ) { pStringOff[ nStringIdx++ ] = nStringOff; //ByteString aByteStr( r, eCharSet ); memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) ); nStringOff += len; // war das der letzte String? Dann die Groesse // des Puffers aktualisieren if( nStringIdx >= nStrings ) nStringSize = nStringOff; } } } // Codeblock hinzufuegen // Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt // und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers // im Big Endian-Format, kann also direkt gelesen/geschrieben werden. void SbiImage::AddCode( char* p, USHORT s ) { pCode = p; nCodeSize = s; } void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen { SbxObject *pCopyObject = new SbxObject(*pObject); rTypes->Insert (pCopyObject,rTypes->Count()); } /************************************************************************** * * Zugriffe auf das Image * **************************************************************************/ // IDs zaehlen ab 1!! String SbiImage::GetString( short nId ) const { if( nId && nId <= nStrings ) { USHORT nOff = pStringOff[ --nId ]; String aStr( pStrings + nOff ); return aStr; } return String(); } const SbxObject* SbiImage::FindType (String aTypeName) const { return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT); } <commit_msg>#90481# Use GetSOLoad/StoreTextEncoding()<commit_after>/************************************************************************* * * $RCSfile: image.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ab $ $Date: 2001-08-07 11:20:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _STREAM_HXX //autogen #include <tools/stream.hxx> #endif #include <tools/tenccvt.hxx> #pragma hdrstop #include <svtools/sbx.hxx> #include "sb.hxx" #include <string.h> // memset() etc #include "image.hxx" #include "filefmt.hxx" #include "segmentc.hxx" #pragma SW_SEGMENT_CLASS( SBASIC, SBASIC_CODE ) SbiImage::SbiImage() { rTypes = new SbxArray; pStringOff = NULL; pStrings = NULL; pCode = NULL; nFlags = nStrings = nStringSize= nCodeSize = nDimBase = 0; bInit = bError = FALSE; eCharSet = gsl_getSystemTextEncoding(); } SbiImage::~SbiImage() { Clear(); } void SbiImage::Clear() { delete pStringOff; delete pStrings; delete pCode; pStringOff = NULL; pStrings = NULL; pCode = NULL; nFlags = nStrings = nStringSize= nCodeSize = 0; eCharSet = gsl_getSystemTextEncoding(); nDimBase = 0; bError = FALSE; } /************************************************************************** * * Service-Routinen fuer das Laden und Speichern * **************************************************************************/ BOOL SbiGood( SvStream& r ) { return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK ); } // Oeffnen eines Records ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem ) { ULONG nPos = r.Tell(); r << nSignature << (INT32) 0 << nElem; return nPos; } // Schliessen eines Records void SbiCloseRecord( SvStream& r, ULONG nOff ) { ULONG nPos = r.Tell(); r.Seek( nOff + 2 ); r << (INT32) ( nPos - nOff - 8 ); r.Seek( nPos ); } /************************************************************************** * * Laden und Speichern * **************************************************************************/ // Falls die Versionsnummer nicht passt, werden die binaeren Teile // nicht geladen, wohl aber Source, Kommentar und Name. BOOL SbiImage::Load( SvStream& r ) { UINT16 nSign, nCount; UINT32 nLen, nOff; Clear(); ULONG nStart = r.Tell(); // Master-Record einlesen r >> nSign >> nLen >> nCount; ULONG nLast = r.Tell() + nLen; UINT32 nVersion = 0; // Versionsnummer UINT32 nCharSet; // System-Zeichensatz UINT32 lDimBase; UINT16 nReserved1; UINT32 nReserved2; UINT32 nReserved3; BOOL bBadVer = FALSE; if( nSign == B_MODULE ) { r >> nVersion >> nCharSet >> lDimBase >> nFlags >> nReserved1 >> nReserved2 >> nReserved3; eCharSet = (CharSet) nCharSet; eCharSet = GetSOLoadTextEncoding( eCharSet ); bBadVer = BOOL( nVersion != B_CURVERSION ); nDimBase = (USHORT) lDimBase; } ULONG nNext; while( ( nNext = r.Tell() ) < nLast ) { short i; r >> nSign >> nLen >> nCount; nNext += nLen + 8; if( r.GetError() == SVSTREAM_OK ) switch( nSign ) { case B_NAME: r.ReadByteString( aName, eCharSet ); //r >> aName; break; case B_COMMENT: r.ReadByteString( aComment, eCharSet ); //r >> aComment; break; case B_SOURCE: r.ReadByteString( aSource, eCharSet ); //r >> aSource; break; case B_PCODE: if( bBadVer ) break; pCode = new char[ nLen ]; nCodeSize = (USHORT) nLen; r.Read( pCode, nCodeSize ); break; case B_PUBLICS: case B_POOLDIR: case B_SYMPOOL: case B_LINERANGES: break; case B_STRINGPOOL: if( bBadVer ) break; MakeStrings( nCount ); for( i = 0; i < nStrings && SbiGood( r ); i++ ) { r >> nOff; pStringOff[ i ] = (USHORT) nOff; } r >> nLen; if( SbiGood( r ) ) { delete pStrings; pStrings = new sal_Unicode[ nLen ]; nStringSize = (USHORT) nLen; char* pByteStrings = new char[ nLen ]; r.Read( pByteStrings, nStringSize ); for( short i = 0; i < nStrings; i++ ) { USHORT nOff = pStringOff[ i ]; String aStr( pByteStrings + nOff, eCharSet ); memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) ); } delete pByteStrings; } break; case B_MODEND: goto done; default: break; } else break; r.Seek( nNext ); } done: r.Seek( nLast ); //if( eCharSet != ::GetSystemCharSet() ) //ConvertStrings(); if( !SbiGood( r ) ) bError = TRUE; return BOOL( !bError ); } BOOL SbiImage::Save( SvStream& r ) { // Erst mal der Header: ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 ); ULONG nPos; eCharSet = GetSOStoreTextEncoding( eCharSet ); r << (INT32) B_CURVERSION << (INT32) eCharSet << (INT32) nDimBase << (INT16) nFlags << (INT16) 0 << (INT32) 0 << (INT32) 0; // Name? if( aName.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_NAME, 1 ); r.WriteByteString( aName, eCharSet ); //r << aName; SbiCloseRecord( r, nPos ); } // Kommentar? if( aComment.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_COMMENT, 1 ); r.WriteByteString( aComment, eCharSet ); //r << aComment; SbiCloseRecord( r, nPos ); } // Source? if( aSource.Len() && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_SOURCE, 1 ); r.WriteByteString( aSource, eCharSet ); //r << aSource; SbiCloseRecord( r, nPos ); } // Binaere Daten? if( pCode && SbiGood( r ) ) { nPos = SbiOpenRecord( r, B_PCODE, 1 ); r.Write( pCode, nCodeSize ); SbiCloseRecord( r, nPos ); } // String-Pool? if( nStrings ) { nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings ); // Fuer jeden String: // UINT32 Offset des Strings im Stringblock for( short i = 0; i < nStrings && SbiGood( r ); i++ ) r << (UINT32) pStringOff[ i ]; // Danach der String-Block char* pByteStrings = new char[ nStringSize ]; for( i = 0; i < nStrings; i++ ) { USHORT nOff = pStringOff[ i ]; ByteString aStr( pStrings + nOff, eCharSet ); memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) ); } r << (UINT32) nStringSize; r.Write( pByteStrings, nStringSize ); delete pByteStrings; SbiCloseRecord( r, nPos ); } // Und die Gesamtlaenge setzen SbiCloseRecord( r, nStart ); if( !SbiGood( r ) ) bError = TRUE; return BOOL( !bError ); } /************************************************************************** * * Routinen, die auch vom Compiler gerufen werden * **************************************************************************/ void SbiImage::MakeStrings( short nSize ) { nStrings = nStringIdx = nStringOff = 0; nStringSize = 1024; pStrings = new sal_Unicode[ nStringSize ]; pStringOff = new UINT16[ nSize ]; if( pStrings && pStringOff ) { nStrings = nSize; memset( pStringOff, 0, nSize * sizeof( UINT16 ) ); memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) ); } else bError = TRUE; } // Hinzufuegen eines Strings an den StringPool. Der String-Puffer // waechst dynamisch in 1K-Schritten // AB 12.5.2000 Aus Zeitgruenden vorerst weiter auf char-Basis // TODO: Auch hier auf Unicode umstellen, d.h. sal_Unicode-Array void SbiImage::AddString( const String& r ) { if( nStringIdx >= nStrings ) bError = TRUE; if( !bError ) { UINT16 len = r.Len() + 1; long needed = (long) nStringOff + len; if( needed > 0xFF00L ) bError = TRUE; // out of mem! else if( (USHORT) needed > nStringSize ) { sal_Unicode* p = new sal_Unicode[ nStringSize + 1024 ]; if( p ) { memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) ); delete pStrings; pStrings = p; nStringSize += 1024; } else bError = TRUE; } if( !bError ) { pStringOff[ nStringIdx++ ] = nStringOff; //ByteString aByteStr( r, eCharSet ); memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) ); nStringOff += len; // war das der letzte String? Dann die Groesse // des Puffers aktualisieren if( nStringIdx >= nStrings ) nStringSize = nStringOff; } } } // Codeblock hinzufuegen // Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt // und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers // im Big Endian-Format, kann also direkt gelesen/geschrieben werden. void SbiImage::AddCode( char* p, USHORT s ) { pCode = p; nCodeSize = s; } void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen { SbxObject *pCopyObject = new SbxObject(*pObject); rTypes->Insert (pCopyObject,rTypes->Count()); } /************************************************************************** * * Zugriffe auf das Image * **************************************************************************/ // IDs zaehlen ab 1!! String SbiImage::GetString( short nId ) const { if( nId && nId <= nStrings ) { USHORT nOff = pStringOff[ --nId ]; String aStr( pStrings + nOff ); return aStr; } return String(); } const SbxObject* SbiImage::FindType (String aTypeName) const { return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT); } <|endoftext|>
<commit_before> #ifndef __CLIENT_HPP__ #define __CLIENT_HPP__ #include <pthread.h> #include "protocol.hpp" using namespace std; /* Information shared between clients */ struct shared_t { public: typedef protocol_t*(*protocol_factory_t)(void); public: shared_t(config_t *_config, protocol_factory_t _protocol_factory) : config(_config), qps_offset(0), latencies_offset(0), qps_fd(NULL), latencies_fd(NULL), protocol_factory(_protocol_factory) { pthread_mutex_init(&mutex, NULL); if(config->qps_file[0] != 0) { qps_fd = fopen(config->qps_file, "wa"); } if(config->latency_file[0] != 0) { latencies_fd = fopen(config->latency_file, "wa"); } } ~shared_t() { if(qps_fd) { fwrite(qps, 1, qps_offset, qps_fd); fclose(qps_fd); } if(latencies_fd) { fwrite(latencies, 1, latencies_offset, latencies_fd); fclose(latencies_fd); } pthread_mutex_destroy(&mutex); } void push_qps(int _qps, int tick) { if(!qps_fd) return; lock(); // Collect qps info from all clients before attempting to print int qps_count = 0, agg_qps = 0; map<int, pair<int, int> >::iterator op = qps_map.find(tick); if(op != qps_map.end()) { qps_count = op->second.first; agg_qps = op->second.second; } qps_count += 1; agg_qps += _qps; if(qps_count == config->clients) { _qps = agg_qps; qps_map.erase(op); } else { qps_map[tick] = pair<int, int>(qps_count, agg_qps); unlock(); return; } int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\n", _qps); if(_off >= sizeof(qps) - qps_offset) { // Couldn't write everything, flush fwrite(qps, 1, qps_offset, qps_fd); // Write again qps_offset = 0; _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\n", _qps); } qps_offset += _off; unlock(); } void push_latency(float latency) { if(!latencies_fd) return; lock(); int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%.2f\n", latency); if(_off >= sizeof(latencies) - latencies_offset) { // Couldn't write everything, flush fwrite(latencies, 1, latencies_offset, latencies_fd); // Write again latencies_offset = 0; _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%.2f\n", latency); } latencies_offset += _off; unlock(); } public: protocol_factory_t protocol_factory; private: config_t *config; map<int, pair<int, int> > qps_map; char qps[40960], latencies[40960]; int qps_offset, latencies_offset; FILE *qps_fd, *latencies_fd; pthread_mutex_t mutex; private: void lock() { pthread_mutex_lock(&mutex); } void unlock() { pthread_mutex_unlock(&mutex); } }; /* Communication structure for main thread and clients */ struct client_data_t { config_t *config; shared_t *shared; }; /* The function that does the work */ void* run_client(void* data) { // Grab the config client_data_t *client_data = (client_data_t*)data; config_t *config = client_data->config; shared_t *shared = client_data->shared; shared_t::protocol_factory_t pf = shared->protocol_factory; protocol_t *proto = (*pf)(); // Connect to the server proto->connect(config->host, config->port); // Store the keys so we can run updates and deletes. vector<payload_t> keys; // Perform the ops ticks_t last_time = get_ticks(), last_qps_time = last_time, now_time; int qps = 0, tick = 0; for(int i = 0; i < config->duration / config->clients; i++) { // Generate the command load_t::load_op_t cmd = config->load.toss(); int _val; payload_t key, value; switch(cmd) { case load_t::delete_op: // Find the key if(keys.empty()) break; _val = random(0, keys.size() - 1); key = keys[_val]; // Delete it from the server proto->remove(key.first, key.second); // Our own bookkeeping free(key.first); keys[_val] = keys[keys.size() - 1]; keys.erase(keys.begin() + _val); break; case load_t::update_op: // Find the key and generate the payload if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; config->values.toss(&value); // Send it to server proto->update(key.first, key.second, value.first, value.second); // Free the value free(value.first); break; case load_t::insert_op: // Generate the payload config->keys.toss(&key); config->values.toss(&value); // Send it to server proto->insert(key.first, key.second, value.first, value.second); // Free the value and save the key free(value.first); keys.push_back(key); break; case load_t::read_op: // Find the key if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; // Read it from the server proto->read(key.first, key.second); break; }; now_time = get_ticks(); qps++; // Deal with individual op latency ticks_t latency = now_time - last_time; shared->push_latency(ticks_to_us(latency)); last_time = now_time; // Deal with QPS if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) { shared->push_qps(qps, tick); last_qps_time = now_time; qps = 0; tick++; } } delete proto; // Free all the keys for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) { free(i->first); } } #endif // __CLIENT_HPP__ <commit_msg>Changing the client to report seconds for each number<commit_after> #ifndef __CLIENT_HPP__ #define __CLIENT_HPP__ #include <pthread.h> #include "protocol.hpp" using namespace std; /* Information shared between clients */ struct shared_t { public: typedef protocol_t*(*protocol_factory_t)(void); public: shared_t(config_t *_config, protocol_factory_t _protocol_factory) : config(_config), qps_offset(0), latencies_offset(0), qps_fd(NULL), latencies_fd(NULL), protocol_factory(_protocol_factory), n_op(1), n_tick(1) { pthread_mutex_init(&mutex, NULL); if(config->qps_file[0] != 0) { qps_fd = fopen(config->qps_file, "wa"); } if(config->latency_file[0] != 0) { latencies_fd = fopen(config->latency_file, "wa"); } } ~shared_t() { if(qps_fd) { fwrite(qps, 1, qps_offset, qps_fd); fclose(qps_fd); } if(latencies_fd) { fwrite(latencies, 1, latencies_offset, latencies_fd); fclose(latencies_fd); } pthread_mutex_destroy(&mutex); } void push_qps(int _qps, int tick) { if(!qps_fd) return; lock(); // Collect qps info from all clients before attempting to print int qps_count = 0, agg_qps = 0; map<int, pair<int, int> >::iterator op = qps_map.find(tick); if(op != qps_map.end()) { qps_count = op->second.first; agg_qps = op->second.second; } qps_count += 1; agg_qps += _qps; if(qps_count == config->clients) { _qps = agg_qps; qps_map.erase(op); } else { qps_map[tick] = pair<int, int>(qps_count, agg_qps); unlock(); return; } int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps); if(_off >= sizeof(qps) - qps_offset) { // Couldn't write everything, flush fwrite(qps, 1, qps_offset, qps_fd); // Write again qps_offset = 0; _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps); } qps_offset += _off; n_tick++; unlock(); } void push_latency(float latency) { if(!latencies_fd) return; lock(); int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency); if(_off >= sizeof(latencies) - latencies_offset) { // Couldn't write everything, flush fwrite(latencies, 1, latencies_offset, latencies_fd); // Write again latencies_offset = 0; _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency); } latencies_offset += _off; n_op++; unlock(); } public: protocol_factory_t protocol_factory; private: config_t *config; map<int, pair<int, int> > qps_map; char qps[40960], latencies[40960]; int qps_offset, latencies_offset; FILE *qps_fd, *latencies_fd; pthread_mutex_t mutex; long n_op; int n_tick; private: void lock() { pthread_mutex_lock(&mutex); } void unlock() { pthread_mutex_unlock(&mutex); } }; /* Communication structure for main thread and clients */ struct client_data_t { config_t *config; shared_t *shared; }; /* The function that does the work */ void* run_client(void* data) { // Grab the config client_data_t *client_data = (client_data_t*)data; config_t *config = client_data->config; shared_t *shared = client_data->shared; shared_t::protocol_factory_t pf = shared->protocol_factory; protocol_t *proto = (*pf)(); // Connect to the server proto->connect(config->host, config->port); // Store the keys so we can run updates and deletes. vector<payload_t> keys; // Perform the ops ticks_t last_time = get_ticks(), last_qps_time = last_time, now_time; int qps = 0, tick = 0; for(int i = 0; i < config->duration / config->clients; i++) { // Generate the command load_t::load_op_t cmd = config->load.toss(); int _val; payload_t key, value; switch(cmd) { case load_t::delete_op: // Find the key if(keys.empty()) break; _val = random(0, keys.size() - 1); key = keys[_val]; // Delete it from the server proto->remove(key.first, key.second); // Our own bookkeeping free(key.first); keys[_val] = keys[keys.size() - 1]; keys.erase(keys.begin() + _val); break; case load_t::update_op: // Find the key and generate the payload if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; config->values.toss(&value); // Send it to server proto->update(key.first, key.second, value.first, value.second); // Free the value free(value.first); break; case load_t::insert_op: // Generate the payload config->keys.toss(&key); config->values.toss(&value); // Send it to server proto->insert(key.first, key.second, value.first, value.second); // Free the value and save the key free(value.first); keys.push_back(key); break; case load_t::read_op: // Find the key if(keys.empty()) break; key = keys[random(0, keys.size() - 1)]; // Read it from the server proto->read(key.first, key.second); break; }; now_time = get_ticks(); qps++; // Deal with individual op latency ticks_t latency = now_time - last_time; shared->push_latency(ticks_to_us(latency)); last_time = now_time; // Deal with QPS if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) { shared->push_qps(qps, tick); last_qps_time = now_time; qps = 0; tick++; } } delete proto; // Free all the keys for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) { free(i->first); } } #endif // __CLIENT_HPP__ <|endoftext|>
<commit_before>#include <nan.h> // toys used in testing #include <cmath> #include <time.h> //============================================================================== // Implementation sketch //============================================================================== namespace NanIntern { // scnr template <typename T> struct FactoryBase { typedef v8::Local<T> return_t; }; template <typename T> struct Factory; template <> struct Factory<v8::Array> : public FactoryBase<v8::Array> { static inline return_t New() { return v8::Array::New(v8::Isolate::GetCurrent()); } static inline return_t New(int length) { return v8::Array::New(v8::Isolate::GetCurrent(), length); } }; template <> struct Factory<v8::Boolean> : public FactoryBase<v8::Boolean> { static inline return_t New(bool value) { return v8::Boolean::New(v8::Isolate::GetCurrent(), value); } }; template <> struct Factory<v8::External> : public FactoryBase<v8::External> { static inline return_t New(void *value) { return v8::External::New(v8::Isolate::GetCurrent(), value); } }; template <> struct Factory<v8::Date> : public FactoryBase<v8::Date> { static inline return_t New(double value) { return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>(); } }; template <> struct Factory<v8::String> : public FactoryBase<v8::String> { static inline return_t New(const char * value) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value); } static inline return_t New(const char * value, int length) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, v8::String::kNormalString, length); } static inline return_t New(std::string const & value) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), &*value.begin(), v8::String::kNormalString, value.size()); } }; //=== Numeric Types ============================================================ template <> struct Factory<v8::Number> : public FactoryBase<v8::Number> { static inline return_t New(double value) { return v8::Number::New(v8::Isolate::GetCurrent(), value); } }; template <typename T> v8::Local<T> To(v8::Handle<v8::Integer> i); template <> v8::Local<v8::Integer> To<v8::Integer>(v8::Handle<v8::Integer> i) { return i; } template <> v8::Local<v8::Int32> To<v8::Int32>(v8::Handle<v8::Integer> i) { return i->ToInt32(); } template <> v8::Local<v8::Uint32> To<v8::Uint32>(v8::Handle<v8::Integer> i) { return i->ToUint32(); } template <typename T> struct IntegerFactory : public FactoryBase<T>{ typedef typename FactoryBase<T>::return_t return_t; static inline return_t New(int32_t value) { return To<T>(T::New(v8::Isolate::GetCurrent(), value)); } static inline return_t New(uint32_t value) { return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); } }; template <> struct Factory<v8::Integer> : public IntegerFactory<v8::Integer> {}; template <> struct Factory<v8::Int32> : public IntegerFactory<v8::Int32> {}; template <> struct Factory<v8::Uint32> : public IntegerFactory<v8::Uint32> {}; } // end of namespace NanIntern //=== API ====================================================================== template <typename T> typename NanIntern::Factory<T>::return_t NanNew2() { return NanIntern::Factory<T>::New(); } template <typename T, typename A0> typename NanIntern::Factory<T>::return_t NanNew2(A0 arg0) { return NanIntern::Factory<T>::New(arg0); } template <typename T, typename A0, typename A1> typename NanIntern::Factory<T>::return_t NanNew2(A0 arg0, A1 arg1) { return NanIntern::Factory<T>::New(arg0, arg1); } void NanExport(v8::Handle<v8::Object> target, const char * name, NanFunctionCallback f) { target->Set(NanNew<v8::String>(name), NanNew<v8::FunctionTemplate>(f)->GetFunction()); } #define return_NanValue(v) NanReturnValue(v) #define NAN_EXPORT(target, function) NanExport(target, #function, function) //============================================================================== // Sample Module //============================================================================== NAN_METHOD(newIntegerWithValue) { NanScope(); return_NanValue(NanNew2<v8::Integer>(args[0]->Int32Value())); } NAN_METHOD(newNumberWithValue) { NanScope(); return_NanValue(NanNew2<v8::Number>(args[0]->NumberValue())); } NAN_METHOD(newUint32WithValue) { NanScope(); return_NanValue(NanNew2<v8::Uint32>(args[0]->Uint32Value())); } NAN_METHOD(newStringFromChars) { NanScope(); return_NanValue(NanNew2<v8::String>("hello?")); } NAN_METHOD(newStringFromCharsWithLength) { NanScope(); return_NanValue(NanNew2<v8::String>("hello?", 4)); } NAN_METHOD(newStringFromStdString) { NanScope(); return_NanValue(NanNew2<v8::String>(std::string("hello!"))); } NAN_METHOD(demoDateAndNumber) { NanScope(); v8::Local<v8::Value> number = NanNew<v8::Number>(M_PI); v8::Local<v8::Value> date = NanNew<v8::Date>(double(time(NULL))); (void)number; (void)date; // unused NanReturnUndefined(); } int ttt = 23; NAN_METHOD(newExternal) { NanScope(); return_NanValue(NanNew2<v8::External>(&ttt)); } void Init(v8::Handle<v8::Object> exports) { NanExport(exports, "newIntegerWithValue", newIntegerWithValue); NAN_EXPORT(exports, newNumberWithValue); NAN_EXPORT(exports, newUint32WithValue); NAN_EXPORT(exports, newStringFromChars); NAN_EXPORT(exports, newStringFromCharsWithLength); NAN_EXPORT(exports, newStringFromStdString); NAN_EXPORT(exports, demoDateAndNumber); NAN_EXPORT(exports, newExternal); } NODE_MODULE(nan_sketch, Init) <commit_msg>Fixed indentation.<commit_after>#include <nan.h> // toys used in testing #include <cmath> #include <time.h> //============================================================================== // Implementation sketch //============================================================================== //namespace NanIntern { // scnr template <typename T> struct FactoryBase { typedef v8::Local<T> return_t; }; template <typename T> struct Factory; template <> struct Factory<v8::Array> : public FactoryBase<v8::Array> { static inline return_t New() { return v8::Array::New(v8::Isolate::GetCurrent()); } static inline return_t New(int length) { return v8::Array::New(v8::Isolate::GetCurrent(), length); } }; template <> struct Factory<v8::Boolean> : public FactoryBase<v8::Boolean> { static inline return_t New(bool value) { return v8::Boolean::New(v8::Isolate::GetCurrent(), value); } }; template <> struct Factory<v8::External> : public FactoryBase<v8::External> { static inline return_t New(void *value) { return v8::External::New(v8::Isolate::GetCurrent(), value); } }; template <> struct Factory<v8::Date> : public FactoryBase<v8::Date> { static inline return_t New(double value) { return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>(); } }; template <> struct Factory<v8::String> : public FactoryBase<v8::String> { static inline return_t New(const char * value) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value); } static inline return_t New(const char * value, int length) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, v8::String::kNormalString, length); } static inline return_t New(std::string const & value) { return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), &*value.begin(), v8::String::kNormalString, value.size()); } }; //=== Numeric Types ============================================================ template <> struct Factory<v8::Number> : public FactoryBase<v8::Number> { static inline return_t New(double value) { return v8::Number::New(v8::Isolate::GetCurrent(), value); } }; template <typename T> v8::Local<T> To(v8::Handle<v8::Integer> i); template <> v8::Local<v8::Integer> To<v8::Integer>(v8::Handle<v8::Integer> i) { return i; } template <> v8::Local<v8::Int32> To<v8::Int32>(v8::Handle<v8::Integer> i) { return i->ToInt32(); } template <> v8::Local<v8::Uint32> To<v8::Uint32>(v8::Handle<v8::Integer> i) { return i->ToUint32(); } template <typename T> struct IntegerFactory : public FactoryBase<T>{ typedef typename FactoryBase<T>::return_t return_t; static inline return_t New(int32_t value) { return To<T>(T::New(v8::Isolate::GetCurrent(), value)); } static inline return_t New(uint32_t value) { return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); } }; template <> struct Factory<v8::Integer> : public IntegerFactory<v8::Integer> {}; template <> struct Factory<v8::Int32> : public IntegerFactory<v8::Int32> {}; template <> struct Factory<v8::Uint32> : public IntegerFactory<v8::Uint32> {}; //} // end of namespace NanIntern //=== API ====================================================================== template <typename T> typename NanIntern::Factory<T>::return_t NanNew2() { return NanIntern::Factory<T>::New(); } template <typename T, typename A0> typename NanIntern::Factory<T>::return_t NanNew2(A0 arg0) { return NanIntern::Factory<T>::New(arg0); } template <typename T, typename A0, typename A1> typename NanIntern::Factory<T>::return_t NanNew2(A0 arg0, A1 arg1) { return NanIntern::Factory<T>::New(arg0, arg1); } void NanExport(v8::Handle<v8::Object> target, const char * name, NanFunctionCallback f) { target->Set(NanNew<v8::String>(name), NanNew<v8::FunctionTemplate>(f)->GetFunction()); } #define return_NanValue(v) NanReturnValue(v) #define NAN_EXPORT(target, function) NanExport(target, #function, function) //============================================================================== // Sample Module //============================================================================== NAN_METHOD(newIntegerWithValue) { NanScope(); return_NanValue(NanNew2<v8::Integer>(args[0]->Int32Value())); } NAN_METHOD(newNumberWithValue) { NanScope(); return_NanValue(NanNew2<v8::Number>(args[0]->NumberValue())); } NAN_METHOD(newUint32WithValue) { NanScope(); return_NanValue(NanNew2<v8::Uint32>(args[0]->Uint32Value())); } NAN_METHOD(newStringFromChars) { NanScope(); return_NanValue(NanNew2<v8::String>("hello?")); } NAN_METHOD(newStringFromCharsWithLength) { NanScope(); return_NanValue(NanNew2<v8::String>("hello?", 4)); } NAN_METHOD(newStringFromStdString) { NanScope(); return_NanValue(NanNew2<v8::String>(std::string("hello!"))); } NAN_METHOD(demoDateAndNumber) { NanScope(); v8::Local<v8::Value> number = NanNew<v8::Number>(M_PI); v8::Local<v8::Value> date = NanNew<v8::Date>(double(time(NULL))); (void)number; (void)date; // unused NanReturnUndefined(); } int ttt = 23; NAN_METHOD(newExternal) { NanScope(); return_NanValue(NanNew2<v8::External>(&ttt)); } void Init(v8::Handle<v8::Object> exports) { NanExport(exports, "newIntegerWithValue", newIntegerWithValue); NAN_EXPORT(exports, newNumberWithValue); NAN_EXPORT(exports, newUint32WithValue); NAN_EXPORT(exports, newStringFromChars); NAN_EXPORT(exports, newStringFromCharsWithLength); NAN_EXPORT(exports, newStringFromStdString); NAN_EXPORT(exports, demoDateAndNumber); NAN_EXPORT(exports, newExternal); } NODE_MODULE(nan_sketch, Init) <|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <list> #include <set> #include <cmath> #include <cassert> #include <iostream> #include <iterator> #include <type_traits> #include <utility> #include <vigra/multi_array.hxx> #include <vigra/linear_algebra.hxx> namespace vigra { template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N == 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { // Will ignore boundaries initially. // Then will try adding reflection. // Rank must be in the range 0 to 1 assert((0 <= rank) && (rank <= 1)); const int rank_pos = round(rank * (2 * half_length)); // The position of the typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0); std::multiset<T1> sorted_window; std::list< typename std::multiset<T1>::iterator > window_iters; // Get the initial sorted window. // Include the reflection. for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--) { window_iters.push_back(sorted_window.insert(src[window_begin + j])); } for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++) { window_iters.push_back(sorted_window.insert(src[window_begin + j])); } typename std::multiset<T1>::iterator rank_point = sorted_window.begin(); for (int i = 0; i < rank_pos; i++) { rank_point++; } typename std::multiset<T1>::iterator prev_iter; T1 prev_value; T1 next_value; while ( window_begin < src.size() ) { dest[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin < (src.size() - half_length) ) { next_value = src[window_begin + half_length]; } else { next_value = src[2 * src.size() - (window_begin + half_length + 2)]; } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N > 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes; for (unsigned int i = 0; i < N; i++) { transposed_axes[i] = i; } std::swap(transposed_axes[0], transposed_axes[axis]); vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes)); vigra::MultiArrayView<N, T1, S1> dest_transposed(dest.transpose(transposed_axes)); typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos; pos = 0; bool done = false; bool carry = true; while (!done) { lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank); carry = true; for (unsigned int i = 1; ( carry && (i < N) ); i++) { if ( (++pos[i]) < src_transposed.shape(i) ) { carry = false; } else { pos[i] = 0; carry = true; } } done = carry; } } template<unsigned int N, class T1, class S1, class T2, class S2> inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { lineRankOrderFilterND(src, dest, half_length, rank, axis); } } #endif //__RANK_FILTER__ <commit_msg>rank_filter.hxx: Switch to using deque instead of a list.<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <set> #include <cmath> #include <cassert> #include <iostream> #include <iterator> #include <type_traits> #include <utility> #include <vigra/multi_array.hxx> #include <vigra/linear_algebra.hxx> namespace vigra { template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N == 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { // Will ignore boundaries initially. // Then will try adding reflection. // Rank must be in the range 0 to 1 assert((0 <= rank) && (rank <= 1)); const int rank_pos = round(rank * (2 * half_length)); // The position of the typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0); std::multiset<T1> sorted_window; std::deque< typename std::multiset<T1>::iterator > window_iters; // Get the initial sorted window. // Include the reflection. for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--) { window_iters.push_back(sorted_window.insert(src[window_begin + j])); } for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++) { window_iters.push_back(sorted_window.insert(src[window_begin + j])); } typename std::multiset<T1>::iterator rank_point = sorted_window.begin(); for (int i = 0; i < rank_pos; i++) { rank_point++; } typename std::multiset<T1>::iterator prev_iter; T1 prev_value; T1 next_value; while ( window_begin < src.size() ) { dest[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin < (src.size() - half_length) ) { next_value = src[window_begin + half_length]; } else { next_value = src[2 * src.size() - (window_begin + half_length + 2)]; } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N > 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes; for (unsigned int i = 0; i < N; i++) { transposed_axes[i] = i; } std::swap(transposed_axes[0], transposed_axes[axis]); vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes)); vigra::MultiArrayView<N, T1, S1> dest_transposed(dest.transpose(transposed_axes)); typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos; pos = 0; bool done = false; bool carry = true; while (!done) { lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank); carry = true; for (unsigned int i = 1; ( carry && (i < N) ); i++) { if ( (++pos[i]) < src_transposed.shape(i) ) { carry = false; } else { pos[i] = 0; carry = true; } } done = carry; } } template<unsigned int N, class T1, class S1, class T2, class S2> inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned int half_length, float rank, unsigned int axis = 0) { lineRankOrderFilterND(src, dest, half_length, rank, axis); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>#include <cmd_classbook_localization_add_record_handler.h> #include <QJsonArray> #include <QSqlError> #include <log.h> #include <QUuid> #include <QCryptographicHash> CmdClassbookLocalizationAddRecordHandler::CmdClassbookLocalizationAddRecordHandler(){ m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("Classbookid for article localization")); m_vInputs.push_back(CmdInputDef("lang").required().string_().description("Language")); m_vInputs.push_back(CmdInputDef("name").required().string_().description("Article name")); m_vInputs.push_back(CmdInputDef("content").required().string_().description("The content of the article")); } QString CmdClassbookLocalizationAddRecordHandler::cmd(){ return "classbook_localization_add_record"; } bool CmdClassbookLocalizationAddRecordHandler::accessUnauthorized(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessUser(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessTester(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessAdmin(){ return true; } const QVector<CmdInputDef> &CmdClassbookLocalizationAddRecordHandler::inputs(){ return m_vInputs; }; QString CmdClassbookLocalizationAddRecordHandler::description(){ return "Add a new article localization for the English version"; } QStringList CmdClassbookLocalizationAddRecordHandler::errors(){ QStringList list; return list; } void CmdClassbookLocalizationAddRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){ int classbookid = obj["classbookid"].toInt(); QSqlDatabase db = *(pWebSocketServer->database()); QJsonObject data; QSqlQuery query(db); QString lang = obj["lang"].toString().trimmed(); query.prepare("SELECT lang FROM classbook_localization WHERE lang = :lang"); query.bindValue(":lang", obj["lang"].toString().trimmed()); if(!query.exec()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text())); return; } if(query.next()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "This lang already exist")); return; } QString name = obj["name"].toString().trimmed(); QString content = obj["content"].toString().trimmed(); //Set md5_content hash QString md5_content = QString(QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Md5).toHex()); //generate uuid QString uuid = QUuid::createUuid().toString().replace("{", "").replace("}", ""); query.prepare("INSERT INTO classbook_localization(" "classbookid," "uuid," "lang," "name," "content," "md5_content," "created," "updated" ") " "VALUES(" ":classbookid," ":uuid," ":lang," ":name," ":content," ":md5_content," "NOW()," "NOW()" ")"); query.bindValue(":classbookid", classbookid); query.bindValue(":uuid", uuid); query.bindValue(":lang", lang); query.bindValue(":name", name); query.bindValue(":content", content); query.bindValue(":md5_content", md5_content); if(!query.exec()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text())); return; } int rowid = query.lastInsertId().toInt(); data["classbookid"] = classbookid; data["classbook_localizationid"] = QJsonValue(rowid); data["lang"] = lang; data["name"] = name; data["content"] = content; data["md5_content"] = md5_content; QJsonObject jsonData; jsonData["cmd"] = QJsonValue(cmd()); jsonData["m"] = QJsonValue(m); jsonData["result"] = QJsonValue("DONE"); jsonData["data"] = data; pWebSocketServer->sendMessage(pClient, jsonData); } <commit_msg>Fix add localization<commit_after>#include <cmd_classbook_localization_add_record_handler.h> #include <QJsonArray> #include <QSqlError> #include <log.h> #include <QUuid> #include <QCryptographicHash> CmdClassbookLocalizationAddRecordHandler::CmdClassbookLocalizationAddRecordHandler(){ m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("Classbookid for article localization")); m_vInputs.push_back(CmdInputDef("lang").required().string_().description("Language")); m_vInputs.push_back(CmdInputDef("name").required().string_().description("Article name")); m_vInputs.push_back(CmdInputDef("content").required().string_().description("The content of the article")); } QString CmdClassbookLocalizationAddRecordHandler::cmd(){ return "classbook_localization_add_record"; } bool CmdClassbookLocalizationAddRecordHandler::accessUnauthorized(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessUser(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessTester(){ return false; } bool CmdClassbookLocalizationAddRecordHandler::accessAdmin(){ return true; } const QVector<CmdInputDef> &CmdClassbookLocalizationAddRecordHandler::inputs(){ return m_vInputs; }; QString CmdClassbookLocalizationAddRecordHandler::description(){ return "Add a new article localization for the English version"; } QStringList CmdClassbookLocalizationAddRecordHandler::errors(){ QStringList list; return list; } void CmdClassbookLocalizationAddRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){ int classbookid = obj["classbookid"].toInt(); QSqlDatabase db = *(pWebSocketServer->database()); QJsonObject data; QSqlQuery query(db); QString lang = obj["lang"].toString().trimmed(); query.prepare("SELECT lang FROM classbook_localization WHERE lang = :lang AND classbookid=:classbookid"); query.bindValue(":lang", obj["lang"].toString().trimmed()); query.bindValue(":classbookid", classbookid); if(!query.exec()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text())); return; } if(query.next()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "This lang already exist")); return; } QString name = obj["name"].toString().trimmed(); QString content = obj["content"].toString().trimmed(); //Set md5_content hash QString md5_content = QString(QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Md5).toHex()); //generate uuid QString uuid = QUuid::createUuid().toString().replace("{", "").replace("}", ""); query.prepare("INSERT INTO classbook_localization(" "classbookid," "uuid," "lang," "name," "content," "md5_content," "created," "updated" ") " "VALUES(" ":classbookid," ":uuid," ":lang," ":name," ":content," ":md5_content," "NOW()," "NOW()" ")"); query.bindValue(":classbookid", classbookid); query.bindValue(":uuid", uuid); query.bindValue(":lang", lang); query.bindValue(":name", name); query.bindValue(":content", content); query.bindValue(":md5_content", md5_content); if(!query.exec()){ pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text())); return; } int rowid = query.lastInsertId().toInt(); data["classbookid"] = classbookid; data["classbook_localizationid"] = QJsonValue(rowid); data["lang"] = lang; data["name"] = name; data["content"] = content; data["md5_content"] = md5_content; QJsonObject jsonData; jsonData["cmd"] = QJsonValue(cmd()); jsonData["m"] = QJsonValue(m); jsonData["result"] = QJsonValue("DONE"); jsonData["data"] = data; pWebSocketServer->sendMessage(pClient, jsonData); } <|endoftext|>
<commit_before>#include "mpi_common.h" #include <iostream> #include "phonons.h" #include "timer.h" #include "parsephon.h" #include "memory.h" #include "error.h" #include "gruneisen.h" #include "system.h" #include "symmetry_core.h" #include "kpoint.h" #include "fcs_phonon.h" #include "dynamical.h" #include "phonon_velocity.h" #include "phonon_thermodynamics.h" #include "write_phonons.h" #include "phonon_dos.h" #include "integration.h" #include "relaxation.h" #include "conductivity.h" #include <omp.h> using namespace PHON_NS; PHON::PHON(int narg, char **arg, MPI_Comm comm) { mympi = new MyMPI(this, comm); input = new Input(this); restart_flag = false; create_pointers(); if (mympi->my_rank == 0) { std::cout << "Phonons program version 1.0 (MPI)" << std::endl; std::cout << std::endl << "Job started at " << timer->DataAndTime() << std::endl << std::endl; std::cout << "The number of MPI threads: " << mympi->nprocs << std::endl; std::cout << "The number of OpenMP threads: " << omp_get_num_threads() << std::endl; std::cout << std::endl; input->parce_input(narg, arg); } mympi->MPI_Bcast_string(input->job_title, 0, MPI_COMM_WORLD); mympi->MPI_Bcast_string(mode, 0, MPI_COMM_WORLD); if (mode == "phonons") { system->setup(); symmetry->setup_symmetry(); kpoint->kpoint_setups(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dos->setup(); dynamical->diagonalize_dynamical_all(); // Calculate the group velocity of phonons along given direction in // the reciprocal space. if (kpoint->kpoint_mode == 1) { phonon_velocity->calc_phonon_vel_band(); } if (dos->flag_dos) { integration->setup_integration(); dos->calc_dos(); } if (mympi->my_rank == 0) { writes->write_phonon_info(); } memory->deallocate(dynamical->evec_phonon); memory->deallocate(dynamical->eval_phonon); if (kpoint->kpoint_mode == 1) { memory->deallocate(phonon_velocity->phvel); } if (dos->flag_dos) { integration->finish_integration(); } } else if (mode == "boltzmann") { system->setup(); symmetry->setup_symmetry(); kpoint->kpoint_setups(); dos->setup(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dynamical->diagonalize_dynamical_all(); integration->setup_integration(); relaxation->setup_relaxation(); // dos->calc_tdos(); // relaxation->calc_selfenergy(); // relaxation->v3_test(); conductivity->setup_kl(); conductivity->calc_kl(); integration->finish_integration(); relaxation->finish_relaxation(); conductivity->finish_kl(); } else if (mode == "gruneisen") { system->setup(); kpoint->kpoint_setups(); dos->setup(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dynamical->diagonalize_dynamical_all(); gruneisen->setup(); gruneisen->calc_gruneisen(); // gruneisen->calc_gruneisen2(); writes->write_gruneisen(); gruneisen->finish_gruneisen(); } else { error->exit("phonons", "invalid mode"); } if (mympi->my_rank == 0) { std::cout << std::endl << "Job finished at " << timer->DataAndTime() << std::endl; std::cout << "Bye! :)" << std::endl; } destroy_pointers(); } PHON::~PHON(){ delete input; delete mympi; } void PHON::create_pointers() { memory = new Memory(this); timer = new Timer(this); error = new Error(this); system = new System(this); symmetry = new Symmetry(this); kpoint = new Kpoint(this); fcs_phonon = new Fcs_phonon(this); dynamical = new Dynamical(this); integration = new Integration(this); phonon_velocity = new Phonon_velocity(this); phonon_thermodynamics = new Phonon_thermodynamics(this); relaxation = new Relaxation(this); conductivity = new Conductivity(this); writes = new Writes(this); dos = new Dos(this); gruneisen = new Gruneisen(this); } void PHON::destroy_pointers() { delete memory; delete timer; delete error; delete system; delete symmetry; delete kpoint; delete fcs_phonon; delete dynamical; delete integration; delete phonon_velocity; delete phonon_thermodynamics; delete relaxation; delete conductivity; delete writes; delete dos; delete gruneisen; } <commit_msg>Formatted.<commit_after>#include "mpi_common.h" #include <iostream> #include "phonons.h" #include "timer.h" #include "parsephon.h" #include "memory.h" #include "error.h" #include "gruneisen.h" #include "system.h" #include "symmetry_core.h" #include "kpoint.h" #include "fcs_phonon.h" #include "dynamical.h" #include "phonon_velocity.h" #include "phonon_thermodynamics.h" #include "write_phonons.h" #include "phonon_dos.h" #include "integration.h" #include "relaxation.h" #include "conductivity.h" #include <omp.h> using namespace PHON_NS; PHON::PHON(int narg, char **arg, MPI_Comm comm) { mympi = new MyMPI(this, comm); input = new Input(this); restart_flag = false; create_pointers(); if (mympi->my_rank == 0) { std::cout << "Phonons program version 1.0 (MPI)" << std::endl; std::cout << std::endl << "Job started at " << timer->DataAndTime() << std::endl << std::endl; std::cout << "The number of MPI threads: " << mympi->nprocs << std::endl; std::cout << "The number of OpenMP threads: " << omp_get_num_threads() << std::endl; std::cout << std::endl; input->parce_input(narg, arg); } mympi->MPI_Bcast_string(input->job_title, 0, MPI_COMM_WORLD); mympi->MPI_Bcast_string(mode, 0, MPI_COMM_WORLD); if (mode == "phonons") { system->setup(); symmetry->setup_symmetry(); kpoint->kpoint_setups(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dos->setup(); dynamical->diagonalize_dynamical_all(); // Calculate the group velocity of phonons along given direction in // the reciprocal space. if (kpoint->kpoint_mode == 1) { phonon_velocity->calc_phonon_vel_band(); } if (dos->flag_dos) { integration->setup_integration(); dos->calc_dos(); } if (mympi->my_rank == 0) { writes->write_phonon_info(); } memory->deallocate(dynamical->evec_phonon); memory->deallocate(dynamical->eval_phonon); if (kpoint->kpoint_mode == 1) { memory->deallocate(phonon_velocity->phvel); } if (dos->flag_dos) { integration->finish_integration(); } } else if (mode == "boltzmann") { system->setup(); symmetry->setup_symmetry(); kpoint->kpoint_setups(); dos->setup(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dynamical->diagonalize_dynamical_all(); integration->setup_integration(); relaxation->setup_relaxation(); // dos->calc_tdos(); // relaxation->calc_selfenergy(); // relaxation->v3_test(); conductivity->setup_kl(); conductivity->calc_kl(); integration->finish_integration(); relaxation->finish_relaxation(); conductivity->finish_kl(); } else if (mode == "gruneisen") { system->setup(); kpoint->kpoint_setups(); dos->setup(); fcs_phonon->setup(mode); dynamical->setup_dynamical(mode); dynamical->diagonalize_dynamical_all(); gruneisen->setup(); gruneisen->calc_gruneisen(); // gruneisen->calc_gruneisen2(); writes->write_gruneisen(); gruneisen->finish_gruneisen(); } else { error->exit("phonons", "invalid mode"); } if (mympi->my_rank == 0) { std::cout << std::endl << "Job finished at " << timer->DataAndTime() << std::endl; std::cout << "Bye! :)" << std::endl; } destroy_pointers(); } PHON::~PHON(){ delete input; delete mympi; } void PHON::create_pointers() { memory = new Memory(this); timer = new Timer(this); error = new Error(this); system = new System(this); symmetry = new Symmetry(this); kpoint = new Kpoint(this); fcs_phonon = new Fcs_phonon(this); dynamical = new Dynamical(this); integration = new Integration(this); phonon_velocity = new Phonon_velocity(this); phonon_thermodynamics = new Phonon_thermodynamics(this); relaxation = new Relaxation(this); conductivity = new Conductivity(this); writes = new Writes(this); dos = new Dos(this); gruneisen = new Gruneisen(this); } void PHON::destroy_pointers() { delete memory; delete timer; delete error; delete system; delete symmetry; delete kpoint; delete fcs_phonon; delete dynamical; delete integration; delete phonon_velocity; delete phonon_thermodynamics; delete relaxation; delete conductivity; delete writes; delete dos; delete gruneisen; } <|endoftext|>
<commit_before>#include <iostream> #include <settings_class.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> void Settings_Profile::test_function(int a){ std::cout << a; return; } Settings_Profile::Settings_Profile(){ } Settings_Profile::Settings_Profile(std::string filename){ try{ boost::property_tree::ptree data; boost::property_tree::xml_parser::read_xml(filename, data); std::string inputs = data.get<std::string>("db.profile.img_name"); this->addImgName(inputs); inputs = data.get<std::string>("db.profile.config_name"); this->setConfigName(inputs); inputs = data.get<std::string>("db.profile.base_dir"); this->setBaseDir(inputs); float coord = data.get<float>("db.profile.x"); this->addX(coord); coord = data.get<float>("db.profile.y"); this->addY(coord); this->default_res_x = data.get<int>("db.profile.default_res_x"); this->default_res_y = data.get<int>("db.profile.default_res_y"); }catch(const std::exception &e){ std::cerr << e.what(); exit(1); } } /* void Settings_Profile::printableContents(std::string* file_contents){ file_contents->clear(); return; } */ int Settings_Profile::writeToFile(){ std::string content = this->img_names.at(0); std::cout << content; return 1; } void Settings_Profile::setConfigName(std::string name){ this->config_name = name; return; } void Settings_Profile::setBaseDir(std::string name){ this->base_dir = name; return; } void Settings_Profile::addImgName(std::string name){ this->img_names.push_back(name); return; } void Settings_Profile::addX(float x){ this->x.push_back(x); return; } void Settings_Profile::addY(float y){ this->y.push_back(y); return; } void Settings_Profile::printInfo(){ std::cout << "Config Name: " << this->config_name << "\nBase Dir: " << this->base_dir << "\nImage Names: " << img_names.at(0) << "\nX: " << this->x.at(0) << "\nY: " << this->y.at(0) << "\n"; } std::string Settings_Profile::getImgName(int a){ return this->img_names.at(a); } std::string Settings_Profile::getConfigName(){ return this->config_name; } std::string Settings_Profile::getBaseDir(){ return this->base_dir; } float Settings_Profile::getX(int a){ return this->x.at(a); } float Settings_Profile::getY(int a){ return this->y.at(a); } std::string Settings_Profile::getProcessName(){ return this->process_name; } void Settings_Profile::setProcessName(std::string name){ this->process_name = name; } int Settings_Profile::getImgCount(){ return this->img_names.size(); } void Settings_Profile::setDefaultRes(int x, int y){ this->default_res_x = x; this->default_res_y = y; } int Settings_Profile::getDresY(){ return this->default_res_y; } int Settings_Profile::getDResX(){ return this->default_res_x; }<commit_msg>removed ptree loading for simple line loading using ifstreams<commit_after>#include "settings_class.h" Settings_Profile::Settings_Profile(){ } /** * Takes a filename as a string. Opens file, and streams in the following format: * Set config name * Process Title * base directory - assumed ./ or current directory * button's image name * Default X resolution * Default Y resolution * Offset x of button - button's distance from top left corner of window * Offset y of button - button's distance from top left corner of window * threshold for image * * */ Settings_Profile::Settings_Profile(std::string filename = "lol.txt"){ char* line; try{ //parse file into settings profile std::ifstream input_file(filename); int resx, resy; float threshold; // Do parsing here line = (char*) calloc(256, sizeof(char)); // Start populating object. // Implement easier way but using function pointer array and while loop input_file.getline(line, 256); this->setConfigName(line); memset(line, 0, 256); input_file.getline(line, 256); this->setProcessName(line); memset(line, 0, 256); input_file.getline(line,256); this->setBaseDir(line); input_file.getline(line, 256); this->addImgName(line); memset(line, 0, 256); input_file >> resx; input_file >> resy; this->setDefaultRes(resx, resy); input_file >> resx; input_file >> resy; this->addX(resx); this->addY(resy); input_file >> threshold; this->addThreshold(threshold); input_file.close(); }catch(const std::exception &e){ std::cerr << e.what(); free(line); // necessary? } free(line); } /* void Settings_Profile::printableContents(std::string* file_contents){ file_contents->clear(); return; } */ int Settings_Profile::writeToFile(){ std::string content = this->img_names.at(0); std::cout << content; return 1; } void Settings_Profile::setConfigName(std::string name){ this->config_name = name; return; } void Settings_Profile::setBaseDir(std::string name){ this->base_dir = name; return; } void Settings_Profile::addImgName(std::string name){ this->img_names.push_back(name); return; } void Settings_Profile::addX(float x){ this->x.push_back(x); return; } void Settings_Profile::addY(float y){ this->y.push_back(y); return; } void Settings_Profile::printInfo(){ std::cout << "Config Name: " << this->config_name << "\nExecutable: " << this->process_name << "\nBase Dir: "; std::cout << this->base_dir << "\nImage Names: " << img_names.at(0); std::cout << "\nX: " << this->x.at(0) << "\nY: " << this->y.at(0) << "\n"; } std::string Settings_Profile::getImgName(int a){ return this->img_names.at(a); } std::string Settings_Profile::getConfigName(){ return this->config_name; } std::string Settings_Profile::getBaseDir(){ return this->base_dir; } float Settings_Profile::getX(int a){ return this->x.at(a); } float Settings_Profile::getY(int a){ return this->y.at(a); } std::string Settings_Profile::getProcessName(){ return this->process_name; } void Settings_Profile::setProcessName(std::string name){ this->process_name = name; } int Settings_Profile::getImgCount(){ return this->img_names.size(); } void Settings_Profile::setDefaultRes(int x, int y){ this->default_res_x = x; this->default_res_y = y; } int Settings_Profile::getDresY(){ return this->default_res_y; } int Settings_Profile::getDResX(){ return this->default_res_x; } void Settings_Profile::addThreshold(float threshold){ this->threshold.push_back(threshold); } float Settings_Profile::getThresholdAt(int a){ return this->threshold.at(a); }<|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <iostream> #include <string> using namespace std; int main() { while(1) { string path; getline(cin, path); cv::Mat input = cv::imread(path+".jpg"); cv::Mat hsv_filtered15;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::Mat hsv; cv::Mat output; cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv,cv::Scalar(0,120,97),cv::Scalar(13,255,255),hsv_filtered15); cv::inRange(hsv,cv::Scalar(175,120,97),cv::Scalar(180,255,255),hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,output); cv::imwrite(path+"BINARY"+".jpg",output); } return 0; } <commit_msg>dbeug<commit_after>#include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <iostream> #include <string> using namespace std; int main() { while(1) { string path; getline(cin, path); cv::Mat input = cv::imread(path+".jpg"); cv::Mat hsv_filtered15;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::Mat hsv; cv::Mat output; cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv,cv::Scalar(0,89,97),cv::Scalar(13,255,255),hsv_filtered15); cv::inRange(hsv,cv::Scalar(175,89,97),cv::Scalar(180,255,255),hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,output); cv::imwrite(path+"BINARY"+".jpg",output); } return 0; } <|endoftext|>
<commit_before>/* * opencog/atomspace/AtomSpace.cc * * Copyright (c) 2008-2010 OpenCog Foundation * Copyright (c) 2009, 2013 Linas Vepstas * 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 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 <string> #include <iostream> #include <fstream> #include <list> #include <stdlib.h> #include <boost/bind.hpp> #include <opencog/atomspace/ClassServer.h> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/Node.h> // #include <opencog/atoms/bind/DeleteLink.h> #include <opencog/atomspace/types.h> #include <opencog/util/Logger.h> #include <opencog/util/oc_assert.h> #include "AtomSpace.h" //#define DPRINTF printf #define DPRINTF(...) using std::string; using std::cerr; using std::cout; using std::endl; using std::min; using std::max; using namespace opencog; // ==================================================================== AtomSpace::AtomSpace(AtomSpace* parent) : atomTable(parent? &parent->atomTable : NULL, this), bank(atomTable), backing_store(NULL) { } AtomSpace::~AtomSpace() { // Be sure to disconnect the attention bank signals before the // atom table destructor runs. XXX FIXME yes this is an ugly hack. bank.shutdown(); } AtomSpace::AtomSpace(const AtomSpace&) : atomTable(NULL), bank(atomTable), backing_store(NULL) { throw opencog::RuntimeException(TRACE_INFO, "AtomSpace - Cannot copy an object of this class"); } AtomSpace& AtomSpace::operator=(const AtomSpace&) { throw opencog::RuntimeException(TRACE_INFO, "AtomSpace - Cannot copy an object of this class"); } // ==================================================================== void AtomSpace::registerBackingStore(BackingStore *bs) { backing_store = bs; } void AtomSpace::unregisterBackingStore(BackingStore *bs) { if (bs == backing_store) backing_store = NULL; } // ==================================================================== Handle AtomSpace::add_atom(AtomPtr atom, bool async) { // Is this atom already in the atom table? Handle hexist(atomTable.getHandle(atom)); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. Type t = atom->getType(); if (backing_store and not backing_store->ignoreType(t)) { Handle ha(atom); Handle hb(backing_store->getAtom(ha)); if (hb.value() != Handle::UNDEFINED.value()) { return atomTable.add(hb, async); } } // If we are here, neither the AtomTable nor backing store know // about this atom. Just add it. If it is a DeleteLink, then the // addition will fail. Deal with it. Handle rh; try { rh = atomTable.add(atom, async); } catch (const DeleteException& ex) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. if (backing_store) // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return rh; } Handle AtomSpace::add_node(Type t, const string& name, bool async) { // Is this atom already in the atom table? Handle hexist(atomTable.getHandle(t, name)); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { NodePtr n(backing_store->getNode(t, name.c_str())); if (n) return atomTable.add(n, async); } // If we are here, neither the AtomTable nor backing store know about // this atom. Just add it. return atomTable.add(createNode(t, name), async); } Handle AtomSpace::get_node(Type t, const string& name) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, name); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { NodePtr n(backing_store->getNode(t, name.c_str())); if (n) { return atomTable.add(n, false); } } // If we are here, nobody knows about this. return Handle::UNDEFINED; } Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, outgoing); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { // If any of the outgoing set is ignorable, we will not // fetch the thing from the backing store. if (not std::any_of(outgoing.begin(), outgoing.end(), [this](Handle ho) { return backing_store->ignoreAtom(ho); })) { LinkPtr l(backing_store->getLink(t, outgoing)); if (l) { // Put the atom into the atomtable, so it gets placed // in indices, so we can find it quickly next time. return atomTable.add(l, async); } } } // If we are here, neither the AtomTable nor backing store know // about this atom. Just add it. If it is a DeleteLink, then the // addition will fail. Deal with it. Handle rh; try { rh = atomTable.add(createLink(t, outgoing), async); } catch (const DeleteException& ex) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. if (backing_store) // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return rh; } Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, outgoing); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { // If any of the outgoing set is ignorable, we will not // fetch the thing from the backing store. if (not std::any_of(outgoing.begin(), outgoing.end(), [this](Handle ho) { return backing_store->ignoreAtom(ho); })) { LinkPtr l(backing_store->getLink(t, outgoing)); if (l) { // Register the atom with the atomtable (so it gets placed in // indices) return atomTable.add(l, false); } } } // If we are here, nobody knows about this. return Handle::UNDEFINED; } void AtomSpace::store_atom(Handle h) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); backing_store->storeAtom(h); } Handle AtomSpace::fetch_atom(Handle h) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); // OK, we have to handle three distinct cases. // 1) If atom table already knows about this uuid or atom, then // this function returns the atom-table's version of the atom. // In particular, no attempt is made to reconcile the possibly // differing truth values in the atomtable vs. backing store. // 2) If the handle h holds a UUID but no atom pointer, then get // the corresponding atom from storage, and add it to the atom // table. // 3) If the handle h contains a pointer to an atom (that is not // in the atom table), then assume that atom is from some previous // (recursive) query, and add it to the atomtable. // For both case 2 & 3, if the atom is a link, then it's outgoing // set is fetched as well, as currently, a link cannot be added to // the atomtable, unless all of its outgoing set already is in the // atomtable. // Case 1: Handle hb(atomTable.getHandle(h)); if (atomTable.holds(hb)) return hb; // Case 2 & 3: // If we don't have the atom for this UUID, then go get it. if (NULL == h.operator->()) { AtomPtr a(backing_store->getAtom(h)); // If we still don't have an atom, then the requested UUID // was "insane", that is, unknown by either the atom table // (case 1) or the backend. if (NULL == a.operator->()) throw RuntimeException(TRACE_INFO, "Asked backend for an unknown handle; UUID=%lu\n", h.value()); h = a; } // For links, must perform a recursive fetch, as otherwise // the atomTable.add() below will throw an error. LinkPtr l(LinkCast(h)); if (l) { const HandleSeq& ogs = l->getOutgoingSet(); size_t arity = ogs.size(); for (size_t i=0; i<arity; i++) { Handle oh(fetch_atom(ogs[i])); if (oh != ogs[i]) throw RuntimeException(TRACE_INFO, "Unexpected handle mismatch! Expected %lu got %lu\n", ogs[i].value(), oh.value()); } } return atomTable.add(h, false); } Handle AtomSpace::fetch_atom(UUID uuid) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); // OK, we have to handle three distinct cases. // 1) If atom table already knows about this uuid or atom, then // this function returns the atom-table's version of the atom. // In particular, no attempt is made to reconcile the possibly // differing truth values in the atomtable vs. backing store. // 2) If the handle h holds a UUID but no atom pointer, then get // the corresponding atom from storage, and add it to the atom // table. // 3) If the handle h contains a pointer to an atom (that is not // in the atom table), then assume that atom is from some previous // (recursive) query, and add it to the atomtable. // For both case 2 & 3, if the atom is a link, then it's outgoing // set is fetched as well, as currently, a link cannot be added to // the atomtable, unless all of its outgoing set already is in the // atomtable. // Case 1: Handle hb(atomTable.getHandle(uuid)); if (atomTable.holds(hb)) return hb; // Case 2 & 3: // We don't have the atom for this UUID, then go get it. Handle h; // xxxxxxxxxxxxxxxxxxxxxx // Handle h(uuid); AtomPtr a(backing_store->getAtom(h)); // If we still don't have an atom, then the requested UUID // was "insane", that is, unknown by either the atom table // (case 1) or the backend. if (NULL == a.operator->()) throw RuntimeException(TRACE_INFO, "Asked backend for an unknown handle; UUID=%lu\n", uuid); h = a; // For links, must perform a recursive fetch, as otherwise // the atomTable.add() below will throw an error. LinkPtr l(LinkCast(h)); if (l) { const HandleSeq& ogs = l->getOutgoingSet(); size_t arity = ogs.size(); for (size_t i=0; i<arity; i++) { Handle oh(fetch_atom(ogs[i])); if (oh != ogs[i]) throw RuntimeException(TRACE_INFO, "Unexpected handle mismatch! Expected %lu got %lu\n", ogs[i].value(), oh.value()); } } return atomTable.add(h, false); } Handle AtomSpace::get_atom(Handle h) { Handle he(atomTable.getHandle(h)); if (he) return he; if (backing_store) return fetch_atom(h); return Handle::UNDEFINED; } Handle AtomSpace::get_atom(UUID uuid) { Handle he(atomTable.getHandle(uuid)); if (he) return he; if (backing_store) return fetch_atom(uuid); return Handle::UNDEFINED; } Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); h = get_atom(h); if (Handle::UNDEFINED == h) return Handle::UNDEFINED; // Get everything from the backing store. HandleSeq iset = backing_store->getIncomingSet(h); size_t isz = iset.size(); for (size_t i=0; i<isz; i++) { Handle hi(iset[i]); if (recursive) { fetch_incoming_set(hi, true); } else { get_atom(hi); } } return h; } bool AtomSpace::remove_atom(Handle h, bool recursive) { if (backing_store) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return 0 < atomTable.extract(h, recursive).size(); } void AtomSpace::clear() { std::vector<Handle> allAtoms; atomTable.getHandlesByType(back_inserter(allAtoms), ATOM, true, false); DPRINTF("atoms in allAtoms: %lu\n", allAtoms.size()); Logger::Level save = logger().getLevel(); logger().setLevel(Logger::DEBUG); // XXX FIXME TODO This is a stunningly inefficient way to clear the // atomspace! This will take minutes on any decent-sized atomspace! std::vector<Handle>::iterator i; for (i = allAtoms.begin(); i != allAtoms.end(); ++i) { purge_atom(*i, true); } allAtoms.clear(); atomTable.getHandlesByType(back_inserter(allAtoms), ATOM, true, false); assert(allAtoms.size() == 0); logger().setLevel(save); } namespace std { ostream& operator<<(ostream& out, const opencog::AtomSpace& as) { list<opencog::Handle> results; as.get_handles_by_type(back_inserter(results), opencog::ATOM, true); for (const opencog::Handle& h : results) if (h->getIncomingSetSize() == 0) out << h->toString() << endl; return out; } } // namespace std <commit_msg>Still broken for persistence; take another small step.<commit_after>/* * opencog/atomspace/AtomSpace.cc * * Copyright (c) 2008-2010 OpenCog Foundation * Copyright (c) 2009, 2013 Linas Vepstas * 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 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 <string> #include <iostream> #include <fstream> #include <list> #include <stdlib.h> #include <boost/bind.hpp> #include <opencog/atomspace/ClassServer.h> #include <opencog/atomspace/Link.h> #include <opencog/atomspace/Node.h> // #include <opencog/atoms/bind/DeleteLink.h> #include <opencog/atomspace/types.h> #include <opencog/util/Logger.h> #include <opencog/util/oc_assert.h> #include "AtomSpace.h" //#define DPRINTF printf #define DPRINTF(...) using std::string; using std::cerr; using std::cout; using std::endl; using std::min; using std::max; using namespace opencog; // ==================================================================== AtomSpace::AtomSpace(AtomSpace* parent) : atomTable(parent? &parent->atomTable : NULL, this), bank(atomTable), backing_store(NULL) { } AtomSpace::~AtomSpace() { // Be sure to disconnect the attention bank signals before the // atom table destructor runs. XXX FIXME yes this is an ugly hack. bank.shutdown(); } AtomSpace::AtomSpace(const AtomSpace&) : atomTable(NULL), bank(atomTable), backing_store(NULL) { throw opencog::RuntimeException(TRACE_INFO, "AtomSpace - Cannot copy an object of this class"); } AtomSpace& AtomSpace::operator=(const AtomSpace&) { throw opencog::RuntimeException(TRACE_INFO, "AtomSpace - Cannot copy an object of this class"); } // ==================================================================== void AtomSpace::registerBackingStore(BackingStore *bs) { backing_store = bs; } void AtomSpace::unregisterBackingStore(BackingStore *bs) { if (bs == backing_store) backing_store = NULL; } // ==================================================================== Handle AtomSpace::add_atom(AtomPtr atom, bool async) { // Is this atom already in the atom table? Handle hexist(atomTable.getHandle(atom)); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. Type t = atom->getType(); if (backing_store and not backing_store->ignoreType(t)) { Handle ha(atom); Handle hb(backing_store->getAtom(ha)); if (hb.value() != Handle::UNDEFINED.value()) { return atomTable.add(hb, async); } } // If we are here, neither the AtomTable nor backing store know // about this atom. Just add it. If it is a DeleteLink, then the // addition will fail. Deal with it. Handle rh; try { rh = atomTable.add(atom, async); } catch (const DeleteException& ex) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. if (backing_store) // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return rh; } Handle AtomSpace::add_node(Type t, const string& name, bool async) { // Is this atom already in the atom table? Handle hexist(atomTable.getHandle(t, name)); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { NodePtr n(backing_store->getNode(t, name.c_str())); if (n) return atomTable.add(n, async); } // If we are here, neither the AtomTable nor backing store know about // this atom. Just add it. return atomTable.add(createNode(t, name), async); } Handle AtomSpace::get_node(Type t, const string& name) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, name); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { NodePtr n(backing_store->getNode(t, name.c_str())); if (n) { return atomTable.add(n, false); } } // If we are here, nobody knows about this. return Handle::UNDEFINED; } Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, outgoing); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { // If any of the outgoing set is ignorable, we will not // fetch the thing from the backing store. if (not std::any_of(outgoing.begin(), outgoing.end(), [this](Handle ho) { return backing_store->ignoreAtom(ho); })) { LinkPtr l(backing_store->getLink(t, outgoing)); if (l) { // Put the atom into the atomtable, so it gets placed // in indices, so we can find it quickly next time. return atomTable.add(l, async); } } } // If we are here, neither the AtomTable nor backing store know // about this atom. Just add it. If it is a DeleteLink, then the // addition will fail. Deal with it. Handle rh; try { rh = atomTable.add(createLink(t, outgoing), async); } catch (const DeleteException& ex) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. if (backing_store) // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return rh; } Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing) { // Is this atom already in the atom table? Handle hexist = atomTable.getHandle(t, outgoing); if (hexist) return hexist; // If we are here, the AtomTable does not yet know about this atom. // Maybe the backing store knows about this atom. if (backing_store and not backing_store->ignoreType(t)) { // If any of the outgoing set is ignorable, we will not // fetch the thing from the backing store. if (not std::any_of(outgoing.begin(), outgoing.end(), [this](Handle ho) { return backing_store->ignoreAtom(ho); })) { LinkPtr l(backing_store->getLink(t, outgoing)); if (l) { // Register the atom with the atomtable (so it gets placed in // indices) return atomTable.add(l, false); } } } // If we are here, nobody knows about this. return Handle::UNDEFINED; } void AtomSpace::store_atom(Handle h) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); backing_store->storeAtom(h); } Handle AtomSpace::fetch_atom(Handle h) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); if (NULL == h) return h; // We deal with two distinct cases. // 1) If atom table already knows about this atom, then this // function returns the atom-table's version of the atom. // In particular, no attempt is made to reconcile the possibly // differing truth values in the atomtable vs. backing store. // Why? Because it is likely that the user plans to over-write // what is in the backend. // 2) If (1) does not hold, i.e. the atom is not in this table, nor // it's environs, then assume that atom is from some previous // (recursive) query; do fetch it from backing store (i.e. fetch // the TV) and add it to the atomtable. // For case 2, if the atom is a link, then it's outgoing set is // fetched as well, as currently, a link cannot be added to the // atomtable, unless all of its outgoing set already is in the // atomtable. // Case 1: Handle hb(atomTable.getHandle(h)); if (atomTable.holds(hb)) return hb; // Case 2: // This atom is not yet in any (this??) atomspace; go get it. if (NULL == h->getAtomTable()) { AtomPtr a(backing_store->getAtom(h)); // If we still don't have an atom, then the requested UUID // was "insane", that is, unknown by either the atom table // (case 1) or the backend. if (NULL == a.operator->()) throw RuntimeException(TRACE_INFO, "Asked backend for an atom %s\n", h->toString().c_str()); h = a; } // For links, must perform a recursive fetch, as otherwise // the atomTable.add() below will throw an error. LinkPtr l(LinkCast(h)); if (l) { bool changed = false; HandleSeq ogs = l->getOutgoingSet(); size_t arity = ogs.size(); for (size_t i=0; i<arity; i++) { Handle oh(fetch_atom(ogs[i])); if (oh != ogs[i]) { changed = true; ogs[i] = oh; } } if (changed) h = createLink(h->getType(), ogs, h->getTruthValue(), h->getAttentionValue()); } return atomTable.add(h, false); } Handle AtomSpace::fetch_atom(UUID uuid) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); // OK, we have to handle three distinct cases. // 1) If atom table already knows about this uuid, then this // function returns the atom-table's version of the atom. // In particular, no attempt is made to reconcile the possibly // differing truth values in the atomtable vs. backing store. // 2) Else, get the atom corresponding to the UUID from storage. // 3) If the handle h contains a pointer to an atom (that is not // in the atom table), then assume that atom is from some previous // (recursive) query, and add it to the atomtable. // For both case 2 & 3, if the atom is a link, then it's outgoing // set is fetched as well, as currently, a link cannot be added to // the atomtable, unless all of its outgoing set already is in the // atomtable. // Case 1: Handle hb(atomTable.getHandle(uuid)); if (atomTable.holds(hb)) return hb; // Case 2 & 3: // We don't have the atom for this UUID, then go get it. Handle h; // xxxxxxxxxxxxxxxxxxxxxx // Handle h(uuid); AtomPtr a(backing_store->getAtom(h)); // If we still don't have an atom, then the requested UUID // was "insane", that is, unknown by either the atom table // (case 1) or the backend. if (NULL == a.operator->()) throw RuntimeException(TRACE_INFO, "Asked backend for an unknown handle; UUID=%lu\n", uuid); h = a; // For links, must perform a recursive fetch, as otherwise // the atomTable.add() below will throw an error. LinkPtr l(LinkCast(h)); if (l) { const HandleSeq& ogs = l->getOutgoingSet(); size_t arity = ogs.size(); for (size_t i=0; i<arity; i++) { Handle oh(fetch_atom(ogs[i])); if (oh != ogs[i]) throw RuntimeException(TRACE_INFO, "Unexpected handle mismatch! Expected %lu got %lu\n", ogs[i].value(), oh.value()); } } return atomTable.add(h, false); } Handle AtomSpace::get_atom(Handle h) { Handle he(atomTable.getHandle(h)); if (he) return he; if (backing_store) return fetch_atom(h); return Handle::UNDEFINED; } Handle AtomSpace::get_atom(UUID uuid) { Handle he(atomTable.getHandle(uuid)); if (he) return he; if (backing_store) return fetch_atom(uuid); return Handle::UNDEFINED; } Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive) { if (NULL == backing_store) throw RuntimeException(TRACE_INFO, "No backing store"); h = get_atom(h); if (Handle::UNDEFINED == h) return Handle::UNDEFINED; // Get everything from the backing store. HandleSeq iset = backing_store->getIncomingSet(h); size_t isz = iset.size(); for (size_t i=0; i<isz; i++) { Handle hi(iset[i]); if (recursive) { fetch_incoming_set(hi, true); } else { get_atom(hi); } } return h; } bool AtomSpace::remove_atom(Handle h, bool recursive) { if (backing_store) { // Atom deletion has not been implemented in the backing store // This is a major to-do item. // Under construction .... throw RuntimeException(TRACE_INFO, "Not implemented!!!"); } return 0 < atomTable.extract(h, recursive).size(); } void AtomSpace::clear() { std::vector<Handle> allAtoms; atomTable.getHandlesByType(back_inserter(allAtoms), ATOM, true, false); DPRINTF("atoms in allAtoms: %lu\n", allAtoms.size()); Logger::Level save = logger().getLevel(); logger().setLevel(Logger::DEBUG); // XXX FIXME TODO This is a stunningly inefficient way to clear the // atomspace! This will take minutes on any decent-sized atomspace! std::vector<Handle>::iterator i; for (i = allAtoms.begin(); i != allAtoms.end(); ++i) { purge_atom(*i, true); } allAtoms.clear(); atomTable.getHandlesByType(back_inserter(allAtoms), ATOM, true, false); assert(allAtoms.size() == 0); logger().setLevel(save); } namespace std { ostream& operator<<(ostream& out, const opencog::AtomSpace& as) { list<opencog::Handle> results; as.get_handles_by_type(back_inserter(results), opencog::ATOM, true); for (const opencog::Handle& h : results) if (h->getIncomingSetSize() == 0) out << h->toString() << endl; return out; } } // namespace std <|endoftext|>
<commit_before><commit_msg>lp: added detection of problem type<commit_after><|endoftext|>
<commit_before>/** @file Rule/Defs.hpp @brief Rule definitions. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_RULE_DEFS_HPP_ #define HORD_RULE_DEFS_HPP_ #include <Hord/config.hpp> #include <Hord/Object/Defs.hpp> #include <Hord/Hive/Defs.hpp> namespace Hord { namespace Rule { // Forward declarations class Unit; // external struct type_info; /** @addtogroup object @{ */ /** @addtogroup rule @{ */ /** Rule ID. @note This type is only to telegraph intent in functions; it is entirely equivalent to @c Object::ID. @sa Object::ID, Hive::ID, Node::ID */ using ID = Object::ID; /** Rule type. */ using Type = uint32_t; /** Standard rule types. @note Values in <code>[0, 8]</code> are reserved for standard types (@c 0 is invalid). Userspace may specify further types in the range <code>[9, (2 ^ 32) - 1]</code>. @sa Rule::Unit */ enum class StandardTypes : Rule::Type { /** Special non-type. @note This type defines the <em>lack</em> of rule/structure. %Rules cannot be registered with this type. */ None = 0, /** Composition of types. @sa CompositionRule */ Composition, /** Delimited set of rules. @sa DelimitedSetRule */ DelimitedSet, /** Value matcher. @sa MatchRule */ Match, /** Number limiter. @sa LimitRule */ Limit, /** List. @sa ListRule */ List, /** Date-time. @sa DateTimeRule */ DateTime, /** Timespan. @sa TimespanRule */ Timespan, /// @{ /** Reserved types (@c 8). */ Reserved1, ReservedFirst = Reserved1, ReservedLast = Reserved1 /// @} }; static_assert( 8 == static_cast<Rule::Type>(StandardTypes::ReservedLast), "StandardTypes must reserve up to 8" ); /** Rule type info. */ struct type_info final { /** %Rule type. @sa StandardTypes */ Type const type; /** Permitted Data::FieldTypes. @note This should be a nonzero combination of Data::FieldTypes. @sa FieldType */ uint8_t const permitted_types; /** Construct a rule of this type. @returns - The constructed rule; or - @c nullptr if construction failed. @param owner Owner ID. @param id %Object ID. */ Unit* (&construct)( Hive::ID const owner, Rule::ID const id ) noexcept; }; /** @} */ // end of doc-group rule /** @} */ // end of doc-group object } // namespace Rule } // namespace Hord #endif // HORD_RULE_DEFS_HPP_ <commit_msg>Rule/Defs: corrected type_info::construct() params; doc tidy.¹<commit_after>/** @file Rule/Defs.hpp @brief Rule definitions. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_RULE_DEFS_HPP_ #define HORD_RULE_DEFS_HPP_ #include <Hord/config.hpp> #include <Hord/Object/Defs.hpp> namespace Hord { namespace Rule { // Forward declarations class Unit; // external struct type_info; /** @addtogroup object @{ */ /** @addtogroup rule @{ */ /** Rule ID. @note This type is only to telegraph intent in functions; it is entirely equivalent to @c Object::ID. @sa Object::ID, Hive::ID, Node::ID */ using ID = Object::ID; /** Rule type. */ using Type = uint32_t; /** Standard rule types. @note Values in <code>[0, 8]</code> are reserved for standard types (@c 0 is invalid). Userspace may specify further types in the range <code>[9, (2 ^ 32) - 1]</code>. @sa Rule::Unit */ enum class StandardTypes : Rule::Type { /** Special non-type. @note This type defines the <em>lack</em> of rule/structure. %Rules cannot be registered with this type. */ None = 0, /** Composition of types. @sa CompositionRule */ Composition, /** Delimited set of rules. @sa DelimitedSetRule */ DelimitedSet, /** Value matcher. @sa MatchRule */ Match, /** Number limiter. @sa LimitRule */ Limit, /** List. @sa ListRule */ List, /** Date-time. @sa DateTimeRule */ DateTime, /** Timespan. @sa TimespanRule */ Timespan, /// @{ /** Reserved types (@c 8). */ Reserved1, ReservedFirst = Reserved1, ReservedLast = Reserved1 /// @} }; static_assert( 8 == static_cast<Rule::Type>(StandardTypes::ReservedLast), "StandardTypes must reserve up to 8" ); /** Rule type info. */ struct type_info final { /** %Rule type. @sa Rule::StandardTypes */ Type const type; /** Permitted field types. @note This should be a nonzero combination of Data::FieldTypes. @sa Data::FieldType */ uint8_t const permitted_types; /** Construct a rule of this type. @returns - The constructed rule; or - @c nullptr if construction failed. @param id Object %ID. @param parent Parent %ID. */ Unit* (&construct)( Rule::ID const id, Object::ID const parent ) noexcept; }; /** @} */ // end of doc-group rule /** @} */ // end of doc-group object } // namespace Rule } // namespace Hord #endif // HORD_RULE_DEFS_HPP_ <|endoftext|>
<commit_before>#ifndef COBALT_COM_STD_HPP_INCLUDED #define COBALT_COM_STD_HPP_INCLUDED #pragma once // Classes in this file: // equatable // comparable // hashable // copyable // coder // decodable // encodable // codable #include <cobalt/com/error.hpp> #include <cobalt/utility/intrusive.hpp> #include <cobalt/utility/uid.hpp> namespace cobalt { namespace com { DECLARE_INTERFACE(com, equatable) struct equatable : any { virtual bool equal(any*) const noexcept = 0; }; DECLARE_INTERFACE(com, comparable) struct comparable : equatable { virtual bool less(any*) const noexcept = 0; }; DECLARE_INTERFACE(com, hashable) struct hashable : equatable { virtual size_t hash_value() const noexcept = 0; }; DECLARE_INTERFACE(com, copyable) struct copyable : any { virtual any* copy() const noexcept = 0; }; enum class coding_mode { encoding, decoding }; DECLARE_INTERFACE(com, coder) struct coder : any { virtual coding_mode mode() const noexcept = 0; virtual bool encode_bool(const char* name, bool& value) noexcept = 0; virtual bool encode_int(const char* name, int& value) noexcept = 0; virtual bool encode_int_range(const char* name, int& value, int min, int max) noexcept = 0; virtual bool encode_float(const char* name, float& value) noexcept = 0; virtual bool encode_float_range(const char* name, float& value, float min, float max, float resolution) noexcept = 0; virtual bool encode_bytes(const char* name, void* data, size_t size_in_bytes) noexcept = 0; }; DECLARE_INTERFACE(com, decodable) struct decodable : any { virtual void init(coder*) noexcept = 0; }; DECLARE_INTERFACE(com, encodable) struct encodable : any { virtual void encode(coder*) const noexcept = 0; }; DECLARE_INTERFACE(com, codable) struct codable : decodable, encodable { }; } // namespace com } // namespace cobalt #endif // COBALT_COM_STD_HPP_INCLUDED <commit_msg>Some changes in com::std.<commit_after>#ifndef COBALT_COM_STD_HPP_INCLUDED #define COBALT_COM_STD_HPP_INCLUDED #pragma once // Classes in this file: // equatable // comparable // hashable // copyable // clonable // decoder // encoder // decodable // encodable #include <cobalt/com/core.hpp> #include <system_error> namespace cobalt { namespace com { DECLARE_INTERFACE(com, equatable) struct equatable : any { virtual bool equals(any*) const noexcept = 0; }; DECLARE_INTERFACE(com, comparable) struct comparable : equatable { virtual bool less(any*) const noexcept = 0; }; DECLARE_INTERFACE(com, hashable) struct hashable : equatable { virtual size_t hash_value() const noexcept = 0; }; DECLARE_INTERFACE(com, copyable) struct copyable : any { virtual ref<any> copy() const noexcept = 0; }; DECLARE_INTERFACE(com, clonable) struct clonable : copyable { virtual ref<any> clone() const noexcept = 0; }; DECLARE_INTERFACE(com, decoder) struct decoder : any { virtual void decode(const char* key, bool& value) noexcept = 0; virtual void decode(const char* key, int& value) noexcept = 0; virtual void decode(const char* key, int& value, int min, int max) noexcept = 0; virtual void decode(const char* key, float& value) noexcept = 0; virtual void decode(const char* key, float& value, float min, float max, float resolution) noexcept = 0; virtual void decode(const char* key, void* data, size_t size) noexcept = 0; }; DECLARE_INTERFACE(com, encoder) struct encoder : any { virtual void encode(const char* key, bool& value) noexcept = 0; virtual void encode(const char* key, int& value) noexcept = 0; virtual void encode(const char* key, int& value, int min, int max) noexcept = 0; virtual void encode(const char* key, float& value) noexcept = 0; virtual void encode(const char* key, float& value, float min, float max, float resolution) noexcept = 0; virtual void encode(const char* key, void* data, size_t size) noexcept = 0; }; DECLARE_INTERFACE(com, decodable) struct decodable : any { virtual void init(decoder*, std::error_code& ec) noexcept = 0; }; DECLARE_INTERFACE(com, encodable) struct encodable : any { virtual void encode(encoder*, std::error_code& ec) const noexcept = 0; }; } // namespace com } // namespace cobalt #endif // COBALT_COM_STD_HPP_INCLUDED <|endoftext|>
<commit_before>#pragma once #include "util.hpp" #include <iostream> #include <memory> #include <type_traits> namespace imu { /** * A type that can hold any other value. This could be replaced with * std::any, once it's not experimental anymore. * */ struct value { typedef std::shared_ptr<value> p; inline value() : pad(nullptr) {} template<typename T> inline value(const T& v) : pad(new value_pad<typename std::decay<const T>::type>(v)) {} inline value(const value& cpy) : pad(cpy.pad ? cpy.pad->clone() : nullptr) {} inline value(value&& other) : pad(other.pad) { other.pad = nullptr; } inline ~value() { delete pad; } inline value& operator= (const value& cpy) { if (cpy.pad) { delete pad; pad = cpy.pad->clone(); } return *this; } inline value& operator= (value&& other) { std::swap(pad, other.pad); delete other.pad; other.pad = nullptr; return *this; } inline bool is_set() const { return (bool) pad; } inline operator bool() const { return is_set(); } template<typename T> inline const T& get() const { typedef typename std::decay<const T>::type value_type; typedef value_pad<value_type> pad_type; if (typeid(value_type) != type()) { throw bad_value_cast(); } return dynamic_cast<const pad_type*>(pad)->value; } inline friend bool operator== (const value& l, const value& r) { return l.pad->equiv(r.pad); } template<typename T> inline friend bool operator== (const value& l, const T& r) { return l.get<T>() == r; } inline const std::type_info& type() const { return pad->type(); } struct value_pad_base { typedef std::unique_ptr<value_pad_base> p; virtual ~value_pad_base() {} virtual value_pad_base* clone() const = 0; virtual bool equiv(const value_pad_base* other) const = 0; virtual const std::type_info& type() const = 0; }; template<typename T> struct value_pad : public value_pad_base { T value; value_pad(const T& v) : value(v) {} value_pad(const T&& v) : value(static_cast<T&&>(v)) {} value_pad_base* clone() const { return new value_pad(value); } bool equiv(const value_pad_base* other) const { return value == dynamic_cast<const value_pad*>(other)->value; } const std::type_info& type() const { return typeid(T); } }; struct bad_value_cast : public std::bad_cast { virtual const char* what() const noexcept { return "Bad cast of imu::value to concrete type"; } }; const value_pad_base* pad; }; template<typename T> inline const T& value_cast(const value& v) { return v.get<T>(); } template<typename T> inline const T& value_cast(const value::p& v) { return v->get<T>(); } template<> inline const value& value_cast<value>(const value& v) { return v; } template<typename T, typename X> inline const T& value_cast(const X& x) { return static_cast<const T&>(x); } } <commit_msg>Use static pointer cast for std::shared_ptr<commit_after>#pragma once #include "util.hpp" #include <iostream> #include <memory> #include <type_traits> namespace imu { /** * A type that can hold any other value. This could be replaced with * std::any, once it's not experimental anymore. * */ struct value { typedef std::shared_ptr<value> p; inline value() : pad(nullptr) {} template<typename T> inline value(const T& v) : pad(new value_pad<typename std::decay<const T>::type>(v)) {} inline value(const value& cpy) : pad(cpy.pad ? cpy.pad->clone() : nullptr) {} inline value(value&& other) : pad(other.pad) { other.pad = nullptr; } inline ~value() { delete pad; } inline value& operator= (const value& cpy) { if (cpy.pad) { delete pad; pad = cpy.pad->clone(); } return *this; } inline value& operator= (value&& other) { std::swap(pad, other.pad); delete other.pad; other.pad = nullptr; return *this; } inline bool is_set() const { return (bool) pad; } inline operator bool() const { return is_set(); } template<typename T> inline const T& get() const { typedef typename std::decay<const T>::type value_type; typedef value_pad<value_type> pad_type; if (typeid(value_type) != type()) { throw bad_value_cast(); } return dynamic_cast<const pad_type*>(pad)->value; } inline friend bool operator== (const value& l, const value& r) { return l.pad->equiv(r.pad); } template<typename T> inline friend bool operator== (const value& l, const T& r) { return l.get<T>() == r; } inline const std::type_info& type() const { return pad->type(); } struct value_pad_base { typedef std::unique_ptr<value_pad_base> p; virtual ~value_pad_base() {} virtual value_pad_base* clone() const = 0; virtual bool equiv(const value_pad_base* other) const = 0; virtual const std::type_info& type() const = 0; }; template<typename T> struct value_pad : public value_pad_base { T value; value_pad(const T& v) : value(v) {} value_pad(const T&& v) : value(static_cast<T&&>(v)) {} value_pad_base* clone() const { return new value_pad(value); } bool equiv(const value_pad_base* other) const { return value == dynamic_cast<const value_pad*>(other)->value; } const std::type_info& type() const { return typeid(T); } }; struct bad_value_cast : public std::bad_cast { virtual const char* what() const noexcept { return "Bad cast of imu::value to concrete type"; } }; const value_pad_base* pad; }; template<typename T> inline const T& value_cast(const value& v) { return v.get<T>(); } template<typename T> inline const T& value_cast(const value::p& v) { return v->get<T>(); } template<> inline const value& value_cast<value>(const value& v) { return v; } template<typename T, typename X> inline const T& value_cast(const X& x) { return static_cast<const T&>(x); } template<typename T, typename X> inline const T& value_cast(const std::shared_ptr<X>& x) { return std::static_pointer_cast<const T&>(x); } } <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 1998-2003 by Hans Meine */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* 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 VIGRA_MESHGRID_HXX #define VIGRA_MESHGRID_HXX #include "tinyvector.hxx" #include "diff2D.hxx" namespace vigra{ /** \addtogroup RangesAndPoints Two-dimensional Ranges and Points Specify a 2D position, extent, or rectangle. */ //@{ /********************************************************/ /* */ /* MeshGridAccessor */ /* */ /********************************************************/ /** Accessor for turning iteration over Diff2D into a mesh grid. The mesh grid concept is adapted from MATLAB. It is a two banded image (i.e. with 2D vector pixel type) whose first band contains the x-coordinates of the current pixel, and whose second band contains the y-coordinates. See \ref meshGrid() for more detailed documentation. */ struct MeshGridAccessor { /** the value_type of a mesh grid is a 2D vector */ typedef TinyVector<Diff2D::MoveX, 2> value_type; /** read the current data item */ template <class ITERATOR> value_type operator()(ITERATOR const & i) const { return value_type(i->x, i->y); } /** read the data item at an offset (can be 1D or 2D or higher order difference). */ template <class ITERATOR, class DIFFERENCE> value_type operator()(ITERATOR const & i, DIFFERENCE const & diff) const { return value_type(i->x+diff.x, i->y+diff.y); } }; /** Create a mesh grid for the specified rectangle. The mesh grid concept is adapted from MATLAB. It is a two banded image (i.e. with 2D vector pixel type) whose first band contains the x-coordinates of the current pixel, and whose second band contains the y-coordinates. If \a upperLeft is not the point (0,0), the mesh grid is translated relative to the pixel indices. <b> Declarations:</b> \code triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Diff2D upperLeft, Diff2D lowerRight); triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Rect2D const & r); \endcode <b>Usage:</b> \code #include <vigra/meshgrid.hxx> // create an image whose values are equal to each pixel's distance from the image center int width = 5, height = 7; int xc = width/2, yc = height/2; // the image center FImage dist(width, height); Point2D upperLeft(-xc, -yc); using namespace vigra::functor; transformImage(meshGrid(upperLeft, upperLeft+dist.size()), destImage(dist), norm(Arg1())); \endcode */ inline triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Diff2D upperLeft, Diff2D lowerRight) { return triple<Diff2D, Diff2D, MeshGridAccessor>(upperLeft, lowerRight, MeshGridAccessor()); } inline triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Rect2D const & r) { return triple<Diff2D, Diff2D, MeshGridAccessor>(r.upperLeft(), r.lowerRight(), MeshGridAccessor()); } }//namespace vigra //@} #endif //VIGRA_MESHGRID_HXX <commit_msg>fix wrongly capitalized #include and guess copyright of meshgrid.hxx<commit_after>/************************************************************************/ /* */ /* Copyright 2009 by Ullrich Kthe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* 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 VIGRA_MESHGRID_HXX #define VIGRA_MESHGRID_HXX #include "tinyvector.hxx" #include "diff2d.hxx" namespace vigra{ /** \addtogroup RangesAndPoints Two-dimensional Ranges and Points Specify a 2D position, extent, or rectangle. */ //@{ /********************************************************/ /* */ /* MeshGridAccessor */ /* */ /********************************************************/ /** Accessor for turning iteration over Diff2D into a mesh grid. The mesh grid concept is adapted from MATLAB. It is a two banded image (i.e. with 2D vector pixel type) whose first band contains the x-coordinates of the current pixel, and whose second band contains the y-coordinates. See \ref meshGrid() for more detailed documentation. */ struct MeshGridAccessor { /** the value_type of a mesh grid is a 2D vector */ typedef TinyVector<Diff2D::MoveX, 2> value_type; /** read the current data item */ template <class ITERATOR> value_type operator()(ITERATOR const & i) const { return value_type(i->x, i->y); } /** read the data item at an offset (can be 1D or 2D or higher order difference). */ template <class ITERATOR, class DIFFERENCE> value_type operator()(ITERATOR const & i, DIFFERENCE const & diff) const { return value_type(i->x+diff.x, i->y+diff.y); } }; /** Create a mesh grid for the specified rectangle. The mesh grid concept is adapted from MATLAB. It is a two banded image (i.e. with 2D vector pixel type) whose first band contains the x-coordinates of the current pixel, and whose second band contains the y-coordinates. If \a upperLeft is not the point (0,0), the mesh grid is translated relative to the pixel indices. <b> Declarations:</b> \code triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Diff2D upperLeft, Diff2D lowerRight); triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Rect2D const & r); \endcode <b>Usage:</b> \code #include <vigra/meshgrid.hxx> // create an image whose values are equal to each pixel's distance from the image center int width = 5, height = 7; int xc = width/2, yc = height/2; // the image center FImage dist(width, height); Point2D upperLeft(-xc, -yc); using namespace vigra::functor; transformImage(meshGrid(upperLeft, upperLeft+dist.size()), destImage(dist), norm(Arg1())); \endcode */ inline triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Diff2D upperLeft, Diff2D lowerRight) { return triple<Diff2D, Diff2D, MeshGridAccessor>(upperLeft, lowerRight, MeshGridAccessor()); } inline triple<Diff2D, Diff2D, MeshGridAccessor> meshGrid(Rect2D const & r) { return triple<Diff2D, Diff2D, MeshGridAccessor>(r.upperLeft(), r.lowerRight(), MeshGridAccessor()); } }//namespace vigra //@} #endif //VIGRA_MESHGRID_HXX <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OPTION_HPP__ #define __STOUT_OPTION_HPP__ #include <assert.h> #include <algorithm> #include <functional> #include <type_traits> #include <boost/functional/hash.hpp> #include <stout/none.hpp> #include <stout/some.hpp> template <typename T> class Option { public: static Option<T> none() { return Option<T>(); } static Option<T> some(const T& t) { return Option<T>(t); } Option() : state(NONE) {} Option(const T& _t) : state(SOME), t(_t) {} Option(T&& _t) : state(SOME), t(std::move(_t)) {} template < typename U, typename = typename std::enable_if< std::is_constructible<T, const U&>::value>::type> Option(const U& u) : state(SOME), t(u) {} Option(const None&) : state(NONE) {} template <typename U> Option(const _Some<U>& some) : state(SOME), t(some.t) {} template <typename U> Option(_Some<U>&& some) : state(SOME), t(std::move(some.t)) {} Option(const Option<T>& that) : state(that.state) { if (that.isSome()) { new (&t) T(that.t); } } Option(Option<T>&& that) noexcept(std::is_nothrow_move_constructible<T>::value) : state(std::move(that.state)) { if (that.isSome()) { new (&t) T(std::move(that.t)); } } ~Option() { if (isSome()) { t.~T(); } } Option<T>& operator=(const Option<T>& that) { if (this != &that) { if (isSome()) { t.~T(); } state = that.state; if (that.isSome()) { new (&t) T(that.t); } } return *this; } Option<T>& operator=(Option<T>&& that) noexcept(std::is_nothrow_move_constructible<T>::value) { if (this != &that) { if (isSome()) { t.~T(); } state = std::move(that.state); if (that.isSome()) { new (&t) T(std::move(that.t)); } } return *this; } bool isSome() const { return state == SOME; } bool isNone() const { return state == NONE; } const T& get() const & { assert(isSome()); return t; } T& get() & { assert(isSome()); return t; } T&& get() && { assert(isSome()); return std::move(t); } const T&& get() const && { assert(isSome()); return std::move(t); } const T* operator->() const { return &get(); } T* operator->() { return &get(); } // This must return a copy to avoid returning a reference to a temporary. T getOrElse(const T& _t) const { return isNone() ? _t : t; } bool operator==(const Option<T>& that) const { return (isNone() && that.isNone()) || (isSome() && that.isSome() && t == that.t); } bool operator!=(const Option<T>& that) const { return !(*this == that); } bool operator==(const T& that) const { return isSome() && t == that; } bool operator!=(const T& that) const { return !(*this == that); } private: enum State { SOME, NONE, }; State state; union { // We remove the const qualifier (if there is one) from T so that // we can initialize 't' from outside of the initializer list // using placement new. This is necessary because sometimes we // specialize 'Option' as such: 'Option<const T>'. typename std::remove_const<T>::type t; }; }; template <typename T> Option<T> min(const Option<T>& left, const Option<T>& right) { if (left.isSome() && right.isSome()) { return std::min(left.get(), right.get()); } else if (left.isSome()) { return left.get(); } else if (right.isSome()) { return right.get(); } else { return Option<T>::none(); } } template <typename T> Option<T> min(const Option<T>& left, const T& right) { return min(left, Option<T>(right)); } template <typename T> Option<T> min(const T& left, const Option<T>& right) { return min(Option<T>(left), right); } template <typename T> Option<T> max(const Option<T>& left, const Option<T>& right) { if (left.isSome() && right.isSome()) { return std::max(left.get(), right.get()); } else if (left.isSome()) { return left.get(); } else if (right.isSome()) { return right.get(); } else { return Option<T>::none(); } } template <typename T> Option<T> max(const Option<T>& left, const T& right) { return max(left, Option<T>(right)); } template <typename T> Option<T> max(const T& left, const Option<T>& right) { return max(Option<T>(left), right); } namespace std { template <typename T> struct hash<Option<T>> { typedef size_t result_type; typedef Option<T> argument_type; result_type operator()(const argument_type& option) const { size_t seed = 0; if (option.isSome()) { boost::hash_combine(seed, hash<T>()(option.get())); } return seed; } }; } // namespace std { #endif // __STOUT_OPTION_HPP__ <commit_msg>Avoided copying when possible in Option::getOrElse.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OPTION_HPP__ #define __STOUT_OPTION_HPP__ #include <assert.h> #include <algorithm> #include <functional> #include <type_traits> #include <boost/functional/hash.hpp> #include <stout/none.hpp> #include <stout/some.hpp> template <typename T> class Option { public: static Option<T> none() { return Option<T>(); } static Option<T> some(const T& t) { return Option<T>(t); } Option() : state(NONE) {} Option(const T& _t) : state(SOME), t(_t) {} Option(T&& _t) : state(SOME), t(std::move(_t)) {} template < typename U, typename = typename std::enable_if< std::is_constructible<T, const U&>::value>::type> Option(const U& u) : state(SOME), t(u) {} Option(const None&) : state(NONE) {} template <typename U> Option(const _Some<U>& some) : state(SOME), t(some.t) {} template <typename U> Option(_Some<U>&& some) : state(SOME), t(std::move(some.t)) {} Option(const Option<T>& that) : state(that.state) { if (that.isSome()) { new (&t) T(that.t); } } Option(Option<T>&& that) noexcept(std::is_nothrow_move_constructible<T>::value) : state(std::move(that.state)) { if (that.isSome()) { new (&t) T(std::move(that.t)); } } ~Option() { if (isSome()) { t.~T(); } } Option<T>& operator=(const Option<T>& that) { if (this != &that) { if (isSome()) { t.~T(); } state = that.state; if (that.isSome()) { new (&t) T(that.t); } } return *this; } Option<T>& operator=(Option<T>&& that) noexcept(std::is_nothrow_move_constructible<T>::value) { if (this != &that) { if (isSome()) { t.~T(); } state = std::move(that.state); if (that.isSome()) { new (&t) T(std::move(that.t)); } } return *this; } bool isSome() const { return state == SOME; } bool isNone() const { return state == NONE; } const T& get() const & { assert(isSome()); return t; } T& get() & { assert(isSome()); return t; } T&& get() && { assert(isSome()); return std::move(t); } const T&& get() const && { assert(isSome()); return std::move(t); } const T* operator->() const { return &get(); } T* operator->() { return &get(); } template <typename U> T getOrElse(U&& u) const & { return isNone() ? static_cast<T>(std::forward<U>(u)) : t; } template <typename U> T getOrElse(U&& u) && { return isNone() ? static_cast<T>(std::forward<U>(u)) : std::move(t); } bool operator==(const Option<T>& that) const { return (isNone() && that.isNone()) || (isSome() && that.isSome() && t == that.t); } bool operator!=(const Option<T>& that) const { return !(*this == that); } bool operator==(const T& that) const { return isSome() && t == that; } bool operator!=(const T& that) const { return !(*this == that); } private: enum State { SOME, NONE, }; State state; union { // We remove the const qualifier (if there is one) from T so that // we can initialize 't' from outside of the initializer list // using placement new. This is necessary because sometimes we // specialize 'Option' as such: 'Option<const T>'. typename std::remove_const<T>::type t; }; }; template <typename T> Option<T> min(const Option<T>& left, const Option<T>& right) { if (left.isSome() && right.isSome()) { return std::min(left.get(), right.get()); } else if (left.isSome()) { return left.get(); } else if (right.isSome()) { return right.get(); } else { return Option<T>::none(); } } template <typename T> Option<T> min(const Option<T>& left, const T& right) { return min(left, Option<T>(right)); } template <typename T> Option<T> min(const T& left, const Option<T>& right) { return min(Option<T>(left), right); } template <typename T> Option<T> max(const Option<T>& left, const Option<T>& right) { if (left.isSome() && right.isSome()) { return std::max(left.get(), right.get()); } else if (left.isSome()) { return left.get(); } else if (right.isSome()) { return right.get(); } else { return Option<T>::none(); } } template <typename T> Option<T> max(const Option<T>& left, const T& right) { return max(left, Option<T>(right)); } template <typename T> Option<T> max(const T& left, const Option<T>& right) { return max(Option<T>(left), right); } namespace std { template <typename T> struct hash<Option<T>> { typedef size_t result_type; typedef Option<T> argument_type; result_type operator()(const argument_type& option) const { size_t seed = 0; if (option.isSome()) { boost::hash_combine(seed, hash<T>()(option.get())); } return seed; } }; } // namespace std { #endif // __STOUT_OPTION_HPP__ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCylinderSource.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <math.h> #include "vtkCylinderSource.h" #include "vtkPoints.h" #include "vtkNormals.h" #include "vtkTCoords.h" vtkCylinderSource::vtkCylinderSource (int res) { this->Resolution = res; this->Height = 1.0; this->Radius = 0.5; this->Capping = 1; this->Center[0] = this->Center[1] = this->Center[2] = 0.0; } void vtkCylinderSource::Execute() { float angle= 2.0*3.141592654/this->Resolution; int numPolys, numPts; float xbot[3], tcbot[2], nbot[3]; float xtop[3], tctop[2], ntop[3]; float *center = this->Center; int i, idx; int pts[VTK_CELL_SIZE]; vtkPoints *newPoints; vtkNormals *newNormals; vtkTCoords *newTCoords; vtkCellArray *newPolys; vtkPolyData *output = this->GetOutput(); // // Set things up; allocate memory // if ( this->Capping ) { numPts = 4*this->Resolution; numPolys = this->Resolution + 2; } else { numPts = 2*this->Resolution; numPolys = this->Resolution; } newPoints = vtkPoints::New(); newPoints->Allocate(numPts); newNormals = vtkNormals::New(); newNormals->Allocate(numPts); newTCoords = vtkTCoords::New(); newTCoords->Allocate(numPts,2); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution)); // // Generate points and point data for sides // for (i=0; i<this->Resolution; i++) { // x coordinate xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle); xbot[0] += center[0]; xtop[0] += center[0]; tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0); // y coordinate xbot[1] = 0.5 * this->Height + center[1]; xtop[1] = -0.5 * this->Height + center[1]; nbot[1] = ntop[1] = 0.0; tcbot[1] = 0.0; tctop[1] = 1.0; // z coordinate xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle); xbot[2] += center[2]; xtop[2] += center[2]; idx = 2*i; newPoints->InsertPoint(idx,xbot); newPoints->InsertPoint(idx+1,xtop); newTCoords->InsertTCoord(idx,tcbot); newTCoords->InsertTCoord(idx+1,tctop); newNormals->InsertNormal(idx,nbot); newNormals->InsertNormal(idx+1,ntop); } // // Generate polygons for sides // for (i=0; i<this->Resolution; i++) { pts[0] = 2*i; pts[1] = pts[0] + 1; pts[2] = (pts[1] + 2) % (2*this->Resolution); pts[3] = pts[2] - 1; newPolys->InsertNextCell(4,pts); } // // Generate points and point data for top/bottom polygons // if ( this->Capping ) { for (i=0; i<this->Resolution; i++) { // x coordinate xbot[0] = xtop[0] = this->Radius * cos((double)i*angle); nbot[0] = ntop[0] = 0.0; tcbot[0] = tctop[0] = xbot[0]; xbot[0] += center[0]; xtop[0] += center[0]; // y coordinate xbot[1] = 0.5 * this->Height; xtop[1] = -0.5 * this->Height; nbot[1] = 1.0; ntop[1] = -1.0; xbot[1] += center[1]; xtop[1] += center[1]; // z coordinate xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle); tcbot[1] = tctop[1] = xbot[2]; xbot[2] += center[2]; xtop[2] += center[2]; nbot[2] = 0.0; ntop[2] = 0.0; idx = 2*this->Resolution; newPoints->InsertPoint(idx+i,xbot); newTCoords->InsertTCoord(idx+i,tcbot); newNormals->InsertNormal(idx+i,nbot); idx = 3*this->Resolution; newPoints->InsertPoint(idx+i,xtop); newTCoords->InsertTCoord(idx+i,tctop); newNormals->InsertNormal(idx+i,ntop); } // // Generate polygons for top/bottom polygons // for (i=0; i<this->Resolution; i++) { pts[i] = 2*this->Resolution + i; } newPolys->InsertNextCell(this->Resolution,pts); for (i=0; i<this->Resolution; i++) { pts[i] = 3*this->Resolution + i; } newPolys->InsertNextCell(this->Resolution,pts); } // if capping // // Update ourselves and release memory // output->SetPoints(newPoints); newPoints->Delete(); output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); newPolys->Squeeze(); // since we've estimated size; reclaim some space output->SetPolys(newPolys); newPolys->Delete(); } void vtkCylinderSource::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); os << indent << "Resolution: " << this->Resolution << "\n"; os << indent << "Height: " << this->Height << "\n"; os << indent << "Radius: " << this->Radius << "\n"; os << indent << "Center: (" << this->Center[0] << ", " << this->Center[1] << ", " << this->Center[2] << " )\n"; os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); } <commit_msg>ERR: top cylinder was oriented wrong.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCylinderSource.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <math.h> #include "vtkCylinderSource.h" #include "vtkPoints.h" #include "vtkNormals.h" #include "vtkTCoords.h" vtkCylinderSource::vtkCylinderSource (int res) { this->Resolution = res; this->Height = 1.0; this->Radius = 0.5; this->Capping = 1; this->Center[0] = this->Center[1] = this->Center[2] = 0.0; } void vtkCylinderSource::Execute() { float angle= 2.0*3.141592654/this->Resolution; int numPolys, numPts; float xbot[3], tcbot[2], nbot[3]; float xtop[3], tctop[2], ntop[3]; float *center = this->Center; int i, idx; int pts[VTK_CELL_SIZE]; vtkPoints *newPoints; vtkNormals *newNormals; vtkTCoords *newTCoords; vtkCellArray *newPolys; vtkPolyData *output = this->GetOutput(); // // Set things up; allocate memory // if ( this->Capping ) { numPts = 4*this->Resolution; numPolys = this->Resolution + 2; } else { numPts = 2*this->Resolution; numPolys = this->Resolution; } newPoints = vtkPoints::New(); newPoints->Allocate(numPts); newNormals = vtkNormals::New(); newNormals->Allocate(numPts); newTCoords = vtkTCoords::New(); newTCoords->Allocate(numPts,2); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution)); // // Generate points and point data for sides // for (i=0; i<this->Resolution; i++) { // x coordinate xbot[0] = xtop[0] = nbot[0] = ntop[0] = this->Radius * cos((double)i*angle); xbot[0] += center[0]; xtop[0] += center[0]; tcbot[0] = tctop[0] = fabs(2.0*i/this->Resolution - 1.0); // y coordinate xbot[1] = 0.5 * this->Height + center[1]; xtop[1] = -0.5 * this->Height + center[1]; nbot[1] = ntop[1] = 0.0; tcbot[1] = 0.0; tctop[1] = 1.0; // z coordinate xbot[2] = xtop[2] = nbot[2] = ntop[2] = -this->Radius * sin((double)i*angle); xbot[2] += center[2]; xtop[2] += center[2]; idx = 2*i; newPoints->InsertPoint(idx,xbot); newPoints->InsertPoint(idx+1,xtop); newTCoords->InsertTCoord(idx,tcbot); newTCoords->InsertTCoord(idx+1,tctop); newNormals->InsertNormal(idx,nbot); newNormals->InsertNormal(idx+1,ntop); } // // Generate polygons for sides // for (i=0; i<this->Resolution; i++) { pts[0] = 2*i; pts[1] = pts[0] + 1; pts[2] = (pts[1] + 2) % (2*this->Resolution); pts[3] = pts[2] - 1; newPolys->InsertNextCell(4,pts); } // // Generate points and point data for top/bottom polygons // if ( this->Capping ) { for (i=0; i<this->Resolution; i++) { // x coordinate xbot[0] = xtop[0] = this->Radius * cos((double)i*angle); nbot[0] = ntop[0] = 0.0; tcbot[0] = tctop[0] = xbot[0]; xbot[0] += center[0]; xtop[0] += center[0]; // y coordinate xbot[1] = 0.5 * this->Height; xtop[1] = -0.5 * this->Height; nbot[1] = 1.0; ntop[1] = -1.0; xbot[1] += center[1]; xtop[1] += center[1]; // z coordinate xbot[2] = xtop[2] = -this->Radius * sin((double)i*angle); tcbot[1] = tctop[1] = xbot[2]; xbot[2] += center[2]; xtop[2] += center[2]; nbot[2] = 0.0; ntop[2] = 0.0; idx = 2*this->Resolution; newPoints->InsertPoint(idx+i,xbot); newTCoords->InsertTCoord(idx+i,tcbot); newNormals->InsertNormal(idx+i,nbot); idx = 3*this->Resolution; newPoints->InsertPoint(idx+this->Resolution-i-1,xtop); newTCoords->InsertTCoord(idx+this->Resolution-i-1,tctop); newNormals->InsertNormal(idx+this->Resolution-i-1,ntop); } // // Generate polygons for top/bottom polygons // for (i=0; i<this->Resolution; i++) { pts[i] = 2*this->Resolution + i; } newPolys->InsertNextCell(this->Resolution,pts); for (i=0; i<this->Resolution; i++) { pts[i] = 3*this->Resolution + i; } newPolys->InsertNextCell(this->Resolution,pts); } // if capping // // Update ourselves and release memory // output->SetPoints(newPoints); newPoints->Delete(); output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); newPolys->Squeeze(); // since we've estimated size; reclaim some space output->SetPolys(newPolys); newPolys->Delete(); } void vtkCylinderSource::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); os << indent << "Resolution: " << this->Resolution << "\n"; os << indent << "Height: " << this->Height << "\n"; os << indent << "Radius: " << this->Radius << "\n"; os << indent << "Center: (" << this->Center[0] << ", " << this->Center[1] << ", " << this->Center[2] << " )\n"; os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); } <|endoftext|>
<commit_before><commit_msg>Draw cicles centred as intended so that folding margin markers look correct.<commit_after><|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "maemodeployconfigurationwidget.h" #include "ui_maemodeployconfigurationwidget.h" #include "deploymentsettingsassistant.h" #include "maemoglobal.h" #include "qt4maemodeployconfiguration.h" #include "qt4maemotarget.h" #include <qt4projectmanager/qt4nodes.h> #include <remotelinux/deployablefile.h> #include <remotelinux/deployablefilesperprofile.h> #include <remotelinux/deploymentinfo.h> #include <remotelinux/remotelinuxdeployconfigurationwidget.h> #include <utils/fileutils.h> #include <utils/qtcassert.h> #include <QtCore/QFileInfo> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtGui/QPixmap> #include <QtGui/QVBoxLayout> using namespace ProjectExplorer; using namespace Qt4ProjectManager; namespace RemoteLinux { namespace Internal { MaemoDeployConfigurationWidget::MaemoDeployConfigurationWidget(QWidget *parent) : DeployConfigurationWidget(parent), ui(new Ui::MaemoDeployConfigurationWidget), m_remoteLinuxWidget(new RemoteLinuxDeployConfigurationWidget) { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setSpacing(0); mainLayout->addWidget(m_remoteLinuxWidget); QWidget * const subWidget = new QWidget; ui->setupUi(subWidget); mainLayout->addWidget(subWidget); mainLayout->addStretch(1); connect(m_remoteLinuxWidget, SIGNAL(currentModelChanged(const DeployableFilesPerProFile*)), SLOT(handleCurrentModelChanged(const DeployableFilesPerProFile*))); handleCurrentModelChanged(0); } MaemoDeployConfigurationWidget::~MaemoDeployConfigurationWidget() { delete ui; } void MaemoDeployConfigurationWidget::init(DeployConfiguration *dc) { m_remoteLinuxWidget->init(dc); connect(ui->addDesktopFileButton, SIGNAL(clicked()), SLOT(addDesktopFile())); connect(ui->addIconButton, SIGNAL(clicked()), SLOT(addIcon())); connect(deployConfiguration()->deploymentInfo().data(), SIGNAL(modelAboutToBeReset()), SLOT(handleDeploymentInfoToBeReset())); } Qt4MaemoDeployConfiguration *MaemoDeployConfigurationWidget::deployConfiguration() const { return qobject_cast<Qt4MaemoDeployConfiguration *>(m_remoteLinuxWidget->deployConfiguration()); } void MaemoDeployConfigurationWidget::handleDeploymentInfoToBeReset() { ui->addDesktopFileButton->setEnabled(false); ui->addIconButton->setEnabled(false); } void MaemoDeployConfigurationWidget::handleCurrentModelChanged(const DeployableFilesPerProFile *proFileInfo) { ui->addDesktopFileButton->setEnabled(canAddDesktopFile(proFileInfo)); ui->addIconButton->setEnabled(canAddIcon(proFileInfo)); } void MaemoDeployConfigurationWidget::addDesktopFile() { DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel(); QTC_ASSERT(canAddDesktopFile(proFileInfo), return); const QString desktopFilePath = QFileInfo(proFileInfo->proFilePath()).path() + QLatin1Char('/') + proFileInfo->projectName() + QLatin1String(".desktop"); if (!QFile::exists(desktopFilePath)) { const QString desktopTemplate = QLatin1String("[Desktop Entry]\nEncoding=UTF-8\n" "Version=1.0\nType=Application\nTerminal=false\nName=%1\nExec=%2\n" "Icon=%1\nX-Window-Icon=\nX-HildonDesk-ShowInToolbar=true\n" "X-Osso-Type=application/x-executable\n"); Utils::FileSaver saver(desktopFilePath); saver.write(desktopTemplate.arg(proFileInfo->projectName(), proFileInfo->remoteExecutableFilePath()).toUtf8()); if (!saver.finalize(this)) return; } DeployableFile d; d.remoteDir = QLatin1String("/usr/share/applications"); if (qobject_cast<Qt4Maemo5Target *>(deployConfiguration()->target())) d.remoteDir += QLatin1String("/hildon"); d.localFilePath = desktopFilePath; if (!deployConfiguration()->deploymentSettingsAssistant()->addDeployableToProFile(proFileInfo, QLatin1String("desktopfile"), d)) { QMessageBox::critical(this, tr("Project File Update Failed"), tr("Could not update the project file.")); } else { ui->addDesktopFileButton->setEnabled(false); } } void MaemoDeployConfigurationWidget::addIcon() { DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel(); const int iconDim = MaemoGlobal::applicationIconSize(deployConfiguration()->supportedOsType()); const QString origFilePath = QFileDialog::getOpenFileName(this, tr("Choose Icon (will be scaled to %1x%1 pixels, if necessary)").arg(iconDim), proFileInfo->projectDir(), QLatin1String("(*.png)")); if (origFilePath.isEmpty()) return; QPixmap pixmap(origFilePath); if (pixmap.isNull()) { QMessageBox::critical(this, tr("Invalid Icon"), tr("Unable to read image")); return; } const QSize iconSize(iconDim, iconDim); if (pixmap.size() != iconSize) pixmap = pixmap.scaled(iconSize); const QString newFileName = proFileInfo->projectName() + QLatin1Char('.') + QFileInfo(origFilePath).suffix(); const QString newFilePath = proFileInfo->projectDir() + QLatin1Char('/') + newFileName; if (!pixmap.save(newFilePath)) { QMessageBox::critical(this, tr("Failed to Save Icon"), tr("Could not save icon to '%1'.").arg(newFilePath)); return; } if (!deployConfiguration()->deploymentSettingsAssistant()->addDeployableToProFile(proFileInfo, QLatin1String("icon"), DeployableFile(newFilePath, remoteIconDir()))) { QMessageBox::critical(this, tr("Project File Update Failed"), tr("Could not update the project file.")); } else { ui->addIconButton->setEnabled(false); } } bool MaemoDeployConfigurationWidget::canAddDesktopFile(const DeployableFilesPerProFile *proFileInfo) const { return proFileInfo && proFileInfo->isApplicationProject() && deployConfiguration()->localDesktopFilePath(proFileInfo).isEmpty(); } bool MaemoDeployConfigurationWidget::canAddIcon(const DeployableFilesPerProFile *proFileInfo) const { return proFileInfo && proFileInfo->isApplicationProject() && remoteIconFilePath(proFileInfo).isEmpty(); } QString MaemoDeployConfigurationWidget::remoteIconFilePath(const DeployableFilesPerProFile *proFileInfo) const { QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString()); const QStringList imageTypes = QStringList() << QLatin1String("jpg") << QLatin1String("png") << QLatin1String("svg"); for (int i = 0; i < proFileInfo->rowCount(); ++i) { const DeployableFile &d = proFileInfo->deployableAt(i); const QString extension = QFileInfo(d.localFilePath).suffix(); if (d.remoteDir.startsWith(remoteIconDir()) && imageTypes.contains(extension)) return d.remoteDir + QLatin1Char('/') + QFileInfo(d.localFilePath).fileName(); } return QString(); } QString MaemoDeployConfigurationWidget::remoteIconDir() const { return QString::fromLocal8Bit("/usr/share/icons/hicolor/%1x%1/apps") .arg(MaemoGlobal::applicationIconSize(deployConfiguration()->supportedOsType())); } } // namespace Internal } // namespace RemoteLinux <commit_msg>MeeGo: Fix initial deployment button state.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "maemodeployconfigurationwidget.h" #include "ui_maemodeployconfigurationwidget.h" #include "deploymentsettingsassistant.h" #include "maemoglobal.h" #include "qt4maemodeployconfiguration.h" #include "qt4maemotarget.h" #include <qt4projectmanager/qt4nodes.h> #include <remotelinux/deployablefile.h> #include <remotelinux/deployablefilesperprofile.h> #include <remotelinux/deploymentinfo.h> #include <remotelinux/remotelinuxdeployconfigurationwidget.h> #include <utils/fileutils.h> #include <utils/qtcassert.h> #include <QtCore/QFileInfo> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtGui/QPixmap> #include <QtGui/QVBoxLayout> using namespace ProjectExplorer; using namespace Qt4ProjectManager; namespace RemoteLinux { namespace Internal { MaemoDeployConfigurationWidget::MaemoDeployConfigurationWidget(QWidget *parent) : DeployConfigurationWidget(parent), ui(new Ui::MaemoDeployConfigurationWidget), m_remoteLinuxWidget(new RemoteLinuxDeployConfigurationWidget) { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setSpacing(0); mainLayout->addWidget(m_remoteLinuxWidget); QWidget * const subWidget = new QWidget; ui->setupUi(subWidget); mainLayout->addWidget(subWidget); mainLayout->addStretch(1); connect(m_remoteLinuxWidget, SIGNAL(currentModelChanged(const DeployableFilesPerProFile*)), SLOT(handleCurrentModelChanged(const DeployableFilesPerProFile*))); handleCurrentModelChanged(m_remoteLinuxWidget->currentModel()); } MaemoDeployConfigurationWidget::~MaemoDeployConfigurationWidget() { delete ui; } void MaemoDeployConfigurationWidget::init(DeployConfiguration *dc) { m_remoteLinuxWidget->init(dc); connect(ui->addDesktopFileButton, SIGNAL(clicked()), SLOT(addDesktopFile())); connect(ui->addIconButton, SIGNAL(clicked()), SLOT(addIcon())); connect(deployConfiguration()->deploymentInfo().data(), SIGNAL(modelAboutToBeReset()), SLOT(handleDeploymentInfoToBeReset())); } Qt4MaemoDeployConfiguration *MaemoDeployConfigurationWidget::deployConfiguration() const { return qobject_cast<Qt4MaemoDeployConfiguration *>(m_remoteLinuxWidget->deployConfiguration()); } void MaemoDeployConfigurationWidget::handleDeploymentInfoToBeReset() { ui->addDesktopFileButton->setEnabled(false); ui->addIconButton->setEnabled(false); } void MaemoDeployConfigurationWidget::handleCurrentModelChanged(const DeployableFilesPerProFile *proFileInfo) { ui->addDesktopFileButton->setEnabled(canAddDesktopFile(proFileInfo)); ui->addIconButton->setEnabled(canAddIcon(proFileInfo)); } void MaemoDeployConfigurationWidget::addDesktopFile() { DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel(); QTC_ASSERT(canAddDesktopFile(proFileInfo), return); const QString desktopFilePath = QFileInfo(proFileInfo->proFilePath()).path() + QLatin1Char('/') + proFileInfo->projectName() + QLatin1String(".desktop"); if (!QFile::exists(desktopFilePath)) { const QString desktopTemplate = QLatin1String("[Desktop Entry]\nEncoding=UTF-8\n" "Version=1.0\nType=Application\nTerminal=false\nName=%1\nExec=%2\n" "Icon=%1\nX-Window-Icon=\nX-HildonDesk-ShowInToolbar=true\n" "X-Osso-Type=application/x-executable\n"); Utils::FileSaver saver(desktopFilePath); saver.write(desktopTemplate.arg(proFileInfo->projectName(), proFileInfo->remoteExecutableFilePath()).toUtf8()); if (!saver.finalize(this)) return; } DeployableFile d; d.remoteDir = QLatin1String("/usr/share/applications"); if (qobject_cast<Qt4Maemo5Target *>(deployConfiguration()->target())) d.remoteDir += QLatin1String("/hildon"); d.localFilePath = desktopFilePath; if (!deployConfiguration()->deploymentSettingsAssistant()->addDeployableToProFile(proFileInfo, QLatin1String("desktopfile"), d)) { QMessageBox::critical(this, tr("Project File Update Failed"), tr("Could not update the project file.")); } else { ui->addDesktopFileButton->setEnabled(false); } } void MaemoDeployConfigurationWidget::addIcon() { DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel(); const int iconDim = MaemoGlobal::applicationIconSize(deployConfiguration()->supportedOsType()); const QString origFilePath = QFileDialog::getOpenFileName(this, tr("Choose Icon (will be scaled to %1x%1 pixels, if necessary)").arg(iconDim), proFileInfo->projectDir(), QLatin1String("(*.png)")); if (origFilePath.isEmpty()) return; QPixmap pixmap(origFilePath); if (pixmap.isNull()) { QMessageBox::critical(this, tr("Invalid Icon"), tr("Unable to read image")); return; } const QSize iconSize(iconDim, iconDim); if (pixmap.size() != iconSize) pixmap = pixmap.scaled(iconSize); const QString newFileName = proFileInfo->projectName() + QLatin1Char('.') + QFileInfo(origFilePath).suffix(); const QString newFilePath = proFileInfo->projectDir() + QLatin1Char('/') + newFileName; if (!pixmap.save(newFilePath)) { QMessageBox::critical(this, tr("Failed to Save Icon"), tr("Could not save icon to '%1'.").arg(newFilePath)); return; } if (!deployConfiguration()->deploymentSettingsAssistant()->addDeployableToProFile(proFileInfo, QLatin1String("icon"), DeployableFile(newFilePath, remoteIconDir()))) { QMessageBox::critical(this, tr("Project File Update Failed"), tr("Could not update the project file.")); } else { ui->addIconButton->setEnabled(false); } } bool MaemoDeployConfigurationWidget::canAddDesktopFile(const DeployableFilesPerProFile *proFileInfo) const { return proFileInfo && proFileInfo->isApplicationProject() && deployConfiguration()->localDesktopFilePath(proFileInfo).isEmpty(); } bool MaemoDeployConfigurationWidget::canAddIcon(const DeployableFilesPerProFile *proFileInfo) const { return proFileInfo && proFileInfo->isApplicationProject() && remoteIconFilePath(proFileInfo).isEmpty(); } QString MaemoDeployConfigurationWidget::remoteIconFilePath(const DeployableFilesPerProFile *proFileInfo) const { QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString()); const QStringList imageTypes = QStringList() << QLatin1String("jpg") << QLatin1String("png") << QLatin1String("svg"); for (int i = 0; i < proFileInfo->rowCount(); ++i) { const DeployableFile &d = proFileInfo->deployableAt(i); const QString extension = QFileInfo(d.localFilePath).suffix(); if (d.remoteDir.startsWith(remoteIconDir()) && imageTypes.contains(extension)) return d.remoteDir + QLatin1Char('/') + QFileInfo(d.localFilePath).fileName(); } return QString(); } QString MaemoDeployConfigurationWidget::remoteIconDir() const { return QString::fromLocal8Bit("/usr/share/icons/hicolor/%1x%1/apps") .arg(MaemoGlobal::applicationIconSize(deployConfiguration()->supportedOsType())); } } // namespace Internal } // namespace RemoteLinux <|endoftext|>
<commit_before>#include "catch.hpp" #include "stream.hpp" #include "gsl.h" #include <sstream> #include <algorithm> using namespace std; using namespace gsl; using Payload = vector<ubyte>; struct TestConnection { void newMessage(span<const ubyte> bytes) { switch(getMessageType(bytes)) { case MqttType::CONNACK: connected = true; connectionCode = MqttConnack::Code::ACCEPTED; break; case MqttType::PUBLISH: { Decerealiser dec{bytes}; const auto hdr = dec.create<MqttFixedHeader>(); dec.reset(); const auto msg = dec.create<MqttPublish>(hdr); payloads.emplace_back(msg.payload.begin(), msg.payload.end()); } break; default: break; } lastMsg = Payload(bytes.begin(), bytes.end()); } void disconnect() { connected = false; } bool connected{false}; MqttConnack::Code connectionCode{MqttConnack::Code::NO_AUTH}; vector<Payload> payloads; Payload lastMsg; }; static vector<ubyte> subscribeMsg(const std::string& topic, ushort msgId) { vector<ubyte> msg{0x8b}; //fixed header sans remaining length const auto remainingLength = topic.size() + 2 /*topic len*/ + 2 /*msgId*/ + 1 /*qos*/; msg.emplace_back(remainingLength); msg.emplace_back(msgId >> 8); msg.emplace_back(msgId & 0xff); msg.emplace_back(topic.size() >> 8); msg.emplace_back(topic.size() & 0xff); copy(topic.cbegin(), topic.cend(), back_inserter(msg)); msg.emplace_back(0); //qos return msg; } int readInto(MqttStream& stream, span<const ubyte> bytes) { copy(bytes.cbegin(), bytes.cend(), stream.begin()); return bytes.size(); } TEST_CASE("MQTT in 2 packets") { MqttServer<TestConnection> server; TestConnection connection; MqttStream stream{128}; const auto subscribe = subscribeMsg("top", 33); server.newMessage(connection, subscribe); const vector<ubyte> bytes1{ 0x3c, 15, //fixed header 0x00, 0x03, 't', 'o', 'p', //topic name 0x00, 0x21, //message ID 1, 2, 3 //first part of payload }; const auto numBytes1 = readInto(stream, bytes1); stream.handleMessages(numBytes1, server, connection); REQUIRE(connection.payloads == vector<Payload>{}); const vector<ubyte> bytes2{4, 5, 6, 7, 8}; //2nd part of payload const auto numBytes2 = readInto(stream, bytes2); stream.handleMessages(numBytes2, server, connection); REQUIRE(connection.payloads == (vector<Payload>{{1, 2, 3, 4, 5, 6, 7, 8}})); } <commit_msg>2nd passing UT for stream<commit_after>#include "catch.hpp" #include "stream.hpp" #include "gsl.h" #include <sstream> #include <algorithm> using namespace std; using namespace gsl; using Payload = vector<ubyte>; struct TestConnection { void newMessage(span<const ubyte> bytes) { switch(getMessageType(bytes)) { case MqttType::CONNACK: connected = true; connectionCode = MqttConnack::Code::ACCEPTED; break; case MqttType::PUBLISH: { Decerealiser dec{bytes}; const auto hdr = dec.create<MqttFixedHeader>(); dec.reset(); const auto msg = dec.create<MqttPublish>(hdr); payloads.emplace_back(msg.payload.begin(), msg.payload.end()); } break; default: break; } lastMsg = Payload(bytes.begin(), bytes.end()); } void disconnect() { connected = false; } bool connected{false}; MqttConnack::Code connectionCode{MqttConnack::Code::NO_AUTH}; vector<Payload> payloads; Payload lastMsg; }; static vector<ubyte> subscribeMsg(const std::string& topic, ushort msgId) { vector<ubyte> msg{0x8b}; //fixed header sans remaining length const auto remainingLength = topic.size() + 2 /*topic len*/ + 2 /*msgId*/ + 1 /*qos*/; msg.emplace_back(remainingLength); msg.emplace_back(msgId >> 8); msg.emplace_back(msgId & 0xff); msg.emplace_back(topic.size() >> 8); msg.emplace_back(topic.size() & 0xff); copy(topic.cbegin(), topic.cend(), back_inserter(msg)); msg.emplace_back(0); //qos return msg; } int readInto(MqttStream& stream, span<const ubyte> bytes) { copy(bytes.cbegin(), bytes.cend(), stream.begin()); return bytes.size(); } TEST_CASE("MQTT in 2 packets") { MqttServer<TestConnection> server; TestConnection connection; MqttStream stream{128}; const auto subscribe = subscribeMsg("top", 33); server.newMessage(connection, subscribe); const vector<ubyte> bytes1{ 0x3c, 15, //fixed header 0x00, 0x03, 't', 'o', 'p', //topic name 0x00, 0x21, //message ID 1, 2, 3 //first part of payload }; const vector<ubyte> bytes2{4, 5, 6, 7, 8}; //2nd part of payload const auto numBytes1 = readInto(stream, bytes1); stream.handleMessages(numBytes1, server, connection); REQUIRE(connection.payloads == vector<Payload>{}); const auto numBytes2 = readInto(stream, bytes2); stream.handleMessages(numBytes2, server, connection); REQUIRE(connection.payloads == (vector<Payload>{{1, 2, 3, 4, 5, 6, 7, 8}})); } TEST_CASE("Broken header and two messages") { MqttServer<TestConnection> server; TestConnection connection; MqttStream stream{128}; connection.connected = true; //easier than sending conneciton packet const auto subscribe = subscribeMsg("top", 33); server.newMessage(connection, subscribe); const vector<ubyte> bytes1{0x3c}; //half of header const vector<ubyte> bytes2{ 15, //2nd half of fixed header 0x00, 0x03, 't', 'o', 'p', //topic name 0x00, 0x21, //message ID 1, 2, 3, 4, 5, 6, 7, 8, 0xe0, 0, //header for disconnect }; const auto numBytes1 = readInto(stream, bytes1); stream.handleMessages(numBytes1, server, connection); REQUIRE(connection.payloads == vector<Payload>{}); REQUIRE(connection.connected == true); const auto numBytes2 = readInto(stream, bytes2); stream.handleMessages(numBytes2, server, connection); REQUIRE(connection.payloads == (vector<Payload>{{1, 2, 3, 4, 5, 6, 7, 8}})); REQUIRE(connection.connected == false); } <|endoftext|>
<commit_before>#include "quadrature/utility/quadrature_utilities.h" #include <algorithm> #include <cmath> #include "quadrature/tests/quadrature_point_mock.h" #include "quadrature/tests/quadrature_generator_mock.h" #include "quadrature/tests/quadrature_set_mock.h" #include "quadrature/tests/ordinate_mock.h" #include "test_helpers/gmock_wrapper.h" #include "test_helpers/test_helper_functions.h" namespace { using namespace bart; template <typename DimensionWrapper> class QuadratureUtilityTests : public ::testing::Test { public: static constexpr int dim = DimensionWrapper::value; }; TYPED_TEST_CASE(QuadratureUtilityTests, bart::testing::AllDimensions); TYPED_TEST(QuadratureUtilityTests, ReflectAcrossOrigin) { constexpr int dim = this->dim; std::array<double, dim> position, negative_position; auto random_position = btest::RandomVector(dim, -10, 10); for (int i = 0; i < dim; ++i) { position.at(i) = random_position.at(i); negative_position.at(i) = -random_position.at(i); } quadrature::OrdinateMock<dim> mock_ordinate; EXPECT_CALL(mock_ordinate, cartesian_position()) .WillOnce(::testing::Return(position)); EXPECT_EQ(quadrature::utility::ReflectAcrossOrigin(mock_ordinate), negative_position); EXPECT_CALL(mock_ordinate, cartesian_position()) .WillOnce(::testing::Return(negative_position)); EXPECT_EQ(quadrature::utility::ReflectAcrossOrigin(mock_ordinate), position); } TYPED_TEST(QuadratureUtilityTests, GenerateAllPositiveX) { const int dim = this->dim; const int n_points = 3; const int n_quadrants = std::pow(2, dim)/2; // Quadrature set to be distributed in positive x std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>> quadrature_set; for (int i = 0; i < n_points; ++i) { auto random_position = btest::RandomVector(dim, 1, 10); auto random_weight = btest::RandomDouble(0, 2); std::array<double, dim> position; for (int j = 0; j < dim; ++j) position.at(j) = random_position.at(j); quadrature_set.emplace_back(quadrature::CartesianPosition<dim>(position), quadrature::Weight(random_weight)); } auto distributed_set = quadrature::utility::GenerateAllPositiveX<dim>(quadrature_set); EXPECT_EQ(distributed_set.size(), n_points * n_quadrants); for (const auto& quadrature_pair : quadrature_set) { EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), quadrature_pair)); if (dim > 1) { auto negative_y_pair = quadrature_pair; negative_y_pair.first.get().at(1) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_y_pair)); } if (dim > 2) { auto negative_z_pair = quadrature_pair; negative_z_pair.first.get().at(2) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_z_pair)); auto negative_zy_pair = negative_z_pair; negative_zy_pair.first.get().at(1) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_zy_pair)); } } } TYPED_TEST(QuadratureUtilityTests, GenerateAllPositiveXScalar) { const int dim = this->dim; std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>> quadrature_set; std::array<double, dim> zero_position; zero_position.fill(0); quadrature_set.emplace_back(quadrature::CartesianPosition<dim>(zero_position), quadrature::Weight(1)); auto distributed_set = quadrature::utility::GenerateAllPositiveX<dim>(quadrature_set); EXPECT_EQ(distributed_set.size(), 1); EXPECT_EQ(quadrature_set.at(0), distributed_set.at(0)); } TYPED_TEST(QuadratureUtilityTests, QuadraturePointCompare) { const int dim = this->dim; std::array<double, dim> position_1, position_2; auto random_position_1 = btest::RandomVector(dim, -100, 100); auto random_position_2 = btest::RandomVector(dim, -100, 100); for (int i = 0; i < dim; ++i) { position_1.at(i) = random_position_1.at(i); position_2.at(i) = random_position_2.at(i); } bool expected_result = (position_1 < position_2); auto mock_point_1 = std::make_shared<quadrature::QuadraturePointMock<dim>>(); auto mock_point_2 = std::make_shared<quadrature::QuadraturePointMock<dim>>(); EXPECT_CALL(*mock_point_1, cartesian_position()) .WillOnce(::testing::Return(position_1)); EXPECT_CALL(*mock_point_2, cartesian_position()) .WillOnce(::testing::Return(position_2)); quadrature::utility::quadrature_point_compare<dim> compare_struct; auto result = compare_struct(mock_point_1, mock_point_2); EXPECT_EQ(result, expected_result); const auto& const_compare_struct = compare_struct; EXPECT_CALL(*mock_point_1, cartesian_position()) .WillOnce(::testing::Return(position_1)); EXPECT_CALL(*mock_point_2, cartesian_position()) .WillOnce(::testing::Return(position_2)); auto const_result = const_compare_struct(mock_point_1, mock_point_2); EXPECT_EQ(const_result, expected_result); } } // namespace<commit_msg>added documentation to tests for quadrature utilities<commit_after>#include "quadrature/utility/quadrature_utilities.h" #include <algorithm> #include <cmath> #include "quadrature/tests/quadrature_point_mock.h" #include "quadrature/tests/quadrature_generator_mock.h" #include "quadrature/tests/quadrature_set_mock.h" #include "quadrature/tests/ordinate_mock.h" #include "test_helpers/gmock_wrapper.h" #include "test_helpers/test_helper_functions.h" namespace { using namespace bart; /* Tests for various quadrature utilities. Will be run in all three dimensions. */ template <typename DimensionWrapper> class QuadratureUtilityTests : public ::testing::Test { public: static constexpr int dim = DimensionWrapper::value; }; TYPED_TEST_CASE(QuadratureUtilityTests, bart::testing::AllDimensions); // ReflectAcrossOrigin should return the correct reflected value TYPED_TEST(QuadratureUtilityTests, ReflectAcrossOrigin) { constexpr int dim = this->dim; std::array<double, dim> position, negative_position; auto random_position = btest::RandomVector(dim, -10, 10); for (int i = 0; i < dim; ++i) { position.at(i) = random_position.at(i); negative_position.at(i) = -random_position.at(i); } quadrature::OrdinateMock<dim> mock_ordinate; EXPECT_CALL(mock_ordinate, cartesian_position()) .WillOnce(::testing::Return(position)); EXPECT_EQ(quadrature::utility::ReflectAcrossOrigin(mock_ordinate), negative_position); EXPECT_CALL(mock_ordinate, cartesian_position()) .WillOnce(::testing::Return(negative_position)); EXPECT_EQ(quadrature::utility::ReflectAcrossOrigin(mock_ordinate), position); } // GenerateAllPositiveX should generate all correct points TYPED_TEST(QuadratureUtilityTests, GenerateAllPositiveX) { const int dim = this->dim; const int n_points = 3; const int n_quadrants = std::pow(2, dim)/2; std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>> quadrature_set; // Fill the quadrature set with random positions for (int i = 0; i < n_points; ++i) { auto random_position = btest::RandomVector(dim, 1, 10); auto random_weight = btest::RandomDouble(0, 2); std::array<double, dim> position; for (int j = 0; j < dim; ++j) position.at(j) = random_position.at(j); quadrature_set.emplace_back(quadrature::CartesianPosition<dim>(position), quadrature::Weight(random_weight)); } auto distributed_set = quadrature::utility::GenerateAllPositiveX<dim>(quadrature_set); EXPECT_EQ(distributed_set.size(), n_points * n_quadrants); for (const auto& quadrature_pair : quadrature_set) { EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), quadrature_pair)); if (dim > 1) { auto negative_y_pair = quadrature_pair; negative_y_pair.first.get().at(1) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_y_pair)); } if (dim > 2) { auto negative_z_pair = quadrature_pair; negative_z_pair.first.get().at(2) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_z_pair)); auto negative_zy_pair = negative_z_pair; negative_zy_pair.first.get().at(1) *= -1; EXPECT_EQ(1, std::count(distributed_set.cbegin(), distributed_set.cend(), negative_zy_pair)); } } } /* GenerateAllPositiveXScalar shouldn't have any effect on quadrature points * at the origin (the only points without a reflection) */ TYPED_TEST(QuadratureUtilityTests, GenerateAllPositiveXScalar) { const int dim = this->dim; std::vector<std::pair<quadrature::CartesianPosition<dim>, quadrature::Weight>> quadrature_set; std::array<double, dim> zero_position; zero_position.fill(0); quadrature_set.emplace_back(quadrature::CartesianPosition<dim>(zero_position), quadrature::Weight(1)); auto distributed_set = quadrature::utility::GenerateAllPositiveX<dim>(quadrature_set); EXPECT_EQ(distributed_set.size(), 1); EXPECT_EQ(quadrature_set.at(0), distributed_set.at(0)); } // QuadraturePointCompare should provide a correct less-than operation. TYPED_TEST(QuadratureUtilityTests, QuadraturePointCompare) { const int dim = this->dim; std::array<double, dim> position_1, position_2; auto random_position_1 = btest::RandomVector(dim, -100, 100); auto random_position_2 = btest::RandomVector(dim, -100, 100); for (int i = 0; i < dim; ++i) { position_1.at(i) = random_position_1.at(i); position_2.at(i) = random_position_2.at(i); } bool expected_result = (position_1 < position_2); auto mock_point_1 = std::make_shared<quadrature::QuadraturePointMock<dim>>(); auto mock_point_2 = std::make_shared<quadrature::QuadraturePointMock<dim>>(); EXPECT_CALL(*mock_point_1, cartesian_position()) .WillOnce(::testing::Return(position_1)); EXPECT_CALL(*mock_point_2, cartesian_position()) .WillOnce(::testing::Return(position_2)); quadrature::utility::quadrature_point_compare<dim> compare_struct; auto result = compare_struct(mock_point_1, mock_point_2); EXPECT_EQ(result, expected_result); // Check const operations const auto& const_compare_struct = compare_struct; EXPECT_CALL(*mock_point_1, cartesian_position()) .WillOnce(::testing::Return(position_1)); EXPECT_CALL(*mock_point_2, cartesian_position()) .WillOnce(::testing::Return(position_2)); auto const_result = const_compare_struct(mock_point_1, mock_point_2); EXPECT_EQ(const_result, expected_result); } } // namespace<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dynamicregister.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-01 13:16:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dynamicregister.hxx" #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif // #include <osl/mutex.hxx> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include "filehelper.hxx" // ----------------------------------------------------------------------------- DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions) :m_pModule(new ::osl::Module()), m_suDLLName(_sDLLName), m_aOptions(_aOptions) { // create and load the module (shared library) rtl::OUString suFile = FileHelper::convertPath( _sDLLName ); rtl::OString sDLLName = rtl::OUStringToOString(suFile, RTL_TEXTENCODING_ASCII_US); if (_aOptions.hasOpt("-verbose")) { fprintf(stderr, "Try to load '%s'.\n", sDLLName.getStr()); } if (! m_pModule->load( suFile )) { rtl::OString sDLLName = rtl::OUStringToOString(_sDLLName, RTL_TEXTENCODING_ASCII_US); fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr()); } } DynamicLibraryHelper::~DynamicLibraryHelper() { delete m_pModule; } <commit_msg>INTEGRATION: CWS fwk01ea (1.4.54); FILE MERGED 2004/04/08 12:45:31 sb 1.4.54.1: #116269# Always call osl::Module::load with GLOBAL (otherwise, C++ exception handling fails on Linux).<commit_after>/************************************************************************* * * $RCSfile: dynamicregister.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-09-20 11:49:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dynamicregister.hxx" #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif // #include <osl/mutex.hxx> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include "filehelper.hxx" // ----------------------------------------------------------------------------- DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions) :m_pModule(new ::osl::Module()), m_suDLLName(_sDLLName), m_aOptions(_aOptions) { // create and load the module (shared library) rtl::OUString suFile = FileHelper::convertPath( _sDLLName ); rtl::OString sDLLName = rtl::OUStringToOString(suFile, RTL_TEXTENCODING_ASCII_US); if (_aOptions.hasOpt("-verbose")) { fprintf(stderr, "Try to load '%s'.\n", sDLLName.getStr()); } if (! m_pModule->load(suFile, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL)) { rtl::OString sDLLName = rtl::OUStringToOString(_sDLLName, RTL_TEXTENCODING_ASCII_US); fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr()); } } DynamicLibraryHelper::~DynamicLibraryHelper() { delete m_pModule; } <|endoftext|>
<commit_before>#ifndef SIMDIFY_COMMON #define SIMDIFY_COMMON #include "../util/inline.hpp" #include "../util/type.hpp" #include "../util/1b.hpp" #include <cmath> #include <cstdint> #include <type_traits> #include <initializer_list> #include <algorithm> #include <array> #include <utility> #include <iterator> #define INL SIMDIFY_FORCE_INLINE namespace simd { // // types for overload selection/disambiguation // struct zero_t {}; struct all_bits_t {}; struct abs_mask_t {}; struct sign_bit_t {}; // // forward declarations // template <typename T> struct horizontal_impl; template <typename T> struct allocator; // // SIMD type base class (with derived class as T, CRTP-style) // template <typename _mm_t, typename _fp_t, typename _bitmask_t, typename T> struct simd_base { using mm_t = _mm_t; using fp_t = _fp_t; using bitmask_t = _bitmask_t; // type-related sanity checks static_assert(sizeof(mm_t) % sizeof(fp_t) == 0, "size of mm_t must be a multiple of the size of fp_t"); static_assert(sizeof(fp_t) == sizeof(bitmask_t), "size of bitmask_t must match the size of fp_t"); static_assert(std::is_integral<bitmask_t>::value, "bitmask_t must be an integral type"); static_assert(std::is_unsigned<bitmask_t>::value, "bitmask_t must be an unsigned type"); // useful constants and types static const auto W = sizeof(mm_t) / sizeof(fp_t); using array_t = std::array<fp_t, W>; using mask_array_t = std::array<bitmask_t, W>; using iterator = typename array_t::iterator; using reverse_iterator = typename array_t::reverse_iterator; using const_iterator = typename array_t::const_iterator; using const_reverse_iterator = typename array_t::const_reverse_iterator; using unary_op_t = ptr<const T(const T& in)>; using binary_op_t = ptr<const T(const T& l, const T& r)>; using horizontal = horizontal_impl<T>; // a wrapper to disambiguate construction with bitmask_t and fp_t struct mask_t { // data union { float f; bitmask_t b; }; // useful bit masks static const bitmask_t ZERO_BIT_MASK = 0; static const bitmask_t ALL_BITS_MASK = ~ZERO_BIT_MASK; static const bitmask_t ABS_BIT_MASK = ALL_BITS_MASK >> 1; static const bitmask_t SIGN_BIT_MASK = ~ABS_BIT_MASK; // constructors INL explicit mask_t() {} INL explicit mask_t(bitmask_t r) : b(r) {} INL mask_t(zero_t) : b(ZERO_BIT_MASK) {} INL mask_t(all_bits_t) : b(ALL_BITS_MASK) {} INL mask_t(abs_mask_t) : b(ABS_BIT_MASK) {} INL mask_t(sign_bit_t) : b(SIGN_BIT_MASK) {} // bitmask_t -- fp_t conversion INL static bitmask_t tob(fp_t l) { mask_t m; m.f = l; return m.b; } INL static fp_t tof(bitmask_t l) { mask_t m; m.b = l; return m.f; } // bitwise operations with fp_t INL static fp_t andf(fp_t l, fp_t r) { return tof(tob(l) & tob(r)); } INL static fp_t orf(fp_t l, fp_t r) { return tof(tob(l) | tob(r)); } INL static fp_t xorf(fp_t l, fp_t r) { return tof(tob(l) ^ tob(r)); } INL static fp_t notf(fp_t l) { return tof(~tob(l)); } INL static fp_t andnotf(fp_t l, fp_t r) { return tof(tob(l) & ~tob(r)); } }; // data union { mm_t mm; array_t f; mask_array_t i; }; // constructor INL simd_base() {} INL simd_base(mm_t r) : mm(r) {} }; // // helper class for lazy evaluation of bitwise not // template <typename T> struct bitwise_not; // // meta operations - apply to all SIMD types // template <typename T> INL T& operator &=(T& l, const T& r) { l = l & r; return l; } template <typename T> INL T& operator |=(T& l, const T& r) { l = l | r; return l; } template <typename T> INL T& operator ^=(T& l, const T& r) { l = l ^ r; return l; } template <typename T> INL T& operator +=(T& l, const T& r) { l = l + r; return l; } template <typename T> INL T& operator -=(T& l, const T& r) { l = l - r; return l; } template <typename T> INL T& operator *=(T& l, const T& r) { l = l * r; return l; } template <typename T> INL T& operator /=(T& l, const T& r) { l = l / r; return l; } template <typename T> INL const T abs(const T& in) { return in & T(ABS_MASK); } template <typename T> INL const T signbit(const T& in) { return in & T(SIGN_BIT); } template <typename T> INL const T signum(const T& in) { return cond(in > T(0), T(1), T(-1)); } template<typename T> INL const T operator~(const bitwise_not<T>& l) { return l.neg; } template<typename T> INL const T operator&(const bitwise_not<T>& l, const T& r) { return andnot(l.neg, r); } template<typename T> INL const T operator&(const T& l, const bitwise_not<T>& r) { return andnot(r.neg, l); } template<typename T> INL const bitwise_not<T> operator&(const bitwise_not<T>& l, const bitwise_not<T>& r) { return bitwise_not<T>(l.neg | r.neg); } template<typename T> INL const bitwise_not<T> operator|(const bitwise_not<T>& l, const bitwise_not<T>& r) { return bitwise_not<T>(l.neg & r.neg); } template<typename T> INL const T operator^(const bitwise_not<T>& l, const bitwise_not<T>& r) { return l.neg ^ r.neg; } template <typename T> INL const T apply_mask(const T& in, const T& mask, zero_t) { return cond(mask, in, T(zero_t{})); } template <typename T> INL const T apply_mask(const T& in, const T& mask, typename T::fp_t neutral_value) { return cond(mask, in, T(neutral_value)); } template <typename T> INL const T apply_mask(const T& in, const T& mask, typename T::mask_t neutral_mask) { return cond(mask, in, T(neutral_mask)); } template <typename T> INL const T apply_mask(const T& in, const T& mask, const T& neutral_value_vector) { return cond(mask, in, neutral_value_vector); } // // provides access to min, max, operator+, operator* before they have been declared // template <typename T> struct operators { static INL const T min_(const T& l, const T& r) { return min(l, r); } static INL const T max_(const T& l, const T& r) { return max(l, r); } static INL const T add_(const T& l, const T& r) { return l + r; } static INL const T mul_(const T& l, const T& r) { return l * r; } }; // // base class for horizontal<T> // template <typename T> struct horizontal_impl_base { using unary_op_t = ptr<const T(const T& in)>; using binary_op_t = ptr<const T(const T& l, const T& r)>; using fp_t = typename T::fp_t; using reduce_find_t = std::pair<fp_t, uint>; using ops = operators<T>; template <binary_op_t F> static INL fp_t reduce(const T& in) { return reduce_vector<F>(in).front(); } template <binary_op_t F> static INL const T reduce_vector(const T& in) { return horizontal_impl<T>::template reduce_vector<F>(in); } template <binary_op_t F> static INL reduce_find_t reduce_find(const T& in) { auto in_reduced = reduce_vector<F>(in); auto selected = horizontal_impl<T>::find(in == in_reduced); return std::make_pair(in_reduced.front(), selected); } template <binary_op_t F, typename N> static INL fp_t reduce_with_mask(const T& in, const T& mask, N&& neutral_value) { return reduce<F>(apply_mask(in, mask, std::forward<N>(neutral_value))); } template <binary_op_t F, typename N> static INL reduce_find_t reduce_find_with_mask(const T& in, const T& mask, N&& neutral_value) { return reduce_find<F>(apply_mask(in, mask, std::forward<N>(neutral_value))); } static INL fp_t min(const T& in) { return reduce<ops::min_>(in); } static INL fp_t max(const T& in) { return reduce<ops::max_>(in); } static INL fp_t sum(const T& in) { return reduce<ops::add_>(in); } static INL fp_t product(const T& in) { return reduce<ops::mul_>(in); } static INL reduce_find_t min_find(const T& in) { return reduce_find<ops::min_>(in); } static INL reduce_find_t max_find(const T& in) { return reduce_find<ops::max_>(in); } static INL fp_t min_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::min_>(in, mask, std::numeric_limits<fp_t>::max()); } static INL fp_t max_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::max_>(in, mask, std::numeric_limits<fp_t>::min()); } static INL fp_t sum_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::add_>(in, mask, zero_t{}); } static INL fp_t product_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::add_>(in, mask, fp_t(1)); } static INL reduce_find_t min_find_with_mask(const T& in, const T& mask) { return reduce_find_with_mask<ops::min_>(in, mask, std::numeric_limits<fp_t>::max()); } static INL reduce_find_t max_find_with_mask(const T& in, const T& mask) { return reduce_find_with_mask<ops::max_>(in, mask, std::numeric_limits<fp_t>::min()); } }; } #undef INL #endif // SIMDIFY_COMMON <commit_msg>Clang compiler errors/warnings removal sweep<commit_after>#ifndef SIMDIFY_COMMON #define SIMDIFY_COMMON #include "../util/inline.hpp" #include "../util/type.hpp" #include "../util/1b.hpp" #include <cmath> #include <cstdint> #include <type_traits> #include <initializer_list> #include <algorithm> #include <array> #include <utility> #include <iterator> #define INL SIMDIFY_FORCE_INLINE namespace simd { // // types for overload selection/disambiguation // struct zero_t {}; struct all_bits_t {}; struct abs_mask_t {}; struct sign_bit_t {}; // // forward declarations // template <typename T> struct horizontal_impl; template <typename T> struct allocator; // // SIMD type base class (with derived class as T, CRTP-style) // template <typename _mm_t, typename _fp_t, typename _bitmask_t, typename T> struct simd_base { using mm_t = _mm_t; using fp_t = _fp_t; using bitmask_t = _bitmask_t; // type-related sanity checks static_assert(sizeof(mm_t) % sizeof(fp_t) == 0, "size of mm_t must be a multiple of the size of fp_t"); static_assert(sizeof(fp_t) == sizeof(bitmask_t), "size of bitmask_t must match the size of fp_t"); static_assert(std::is_integral<bitmask_t>::value, "bitmask_t must be an integral type"); static_assert(std::is_unsigned<bitmask_t>::value, "bitmask_t must be an unsigned type"); // useful constants and types static const auto W = sizeof(mm_t) / sizeof(fp_t); using array_t = std::array<fp_t, W>; using mask_array_t = std::array<bitmask_t, W>; using iterator = typename array_t::iterator; using reverse_iterator = typename array_t::reverse_iterator; using const_iterator = typename array_t::const_iterator; using const_reverse_iterator = typename array_t::const_reverse_iterator; using unary_op_t = ptr<const T(const T& in)>; using binary_op_t = ptr<const T(const T& l, const T& r)>; using horizontal = horizontal_impl<T>; // a wrapper to disambiguate construction with bitmask_t and fp_t struct mask_t { // data union { float f; bitmask_t b; }; // useful bit masks static const bitmask_t ZERO_BIT_MASK = 0; static const bitmask_t ALL_BITS_MASK = ~ZERO_BIT_MASK; static const bitmask_t ABS_BIT_MASK = ALL_BITS_MASK >> 1; static const bitmask_t SIGN_BIT_MASK = ~ABS_BIT_MASK; // constructors INL explicit mask_t() {} INL explicit mask_t(bitmask_t r) : b(r) {} INL mask_t(zero_t) : b(ZERO_BIT_MASK) {} INL mask_t(all_bits_t) : b(ALL_BITS_MASK) {} INL mask_t(abs_mask_t) : b(ABS_BIT_MASK) {} INL mask_t(sign_bit_t) : b(SIGN_BIT_MASK) {} // bitmask_t -- fp_t conversion INL static bitmask_t tob(fp_t l) { mask_t m; m.f = l; return m.b; } INL static fp_t tof(bitmask_t l) { mask_t m; m.b = l; return m.f; } // bitwise operations with fp_t INL static fp_t andf(fp_t l, fp_t r) { return tof(tob(l) & tob(r)); } INL static fp_t orf(fp_t l, fp_t r) { return tof(tob(l) | tob(r)); } INL static fp_t xorf(fp_t l, fp_t r) { return tof(tob(l) ^ tob(r)); } INL static fp_t notf(fp_t l) { return tof(~tob(l)); } INL static fp_t andnotf(fp_t l, fp_t r) { return tof(tob(l) & ~tob(r)); } }; // data union { mm_t mm; array_t f; mask_array_t i; }; // constructor INL simd_base() {} INL simd_base(mm_t r) : mm(r) {} }; // // helper class for lazy evaluation of bitwise not // template <typename T> struct bitwise_not; // // meta operations - apply to all SIMD types // template <typename T> INL T& operator &=(T& l, const T& r) { l = l & r; return l; } template <typename T> INL T& operator |=(T& l, const T& r) { l = l | r; return l; } template <typename T> INL T& operator ^=(T& l, const T& r) { l = l ^ r; return l; } template <typename T> INL T& operator +=(T& l, const T& r) { l = l + r; return l; } template <typename T> INL T& operator -=(T& l, const T& r) { l = l - r; return l; } template <typename T> INL T& operator *=(T& l, const T& r) { l = l * r; return l; } template <typename T> INL T& operator /=(T& l, const T& r) { l = l / r; return l; } template <typename T> INL const T abs(const T& in) { return in & T(abs_mask_t{}); } template <typename T> INL const T signbit(const T& in) { return in & T(sign_bit_t{}); } template <typename T> INL const T signum(const T& in) { return cond(in > T(zero_t{}), T(1), T(-1)); } template<typename T> INL const T operator~(const bitwise_not<T>& l) { return l.neg; } template<typename T> INL const T operator&(const bitwise_not<T>& l, const T& r) { return andnot(l.neg, r); } template<typename T> INL const T operator&(const T& l, const bitwise_not<T>& r) { return andnot(r.neg, l); } template<typename T> INL const bitwise_not<T> operator&(const bitwise_not<T>& l, const bitwise_not<T>& r) { return bitwise_not<T>(l.neg | r.neg); } template<typename T> INL const bitwise_not<T> operator|(const bitwise_not<T>& l, const bitwise_not<T>& r) { return bitwise_not<T>(l.neg & r.neg); } template<typename T> INL const T operator^(const bitwise_not<T>& l, const bitwise_not<T>& r) { return l.neg ^ r.neg; } template <typename T> INL const T apply_mask(const T& in, const T& mask, zero_t) { return cond(mask, in, T(zero_t{})); } template <typename T> INL const T apply_mask(const T& in, const T& mask, typename T::fp_t neutral_value) { return cond(mask, in, T(neutral_value)); } template <typename T> INL const T apply_mask(const T& in, const T& mask, typename T::mask_t neutral_mask) { return cond(mask, in, T(neutral_mask)); } template <typename T> INL const T apply_mask(const T& in, const T& mask, const T& neutral_value_vector) { return cond(mask, in, neutral_value_vector); } // // provides access to min, max, operator+, operator* before they have been declared // template <typename T> struct operators { static INL const T min_(const T& l, const T& r) { return min(l, r); } static INL const T max_(const T& l, const T& r) { return max(l, r); } static INL const T add_(const T& l, const T& r) { return l + r; } static INL const T mul_(const T& l, const T& r) { return l * r; } }; // // base class for horizontal<T> // template <typename T> struct horizontal_impl_base { using unary_op_t = ptr<const T(const T& in)>; using binary_op_t = ptr<const T(const T& l, const T& r)>; using fp_t = typename T::fp_t; using reduce_find_t = std::pair<fp_t, uint>; using ops = operators<T>; template <binary_op_t F> static INL fp_t reduce(const T& in) { return reduce_vector<F>(in).front(); } template <binary_op_t F> static INL const T reduce_vector(const T& in) { return horizontal_impl<T>::template reduce_vector<F>(in); } template <binary_op_t F> static INL reduce_find_t reduce_find(const T& in) { auto in_reduced = reduce_vector<F>(in); auto selected = horizontal_impl<T>::find(in == in_reduced); return std::make_pair(in_reduced.front(), selected); } template <binary_op_t F, typename N> static INL fp_t reduce_with_mask(const T& in, const T& mask, N&& neutral_value) { return reduce<F>(apply_mask(in, mask, std::forward<N>(neutral_value))); } template <binary_op_t F, typename N> static INL reduce_find_t reduce_find_with_mask(const T& in, const T& mask, N&& neutral_value) { return reduce_find<F>(apply_mask(in, mask, std::forward<N>(neutral_value))); } static INL fp_t min(const T& in) { return reduce<ops::min_>(in); } static INL fp_t max(const T& in) { return reduce<ops::max_>(in); } static INL fp_t sum(const T& in) { return reduce<ops::add_>(in); } static INL fp_t product(const T& in) { return reduce<ops::mul_>(in); } static INL reduce_find_t min_find(const T& in) { return reduce_find<ops::min_>(in); } static INL reduce_find_t max_find(const T& in) { return reduce_find<ops::max_>(in); } static INL fp_t min_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::min_>(in, mask, std::numeric_limits<fp_t>::max()); } static INL fp_t max_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::max_>(in, mask, std::numeric_limits<fp_t>::min()); } static INL fp_t sum_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::add_>(in, mask, zero_t{}); } static INL fp_t product_with_mask(const T& in, const T& mask) { return reduce_with_mask<ops::add_>(in, mask, fp_t(1)); } static INL reduce_find_t min_find_with_mask(const T& in, const T& mask) { return reduce_find_with_mask<ops::min_>(in, mask, std::numeric_limits<fp_t>::max()); } static INL reduce_find_t max_find_with_mask(const T& in, const T& mask) { return reduce_find_with_mask<ops::max_>(in, mask, std::numeric_limits<fp_t>::min()); } }; } #undef INL #endif // SIMDIFY_COMMON <|endoftext|>
<commit_before>/** * Render Pipeline C++ * * Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> * Copyright (c) 2016-2017 Center of Human-centered Interaction for Coexistence. * * 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 "environment_capture_stage.hpp" #include <graphicsBuffer.h> #include <render_pipeline/rpcore/render_pipeline.hpp> #include <render_pipeline/rpcore/render_target.hpp> #include <render_pipeline/rpcore/globals.hpp> #include <render_pipeline/rpcore/native/tag_state_manager.h> #include <render_pipeline/rpcore/util/task_scheduler.hpp> #include "environment_probe.hpp" namespace rpplugins { EnvironmentCaptureStage::RequireType EnvironmentCaptureStage::required_inputs = { "DefaultEnvmap", "AllLightsData", "maxLightIndex" }; EnvironmentCaptureStage::RequireType EnvironmentCaptureStage::required_pipes; EnvironmentCaptureStage::EnvironmentCaptureStage(rpcore::RenderPipeline& pipeline): RenderStage(pipeline, "EnvironmentCaptureStage") { rig_node = rpcore::Globals::render.attach_new_node("EnvmapCamRig"); _pta_index = PTA_int::empty_array(1); } void EnvironmentCaptureStage::create() { _target = create_target("CaptureScene"); _target->set_size(_resolution * 6, _resolution); _target->add_depth_attachment(16); _target->add_color_attachment(16, true); _target->prepare_render(NodePath()); // Remove all unused display regions GraphicsBuffer* internal_buffer = _target->get_internal_buffer(); internal_buffer->remove_all_display_regions(); internal_buffer->disable_clears(); internal_buffer->get_overlay_display_region()->disable_clears(); setup_camera_rig(); create_store_targets(); create_filter_targets(); } void EnvironmentCaptureStage::setup_camera_rig() { const LVecBase3f directions[6] = { LVecBase3f(1, 0, 0), LVecBase3f(-1, 0, 0), LVecBase3f(0, 1, 0), LVecBase3f(0, -1, 0), LVecBase3f(0, 0, 1), LVecBase3f(0, 0, -1),}; // Prepare the display regions for (size_t i = 0; i < std::extent<decltype(directions)>::value; ++i) { DisplayRegion* region = _target->get_internal_buffer()->make_display_region( i / 6.0f, i / 6.0f + 1 / 6.0f, 0.0f, 1.0f); region->set_sort(25 + i); region->set_active(true); region->disable_clears(); // Set the correct clears region->set_clear_depth_active(true); region->set_clear_depth(1.0f); region->set_clear_color_active(true); region->set_clear_color(LColorf(0)); PT(PerspectiveLens) lens = new PerspectiveLens; lens->set_fov(90.0f); lens->set_near_far(0.001f, 1.0f); PT(Camera) camera = new Camera(std::string("EnvmapCam-") + std::to_string(i), lens); NodePath camera_np = rig_node.attach_new_node(camera); camera_np.look_at(camera_np, directions[i]); region->set_camera(camera_np); regions.push_back(region); cameras.push_back(camera_np); } cameras[0].set_r(90); cameras[1].set_r(-90); cameras[3].set_r(180); cameras[5].set_r(180); // Register cameras for (NodePath& camera_np :cameras) pipeline_.get_tag_mgr()->register_camera("envmap", DCAST(Camera, camera_np.node())); } void EnvironmentCaptureStage::create_store_targets() { _target_store = create_target("StoreCubemap"); _target_store->set_size(_resolution * 6, _resolution); _target_store->prepare_buffer(); _target_store->set_shader_input(ShaderInput("SourceTex", _target->get_color_tex())); _target_store->set_shader_input(ShaderInput("DestTex", _storage_tex)); _target_store->set_shader_input(ShaderInput("currentIndex", _pta_index)); _temporary_diffuse_map = rpcore::Image::create_cube("DiffuseTemp", _resolution, "RGBA16"); _target_store_diff = create_target("StoreCubemapDiffuse"); _target_store_diff->set_size(_resolution * 6, _resolution); _target_store_diff->prepare_buffer(); _target_store_diff->set_shader_input(ShaderInput("SourceTex", _target->get_color_tex())); _target_store_diff->set_shader_input(ShaderInput("DestTex", _temporary_diffuse_map->get_texture())); _target_store_diff->set_shader_input(ShaderInput("currentIndex", _pta_index)); } void EnvironmentCaptureStage::create_filter_targets() { int mip = 0; int size = _resolution; while (size > 1) { size = size / 2; mip += 1; const std::string string_size(std::to_string(size)); auto target = create_target(std::string("FilterCubemap:") + std::to_string(mip) + "-" + string_size + "x" + string_size); target->set_size(size * 6, size); target->prepare_buffer(); target->set_shader_input(ShaderInput("currentIndex", _pta_index)); target->set_shader_input(ShaderInput("currentMip", LVecBase4i(mip, 0, 0, 0))); target->set_shader_input(ShaderInput("SourceTex", _storage_tex)); target->set_shader_input(ShaderInput("DestTex", _storage_tex, false, true, -1, mip, 0)); _filter_targets.push_back(target); } // Target to filter the diffuse cubemap _filter_diffuse_target = create_target("FilterCubemapDiffuse"); _filter_diffuse_target->set_size(_diffuse_resolution * 6, _diffuse_resolution); _filter_diffuse_target->prepare_buffer(); _filter_diffuse_target->set_shader_input(ShaderInput("SourceTex", _temporary_diffuse_map->get_texture())); _filter_diffuse_target->set_shader_input(ShaderInput("DestTex", _storage_tex_diffuse)); _filter_diffuse_target->set_shader_input(ShaderInput("currentIndex", _pta_index)); } void EnvironmentCaptureStage::update() { // First, disable all targets for (const auto& id_target: get_targets()) id_target.second->set_active(false); // Check for updated faces for (size_t i = 0, i_end=regions.size(); i < i_end; ++i) if (pipeline_.get_task_scheduler()->is_scheduled(std::string("envprobes_capture_envmap_face") + std::to_string(i))) regions[i]->set_active(true); // Check for filtering if (pipeline_.get_task_scheduler()->is_scheduled("envprobes_filter_and_store_envmap")) { _target_store->set_active(true); _target_store_diff->set_active(true); _filter_diffuse_target->set_active(true); for (auto&& target: _filter_targets) target->set_active(true); } } void EnvironmentCaptureStage::set_shader_input(const ShaderInput& inp) { rpcore::Globals::render.set_shader_input(inp); } void EnvironmentCaptureStage::set_probe(EnvironmentProbe* probe) { rig_node.set_mat(probe->get_matrix()); _pta_index[0] = probe->get_index(); } void EnvironmentCaptureStage::reload_shaders() { _target_store->set_shader(load_plugin_shader({"store_cubemap.frag.glsl"})); _target_store_diff->set_shader(load_plugin_shader({"store_cubemap_diffuse.frag.glsl"})); _filter_diffuse_target->set_shader(load_plugin_shader({"filter_cubemap_diffuse.frag.glsl"})); for (size_t i=0, i_end=_filter_targets.size(); i < i_end; ++i) _filter_targets[i]->set_shader(load_plugin_shader({std::string("mips/") + std::to_string(i) + ".autogen.glsl"})); } std::string EnvironmentCaptureStage::get_plugin_id() const { return RPPLUGIN_ID_STRING; } } // namespace rpplugins <commit_msg>Fix IESDatasetTex error message<commit_after>/** * Render Pipeline C++ * * Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> * Copyright (c) 2016-2017 Center of Human-centered Interaction for Coexistence. * * 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 "environment_capture_stage.hpp" #include <graphicsBuffer.h> #include <render_pipeline/rpcore/render_pipeline.hpp> #include <render_pipeline/rpcore/render_target.hpp> #include <render_pipeline/rpcore/globals.hpp> #include <render_pipeline/rpcore/native/tag_state_manager.h> #include <render_pipeline/rpcore/util/task_scheduler.hpp> #include "environment_probe.hpp" namespace rpplugins { EnvironmentCaptureStage::RequireType EnvironmentCaptureStage::required_inputs = { "DefaultEnvmap", "AllLightsData", "maxLightIndex", "IESDatasetTex" }; EnvironmentCaptureStage::RequireType EnvironmentCaptureStage::required_pipes; EnvironmentCaptureStage::EnvironmentCaptureStage(rpcore::RenderPipeline& pipeline): RenderStage(pipeline, "EnvironmentCaptureStage") { rig_node = rpcore::Globals::render.attach_new_node("EnvmapCamRig"); _pta_index = PTA_int::empty_array(1); } void EnvironmentCaptureStage::create() { _target = create_target("CaptureScene"); _target->set_size(_resolution * 6, _resolution); _target->add_depth_attachment(16); _target->add_color_attachment(16, true); _target->prepare_render(NodePath()); // Remove all unused display regions GraphicsBuffer* internal_buffer = _target->get_internal_buffer(); internal_buffer->remove_all_display_regions(); internal_buffer->disable_clears(); internal_buffer->get_overlay_display_region()->disable_clears(); setup_camera_rig(); create_store_targets(); create_filter_targets(); } void EnvironmentCaptureStage::setup_camera_rig() { const LVecBase3f directions[6] = { LVecBase3f(1, 0, 0), LVecBase3f(-1, 0, 0), LVecBase3f(0, 1, 0), LVecBase3f(0, -1, 0), LVecBase3f(0, 0, 1), LVecBase3f(0, 0, -1),}; // Prepare the display regions for (size_t i = 0; i < std::extent<decltype(directions)>::value; ++i) { DisplayRegion* region = _target->get_internal_buffer()->make_display_region( i / 6.0f, i / 6.0f + 1 / 6.0f, 0.0f, 1.0f); region->set_sort(25 + i); region->set_active(true); region->disable_clears(); // Set the correct clears region->set_clear_depth_active(true); region->set_clear_depth(1.0f); region->set_clear_color_active(true); region->set_clear_color(LColorf(0)); PT(PerspectiveLens) lens = new PerspectiveLens; lens->set_fov(90.0f); lens->set_near_far(0.001f, 1.0f); PT(Camera) camera = new Camera(std::string("EnvmapCam-") + std::to_string(i), lens); NodePath camera_np = rig_node.attach_new_node(camera); camera_np.look_at(camera_np, directions[i]); region->set_camera(camera_np); regions.push_back(region); cameras.push_back(camera_np); } cameras[0].set_r(90); cameras[1].set_r(-90); cameras[3].set_r(180); cameras[5].set_r(180); // Register cameras for (NodePath& camera_np :cameras) pipeline_.get_tag_mgr()->register_camera("envmap", DCAST(Camera, camera_np.node())); } void EnvironmentCaptureStage::create_store_targets() { _target_store = create_target("StoreCubemap"); _target_store->set_size(_resolution * 6, _resolution); _target_store->prepare_buffer(); _target_store->set_shader_input(ShaderInput("SourceTex", _target->get_color_tex())); _target_store->set_shader_input(ShaderInput("DestTex", _storage_tex)); _target_store->set_shader_input(ShaderInput("currentIndex", _pta_index)); _temporary_diffuse_map = rpcore::Image::create_cube("DiffuseTemp", _resolution, "RGBA16"); _target_store_diff = create_target("StoreCubemapDiffuse"); _target_store_diff->set_size(_resolution * 6, _resolution); _target_store_diff->prepare_buffer(); _target_store_diff->set_shader_input(ShaderInput("SourceTex", _target->get_color_tex())); _target_store_diff->set_shader_input(ShaderInput("DestTex", _temporary_diffuse_map->get_texture())); _target_store_diff->set_shader_input(ShaderInput("currentIndex", _pta_index)); } void EnvironmentCaptureStage::create_filter_targets() { int mip = 0; int size = _resolution; while (size > 1) { size = size / 2; mip += 1; const std::string string_size(std::to_string(size)); auto target = create_target(std::string("FilterCubemap:") + std::to_string(mip) + "-" + string_size + "x" + string_size); target->set_size(size * 6, size); target->prepare_buffer(); target->set_shader_input(ShaderInput("currentIndex", _pta_index)); target->set_shader_input(ShaderInput("currentMip", LVecBase4i(mip, 0, 0, 0))); target->set_shader_input(ShaderInput("SourceTex", _storage_tex)); target->set_shader_input(ShaderInput("DestTex", _storage_tex, false, true, -1, mip, 0)); _filter_targets.push_back(target); } // Target to filter the diffuse cubemap _filter_diffuse_target = create_target("FilterCubemapDiffuse"); _filter_diffuse_target->set_size(_diffuse_resolution * 6, _diffuse_resolution); _filter_diffuse_target->prepare_buffer(); _filter_diffuse_target->set_shader_input(ShaderInput("SourceTex", _temporary_diffuse_map->get_texture())); _filter_diffuse_target->set_shader_input(ShaderInput("DestTex", _storage_tex_diffuse)); _filter_diffuse_target->set_shader_input(ShaderInput("currentIndex", _pta_index)); } void EnvironmentCaptureStage::update() { // First, disable all targets for (const auto& id_target: get_targets()) id_target.second->set_active(false); // Check for updated faces for (size_t i = 0, i_end=regions.size(); i < i_end; ++i) if (pipeline_.get_task_scheduler()->is_scheduled(std::string("envprobes_capture_envmap_face") + std::to_string(i))) regions[i]->set_active(true); // Check for filtering if (pipeline_.get_task_scheduler()->is_scheduled("envprobes_filter_and_store_envmap")) { _target_store->set_active(true); _target_store_diff->set_active(true); _filter_diffuse_target->set_active(true); for (auto&& target: _filter_targets) target->set_active(true); } } void EnvironmentCaptureStage::set_shader_input(const ShaderInput& inp) { rpcore::Globals::render.set_shader_input(inp); } void EnvironmentCaptureStage::set_probe(EnvironmentProbe* probe) { rig_node.set_mat(probe->get_matrix()); _pta_index[0] = probe->get_index(); } void EnvironmentCaptureStage::reload_shaders() { _target_store->set_shader(load_plugin_shader({"store_cubemap.frag.glsl"})); _target_store_diff->set_shader(load_plugin_shader({"store_cubemap_diffuse.frag.glsl"})); _filter_diffuse_target->set_shader(load_plugin_shader({"filter_cubemap_diffuse.frag.glsl"})); for (size_t i=0, i_end=_filter_targets.size(); i < i_end; ++i) _filter_targets[i]->set_shader(load_plugin_shader({std::string("mips/") + std::to_string(i) + ".autogen.glsl"})); } std::string EnvironmentCaptureStage::get_plugin_id() const { return RPPLUGIN_ID_STRING; } } // namespace rpplugins <|endoftext|>
<commit_before>#include "sbt.h" #include <llvm/Bitcode/BitcodeWriter.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCContext.h> #include <llvm/MC/MCDisassembler/MCDisassembler.h> #include <llvm/MC/MCInstrInfo.h> #include <llvm/MC/MCObjectFileInfo.h> #include <llvm/MC/MCRegisterInfo.h> #include <llvm/Object/Binary.h> #include <llvm/Object/ObjectFile.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Signals.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Target/TargetMachine.h> using namespace llvm; namespace sbt { void SBT::init() { BIN_NAME = new std::string("riscv-sbt"); // print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(*BIN_NAME); InitializeAllTargetInfos(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllDisassemblers(); } void SBT::finish() { delete BIN_NAME; llvm_shutdown(); } Expected<SBT> SBT::create( const llvm::cl::list<std::string> &InputFiles, const std::string &OutputFile) { Error Err = Error::success(); SBT S(InputFiles, OutputFile, Err); if (Err) return std::move(Err); return std::move(S); } const std::string *SBT::BIN_NAME = nullptr; SBT::SBT( const cl::list<std::string> &InputFilesList, const std::string &OutputFile, Error &E) : OutputFile(OutputFile), Context(new LLVMContext), Builder(*Context), Module(new llvm::Module("main", *Context)) { for (auto File : InputFilesList) { if (!sys::fs::exists(File)) { SBTError SE(File); SE << "No such file.\n"; E = make_error<SBTError>(std::move(SE)); return; } InputFiles.push_back(File); } } Error SBT::genHello() { // constants static const int SYS_EXIT = 1; static const int SYS_WRITE = 4; // types Type *Int8 = Type::getInt8Ty(*Context); Type *Int32 = Type::getInt32Ty(*Context); // syscall FunctionType *FTSyscall = FunctionType::get(Int32, { Int32, Int32 }, VAR_ARG); Function *FSyscall = Function::Create(FTSyscall, Function::ExternalLinkage, "syscall", &*Module); // set data std::string Hello("Hello, World!\n"); GlobalVariable *Msg = new GlobalVariable( *Module, ArrayType::get(Int8, Hello.size()), CONSTANT, GlobalVariable::PrivateLinkage, ConstantDataArray::getString(*Context, Hello.c_str(), !ADD_NULL), "msg"); // _start FunctionType *FTStart = FunctionType::get(Int32, {}, !VAR_ARG); Function *FStart = Function::Create(FTStart, Function::ExternalLinkage, "_start", &*Module); // entry basic block BasicBlock *BB = BasicBlock::Create(*Context, "entry", FStart); Builder.SetInsertPoint(BB); // call write Value *SC = ConstantInt::get(Int32, APInt(32, SYS_WRITE, SIGNED)); Value *FD = ConstantInt::get(Int32, APInt(32, 1, SIGNED)); Value *Ptr = Msg; Value *Len = ConstantInt::get(Int32, APInt(32, Hello.size(), SIGNED)); std::vector<Value *> Args = { SC, FD, Ptr, Len }; Builder.CreateCall(FSyscall, Args); // call exit SC = ConstantInt::get(Int32, APInt(32, SYS_EXIT, SIGNED)); Value *RC = ConstantInt::get(Int32, APInt(32, 0, SIGNED)); Args = { SC, RC }; Builder.CreateCall(FSyscall, Args); Builder.CreateRet(RC); return Error::success(); } Error SBT::run() { // genHello(); for (auto &F : InputFiles) { Error E = translate(F); if (E) return E; } return Error::success(); } void SBT::write() { std::error_code EC; raw_fd_ostream OS(OutputFile, EC, sys::fs::F_None); WriteBitcodeToFile(&*Module, OS); OS.flush(); } Error SBT::translate(const std::string &File) { SBTError SE(File); auto E = [&SE](){ return make_error<SBTError>(std::move(SE)); }; // attempt to open the binary. Expected<object::OwningBinary<object::Binary>> Exp = object::createBinary(File); if (!Exp) return Exp.takeError(); object::OwningBinary<object::Binary> &OB = Exp.get(); object::Binary *Bin = OB.getBinary(); if (!object::ObjectFile::classof(Bin)) { SE << "Unrecognized file type.\n"; return E(); } object::ObjectFile *OBJ = dyn_cast<object::ObjectFile>(Bin); outs() << OBJ->getFileName() << ": file format: " << OBJ->getFileFormatName() << "\n"; // get target Triple Triple("riscv32-unknown-elf"); Triple.setArch(Triple::ArchType(OBJ->getArch())); std::string TripleName = Triple.getTriple(); outs() << "Triple: " << TripleName << "\n"; std::string StrError; const Target *Target = TargetRegistry::lookupTarget(TripleName, StrError); if (!Target) { SE << "Target not found: " << TripleName << ": " << StrError << "\n"; return E(); } std::unique_ptr<const MCRegisterInfo> MRI( Target->createMCRegInfo(TripleName)); if (!MRI) { SE << "No register info for target " << TripleName << "\n"; return E(); } // Set up disassembler. std::unique_ptr<const MCAsmInfo> AsmInfo( Target->createMCAsmInfo(*MRI, TripleName)); if (!AsmInfo) { SE << "No assembly info for target " << TripleName << "\n"; return E(); } SubtargetFeatures Features; std::unique_ptr<const MCSubtargetInfo> STI( Target->createMCSubtargetInfo(TripleName, "", Features.getString())); if (!STI) { SE << "No subtarget info for target " << TripleName << "\n"; return E(); } std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); std::unique_ptr<const MCDisassembler> DisAsm( Target->createMCDisassembler(*STI, Ctx)); if (!DisAsm) { SE << "No disassembler for target " << TripleName << "\n"; return E(); } std::unique_ptr<const MCInstrInfo> MII(Target->createMCInstrInfo()); if (!MII) { SE << "No instruction info for target " << TripleName << "\n"; return E(); } return Error::success(); } /// SBTError /// char SBTError::ID = 'S'; /// void handleError(Error &&E) { Error E2 = llvm::handleErrors(std::move(E), [](const SBTError &SE) { // errs() << "SBTError:\n"; SE.log(errs()); errs().flush(); std::exit(EXIT_FAILURE); }); if (E2) { logAllUnhandledErrors(std::move(E2), errs(), *SBT::BIN_NAME + ": error: "); std::exit(EXIT_FAILURE); } } } // sbt int main(int argc, char *argv[]) { // test(); // ExitOnError ExitOnErr; // options cl::list<std::string> InputFiles( cl::Positional, cl::desc("<input object files>"), cl::OneOrMore); cl::opt<std::string> OutputFileOpt( "o", cl::desc("output filename")); // parse args cl::ParseCommandLineOptions(argc, argv); std::string OutputFile; if (OutputFileOpt.empty()) { OutputFile = "x86-" + InputFiles.front(); // remove file extension OutputFile = OutputFile.substr(0, OutputFile.find_last_of('.')) + ".bc"; } else OutputFile = OutputFileOpt; // start SBT sbt::SBT::init(); struct SBTFinish { ~SBTFinish() { sbt::SBT::finish(); } } Finish; Expected<sbt::SBT> Exp = sbt::SBT::create(InputFiles, OutputFile); if (!Exp) sbt::handleError(Exp.takeError()); sbt::SBT &SBT = Exp.get(); sbt::handleError(SBT.run()); SBT.dump(); errs() << "Error: Incomplete translation\n"; std::exit(EXIT_FAILURE); SBT.write(); return EXIT_SUCCESS; } <commit_msg>Trying to make RISCV disassembler work.<commit_after>#include "sbt.h" #include <llvm/Bitcode/BitcodeWriter.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCContext.h> #include <llvm/MC/MCDisassembler/MCDisassembler.h> #include <llvm/MC/MCInstrInfo.h> #include <llvm/MC/MCObjectFileInfo.h> #include <llvm/MC/MCRegisterInfo.h> #include <llvm/Object/Binary.h> #include <llvm/Object/ELF.h> #include <llvm/Object/MachO.h> #include <llvm/Object/ObjectFile.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Signals.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Target/TargetMachine.h> using namespace llvm; namespace sbt { void SBT::init() { BIN_NAME = new std::string("riscv-sbt"); // print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(*BIN_NAME); InitializeAllTargetInfos(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllDisassemblers(); } void SBT::finish() { delete BIN_NAME; llvm_shutdown(); } Expected<SBT> SBT::create( const llvm::cl::list<std::string> &InputFiles, const std::string &OutputFile) { Error Err = Error::success(); SBT S(InputFiles, OutputFile, Err); if (Err) return std::move(Err); return std::move(S); } const std::string *SBT::BIN_NAME = nullptr; SBT::SBT( const cl::list<std::string> &InputFilesList, const std::string &OutputFile, Error &E) : OutputFile(OutputFile), Context(new LLVMContext), Builder(*Context), Module(new llvm::Module("main", *Context)) { for (auto File : InputFilesList) { if (!sys::fs::exists(File)) { SBTError SE(File); SE << "No such file.\n"; E = make_error<SBTError>(std::move(SE)); return; } InputFiles.push_back(File); } } Error SBT::genHello() { // constants static const int SYS_EXIT = 1; static const int SYS_WRITE = 4; // types Type *Int8 = Type::getInt8Ty(*Context); Type *Int32 = Type::getInt32Ty(*Context); // syscall FunctionType *FTSyscall = FunctionType::get(Int32, { Int32, Int32 }, VAR_ARG); Function *FSyscall = Function::Create(FTSyscall, Function::ExternalLinkage, "syscall", &*Module); // set data std::string Hello("Hello, World!\n"); GlobalVariable *Msg = new GlobalVariable( *Module, ArrayType::get(Int8, Hello.size()), CONSTANT, GlobalVariable::PrivateLinkage, ConstantDataArray::getString(*Context, Hello.c_str(), !ADD_NULL), "msg"); // _start FunctionType *FTStart = FunctionType::get(Int32, {}, !VAR_ARG); Function *FStart = Function::Create(FTStart, Function::ExternalLinkage, "_start", &*Module); // entry basic block BasicBlock *BB = BasicBlock::Create(*Context, "entry", FStart); Builder.SetInsertPoint(BB); // call write Value *SC = ConstantInt::get(Int32, APInt(32, SYS_WRITE, SIGNED)); Value *FD = ConstantInt::get(Int32, APInt(32, 1, SIGNED)); Value *Ptr = Msg; Value *Len = ConstantInt::get(Int32, APInt(32, Hello.size(), SIGNED)); std::vector<Value *> Args = { SC, FD, Ptr, Len }; Builder.CreateCall(FSyscall, Args); // call exit SC = ConstantInt::get(Int32, APInt(32, SYS_EXIT, SIGNED)); Value *RC = ConstantInt::get(Int32, APInt(32, 0, SIGNED)); Args = { SC, RC }; Builder.CreateCall(FSyscall, Args); Builder.CreateRet(RC); return Error::success(); } Error SBT::run() { // genHello(); for (auto &F : InputFiles) { Error E = translate(F); if (E) return E; } return Error::success(); } void SBT::write() { std::error_code EC; raw_fd_ostream OS(OutputFile, EC, sys::fs::F_None); WriteBitcodeToFile(&*Module, OS); OS.flush(); } static Expected<std::vector<std::pair<uint64_t, StringRef>>> getSymbolsList(const object::ObjectFile *Obj, const object::SectionRef &Section) { uint64_t SectionAddr = Section.getAddress(); std::error_code EC; // Make a list of all the symbols in this section. std::vector<std::pair<uint64_t, StringRef>> Symbols; for (auto Symbol : Obj->symbols()) { if (!Section.containsSymbol(Symbol)) continue; auto Exp = Symbol.getAddress(); if (!Exp) return Exp.takeError(); auto &Address = Exp.get(); Address -= SectionAddr; auto Exp2 = Symbol.getName(); if (!Exp2) return Exp2.takeError(); auto &Name = Exp2.get(); Symbols.push_back(std::make_pair(Address, Name)); } // Sort the symbols by address, just in case they didn't come in that way. array_pod_sort(Symbols.begin(), Symbols.end()); return Symbols; } static uint64_t getELFOffset(const object::SectionRef &Section) { object::DataRefImpl Sec = Section.getRawDataRefImpl(); auto sec = reinterpret_cast< const object::Elf_Shdr_Impl< object::ELFType<support::little, false>> *>(Sec.p); return sec->sh_offset; } Error SBT::translate(const std::string &File) { SBTError SE(File); auto E = [&SE](){ return make_error<SBTError>(std::move(SE)); }; // attempt to open the binary. Expected<object::OwningBinary<object::Binary>> Exp = object::createBinary(File); if (!Exp) return Exp.takeError(); object::OwningBinary<object::Binary> &OB = Exp.get(); object::Binary *Bin = OB.getBinary(); if (!object::ObjectFile::classof(Bin)) { SE << "Unrecognized file type.\n"; return E(); } object::ObjectFile *Obj = dyn_cast<object::ObjectFile>(Bin); outs() << Obj->getFileName() << ": file format: " << Obj->getFileFormatName() << "\n"; // get target Triple Triple("riscv32-unknown-elf"); Triple.setArch(Triple::ArchType(Obj->getArch())); std::string TripleName = Triple.getTriple(); outs() << "Triple: " << TripleName << "\n"; std::string StrError; const Target *Target = TargetRegistry::lookupTarget(TripleName, StrError); if (!Target) { SE << "Target not found: " << TripleName << ": " << StrError << "\n"; return E(); } std::unique_ptr<const MCRegisterInfo> MRI( Target->createMCRegInfo(TripleName)); if (!MRI) { SE << "No register info for target " << TripleName << "\n"; return E(); } // Set up disassembler. std::unique_ptr<const MCAsmInfo> AsmInfo( Target->createMCAsmInfo(*MRI, TripleName)); if (!AsmInfo) { SE << "No assembly info for target " << TripleName << "\n"; return E(); } SubtargetFeatures Features; std::unique_ptr<const MCSubtargetInfo> STI( Target->createMCSubtargetInfo(TripleName, "", Features.getString())); if (!STI) { SE << "No subtarget info for target " << TripleName << "\n"; return E(); } std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); std::unique_ptr<const MCDisassembler> DisAsm( Target->createMCDisassembler(*STI, Ctx)); if (!DisAsm) { SE << "No disassembler for target " << TripleName << "\n"; return E(); } std::unique_ptr<const MCInstrInfo> MII(Target->createMCInstrInfo()); if (!MII) { SE << "No instruction info for target " << TripleName << "\n"; return E(); } // sections for (const object::SectionRef &Section : Obj->sections()) { if (!Section.isText()) continue; uint64_t SectionAddr = Section.getAddress(); StringRef SegmentName = ""; if (const object::MachOObjectFile *MachO = dyn_cast<const object::MachOObjectFile>(Obj)) { object::DataRefImpl DR = Section.getRawDataRefImpl(); SegmentName = MachO->getSectionFinalSegmentName(DR); } StringRef Name; std::error_code EC = Section.getName(Name); if (EC) { SE << "Failed to get Section Name"; return E(); } #ifndef NDEBUG outs() << "Disassembly of section "; if (!SegmentName.empty()) outs() << SegmentName << ","; outs() << Name << ':'; #endif StringRef BytesStr; EC = Section.getContents(BytesStr); if (EC) { SE << "Failed to get Section Contents"; return E(); } ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), BytesStr.size()); // Make a list of all the symbols in this section. auto Exp = getSymbolsList(Obj, Section); if (!Exp) return Exp.takeError(); auto &Symbols = Exp.get(); // If the section has no symbols just insert a dummy one and disassemble // the whole section. if (Symbols.empty()) Symbols.push_back(std::make_pair(0, Name)); uint64_t SectSize = Section.getSize(); // Disassemble symbol by symbol. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { uint64_t Start = Symbols[si].first; uint64_t End; // The end is either the size of the section or the beginning of the next // symbol. if (si == se - 1) End = SectSize; // Make sure this symbol takes up space. else if (Symbols[si + 1].first != Start) End = Symbols[si + 1].first - 1; else // This symbol has the same address as the next symbol. Skip it. continue; #ifndef NDEBUG outs() << '\n' << Symbols[si].second << ":\n"; #endif #ifndef NDEBUG raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); #else raw_ostream &DebugOut = nulls(); #endif /* uint64_t eoffset = SectionAddr; // Relocatable object if (SectionAddr == 0) // TODO handle errors eoffset = getELFOffset(Section); */ /* if (Symbols[si].second == "main") IP->StartMainFunction(Start + eoffset); else IP->StartFunction( Twine("a").concat(Twine::utohexstr(Start + eoffset)).str(), Start + eoffset); */ // instructions uint64_t Size; outs() << "SectionAddr = " << SectionAddr << "\n"; outs() << "Bytes = " << Bytes.size() << "\n"; for (uint64_t Index = Start; Index < End; Index += Size) { outs() << "Index = " << Index << "\n"; MCInst Inst; // IP->UpdateCurAddr(Index + eoffset); MCDisassembler::DecodeStatus st = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut, nulls()); if (st == MCDisassembler::DecodeStatus::Success) { outs() << "*\n"; Inst.print(outs()); /* #ifndef NDEBUG outs() << format("%8" PRIx64 ":", eoffset + Index); outs() << "\t"; DumpBytes(StringRef(BytesStr.data() + Index, Size)); #endif IP->printInst(&Inst, outs(), ""); #ifdef NDEBUG if (++NumProcessed % 10000 == 0) { outs() << "."; } #endif #ifndef NDEBUG outs() << "\n"; #endif */ } else { SE << "Invalid instruction encoding\n"; return E(); } } // instructions // IP->FinishFunction(); } // symbols } // sections // IP->FinishModule(); // OptimizeAndWriteBitcode(&*IP); return Error::success(); } /// SBTError /// char SBTError::ID = 'S'; /// void handleError(Error &&E) { Error E2 = llvm::handleErrors(std::move(E), [](const SBTError &SE) { // errs() << "SBTError:\n"; SE.log(errs()); errs() << "\n"; errs().flush(); std::exit(EXIT_FAILURE); }); if (E2) { logAllUnhandledErrors(std::move(E2), errs(), *SBT::BIN_NAME + ": error: "); std::exit(EXIT_FAILURE); } } } // sbt int main(int argc, char *argv[]) { // test(); // ExitOnError ExitOnErr; // options cl::list<std::string> InputFiles( cl::Positional, cl::desc("<input object files>"), cl::OneOrMore); cl::opt<std::string> OutputFileOpt( "o", cl::desc("output filename")); // parse args cl::ParseCommandLineOptions(argc, argv); std::string OutputFile; if (OutputFileOpt.empty()) { OutputFile = "x86-" + InputFiles.front(); // remove file extension OutputFile = OutputFile.substr(0, OutputFile.find_last_of('.')) + ".bc"; } else OutputFile = OutputFileOpt; // start SBT sbt::SBT::init(); struct SBTFinish { ~SBTFinish() { sbt::SBT::finish(); } } Finish; Expected<sbt::SBT> Exp = sbt::SBT::create(InputFiles, OutputFile); if (!Exp) sbt::handleError(Exp.takeError()); sbt::SBT &SBT = Exp.get(); sbt::handleError(SBT.run()); SBT.dump(); errs() << "Error: Incomplete translation\n"; std::exit(EXIT_FAILURE); SBT.write(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> using std::string; #include <Exceptions.hpp> using isa::Exceptions::OpenCLError; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::toStringValue; using isa::utils::giga; #include <Kernel.hpp> using isa::OpenCL::Kernel; #include <Observation.hpp> using AstroData::Observation; #ifndef SNR_HPP #define SNR_HPP namespace PulsarSearch { // OpenCL SNR template< typename T > class SNR : public Kernel< T > { public: SNR(string name, string dataType); void generateCode() throw (OpenCLError); void operator()(CLData< T > * input, CLData< T > * output) throw (OpenCLError); inline void setNrDMsPerBlock(unsigned int DMs); inline void setNrPeriodsPerBlock(unsigned int periods); inline void setTransientPipeline(); inline void setPulsarPipeline(); inline void setObservation(Observation< T > * obs); private: cl::NDRange globalSize; cl::NDRange localSize; unsigned int nrDMsPerBlock; unsigned int nrPeriodsPerBlock; bool transientPipeline; bool pulsarPipeline; Observation< T > * observation; }; // Implementation template< typename T > SNR< T >::SNR(string name, string dataType) : Kernel< T >(name, dataType), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), nrDMsPerBlock(0), nrPeriodsPerBlock(0), transientPipeline(false), pulsarPipeline(false), observation(0) {} template< typename T > void SNR< T >::generateCode() throw (OpenCLError) { delete this->code; this->code = new string(); if ( transientPipeline ) { throw OpenCLError("Transient pipeline not implemented."); } else if ( pulsarPipeline ) { // Begin kernel's template string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock); string nrPeriodsPerBlock_s = toStringValue< unsigned int >(nrPeriodsPerBlock); string nrBins_s = toStringValue< unsigned int >(observation->getNrBins()); string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods()); string nrPaddedDMs_s = toStringValue< unsigned int >(observation->getNrPaddedDMs()); string nrBinsInverse_s = toStringValue< float >(1.0f / observation->getNrBins()); *(this->code) = "__kernel void " + this->name + "(__global const " + this->dataType + " * const restrict foldedData, __global " + this->dataType + " * const restrict snrs) {\n" "const unsigned int dm = (get_group_id(0) * " + nrDMsPerBlock_s + ") + get_local_id(0);\n" "const unsigned int period = (get_group_id(1) * " + nrPeriodsPerBlock_s + ") + get_local_id(1);\n" + this->dataType + " average = 0;\n" + this->dataType + " rms = 0;\n" + this->dataType + " max = 0;\n" "\n" "for ( unsigned int bin = 0; bin < " + nrBins_s + "; bin++ ) {\n" "const " + this->dataType + " globalItem = foldedData[(bin * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period * " + nrPaddedDMs_s + ") + dm];\n" "average += globalItem;\n" "rms += (globalItem * globalItem);\n" "max = fmax(max, globalItem);\n" "}\n" "average *= " + nrBinsInverse_s + "f;\n" "rms *= " + nrBinsInverse_s + "f;\n" "snrs[(period * " + nrPaddedDMs_s + ") + dm] = (max - average) / native_sqrt(rms);\n" "}\n"; // End kernel's template globalSize = cl::NDRange(observation->getNrPaddedDMs(), observation->getNrPeriods()); localSize = cl::NDRange(nrDMsPerBlock, nrPeriodsPerBlock); this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * ((observation->getNrBins() * 3) + 4)); this->gb = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * ((observation->getNrBins() * sizeof(T)) + sizeof(T))); } else { throw OpenCLError("Pipeline not implemented."); } this->compile(); } template< typename T > void SNR< T >::operator()(CLData< T > * input, CLData< T > * output) throw (OpenCLError) { this->setArgument(0, *(input->getDeviceData())); this->setArgument(1, *(output->getDeviceData())); this->run(globalSize, localSize); } template< typename T > inline void SNR< T >::setNrDMsPerBlock(unsigned int DMs) { nrDMsPerBlock = DMs; } template< typename T > inline void SNR< T >::setNrPeriodsPerBlock(unsigned int periods) { nrPeriodsPerBlock = periods; } template< typename T > inline void SNR< T >::setTransientPipeline() { transientPipeline = true; pulsarPipeline = false; } template< typename T > inline void SNR< T >::setPulsarPipeline() { pulsarPipeline = true; transientPipeline = false; } template< typename T >inline void SNR< T >::setObservation(Observation< T > *obs) { observation = obs; } } // PulsarSearch #endif // SNR_HPP <commit_msg>Started the refactoring. Added sequential and OpenCL SNR.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <utils.hpp> #include <Observation.hpp> #ifndef SNR_HPP #define SNR_HPP namespace PulsarSearch { // Sequential SNR template< typename T > void snrFoldedTS(const AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs); // OpenCL SNR template< typename T > std::string getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation); // Implementations template< typename T > void snrFoldedTS(AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { T max = 0; float average = 0.0f; float rms = 0.0f; for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { T value = foldedTS[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm]; average += value; rms += (value * value); if ( value > max ) { max = value; } } average /= observation.getNrBins(); rms = sqrt(rms / observation.getNrBins()); snrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) / rms; } } } template< typename T > std::string getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation) { std::string * code = new std::string(); // Begin kernel's template std::string nrPaddedDMs_s = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs()); std::string nrBinsInverse_s = isa::utils::toString< float >(1.0f / observation.getNrBins()); *code = "__kernel void snr(__global const " + dataType + " * const restrict foldedData, __global " + dataType + " * const restrict snrs) {\n" "<%DEF_DM%>" "<%DEF_PERIOD%>" + dataType + " globalItem = 0;\n" + dataType + " average = 0;\n" + dataType + " rms = 0;\n" + dataType + " max = 0;\n" "\n" "<%COMPUTE%>"; std::string defDMsTemplate = "const unsigned int dm<%DM_NUM%> = (get_group_id(0) * " + isa::utils::toString< unsigned int >(nrDMsPerBlock * nrDMsPerThread) + ") + get_local_id(0) + <%DM_NUM%>;\n"; std::string defPeriodsTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + isa::utils::toString< unsigned int >(nrPeriodsPerBlock * nrPeriodsPerThread) + ") + get_local_id(1) + <%PERIOD_NUM%>;\n"; std::string computeTemplate = "average = 0;\n" " rms = 0;\n" " max = 0;\n" "for ( unsigned int bin = 0; bin < " + isa::utils::toString< unsigned int >(observation.getNrBins()) + "; bin++ ) {\n" "globalItem = foldedData[(bin * " + isa::utils::toString< unsigned int >(observation.getNrPeriods()) + " * " + nrPaddedDMs_s + ") + ((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>];\n" "average += globalItem;\n" "rms += (globalItem * globalItem);\n" "max = fmax(max, globalItem);\n" "}\n" "average *= " + nrBinsInverse_s + "f;\n" "rms *= " + nrBinsInverse_s + "f;\n" "snrs[((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>] = (max - average) / native_sqrt(rms);\n" "}\n"; // End kernel's template std::string * defDM_s = new std::string(); std::string * defPeriod_s = new std::string(); std::string * compute_s = new std::string(); for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); std::string * temp_s = 0; temp_s = isa::utils::replace(&defDMsTemplate, "<%DM_NUM%>", dm_s); defDM_s->append(*temp_s); delete temp_s; } for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) { std::string period_s = isa::utils::toString< unsigned int >(period); std::string * temp_s = 0; temp_s = isa::utils::replace(&defPeriodsTemplate, "<%PERIOD_NUM%>", period_s); defPeriod_s->append(*temp_s); delete temp_s; for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); temp_s = isa::utils::replace(&computeTemplate, "<%PERIOD_NUM%>", period_s); temp_s = isa::utils::replace(temp_s, "<%DM_NUM%>", dm_s, true); compute_s->append(*temp_s); delete temp_s; } } code = isa::utils::replace(code, "<%DEF_DM%>", *defDM_s, true); code = isa::utils::replace(code, "<%DEF_PERIOD%>", *defPeriod_s, true); code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true); return code; } } // PulsarSearch #endif // SNR_HPP <|endoftext|>